Search code examples
sqlgaps-and-islands

SQL interview question


I got following question on an interview: Given a table of natural numbers with some missing ones, provide output of two tables, beginning of number gap in first table and ending in second. Example:

 ____    ________
|    |   |   |   |
| 1  |   | 3 | 3 |
| 2  |   | 6 | 7 |
| 4  |   | 10| 12|
| 5  |   |___|___|
| 8  |
| 9  |
| 13 |
|____|

Solution

  • While this is pretty much the same as Phil Sandler's answer, this should return two separate tables (and I think it looks cleaner) (it works in SQL Server, at least):

    DECLARE @temp TABLE (num int)
    INSERT INTO @temp VALUES (1),(2),(4),(5),(8),(9),(13)
    
    DECLARE @min INT, @max INT
    SELECT @min = MIN(num), @max = MAX(num) FROM @temp
    
    SELECT t.num + 1 AS range_start
        FROM @temp t
        LEFT JOIN @temp t2 ON t.num + 1 = t2.num
        WHERE t.num < @max AND t2.num IS NULL
    
    SELECT t.num - 1 AS range_end
        FROM @temp t
        LEFT JOIN @temp t2 ON t.num - 1 = t2.num
        WHERE t.num > @min AND t2.num IS NULL