How to find “holes” in a table

后端 未结 10 2190
野趣味
野趣味 2020-12-24 04:28

I recently inherited a database on which one of the tables has the primary key composed of encoded values (Part1*1000 + Part2).
I normalized that column, but I cannot ch

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 05:14

    Many of the previous answer are quite good. However they all miss to return the first value of the sequence and/or miss to consider the lower limit 100000. They all returns intermediate holes but not the very first one (100001 if missing).

    A full solution to the question is the following one:

    select id + 1 as newid from
        (select 100000 as id union select id from tbl) t
        where (id + 1 not in (select id from tbl)) and
              (id >= 100000)
        order by id
        limit 1;
    

    The number 100000 is to be used if the first number of the sequence is 100001 (as in the original question); otherwise it is to be modified accordingly "limit 1" is used in order to have just the first available number instead of the full sequence

提交回复
热议问题