Introduction
Suppose we have a table called ‘Tree’ with only one column called ‘lemons’ (unsigned int) for a very simple application to document the productivity of our trees. Typical data might be five rows with lemons numbering 0, 1, 2, 3 and 7. Of course, there can be any number of trees and the number of lemons can span the full range of an int.

The Puzzle
Write a pure SQL program that computes the smallest non-negative integer, such that no tree has that number of lemons. In the typical data above, the answer would be 4. Just to standardize, your solution must run in MySQL 4.1.12.

Guidelines

  • Obviously, you could chain an huge tower of subqueries together

    select
    if(
        (select * from min_absent where value = 0 limit 1) is null, 0,
        if(
            (select * from min_absent where value = 1 limit 1) is null, 1,
            if(
                (select * from min_absent where value = 2 limit 1) is null, 2,
                if(
                    (select * from min_absent where value = 3 limit 1) is null, 3,
                    if(
                        (select * from min_absent where value = 4 limit 1) is null, 4,
    ...
                      )
                  )
              )
          )
      ) 

    up to the full range of an int, but this is not elegant.

  • There are also tricks involving creating new (non-temporary) tables. This requires both more permissions, that there be no table name conflicts and it is less ‘lightweight’ and clean than selects. You don’t need to do this, either.

Solution
To come in a few days if no one finds an answer.