Search code examples
mysql

MySQL get missing IDs from table


I have this table in MySQL, for example:

ID | Name
1  | Bob
4  | Adam
6  | Someguy

If you notice, there is no ID number (2, 3 and 5).

How can I write a query so that MySQL would answer the missing IDs only, in this case: "2,3,5" ?


Solution

  • SELECT a.id+1 AS start, MIN(b.id) - 1 AS end
        FROM testtable AS a, testtable AS b
        WHERE a.id < b.id
        GROUP BY a.id
        HAVING start < MIN(b.id)
    

    Here is some additional reaading on this subject: https://web.archive.org/web/20220706195255/http://www.codediesel.com/mysql/sequence-gaps-in-mysql/