How I can improve SQL gaps searching code for long tables?

48 views Asked by At

How I can improve (speed up) my code for long tables (1M rows)?

I have a table named names. The data in id's column is 1, 2, 5, 7.

    ID | NAME
    1  | Homer
    2  | Bart
    5  | March
    7  | Lisa

I need to find the missing sequence numbers from the table. My SQL query found the missing sequence numbers from my table. It is similar with problem asked here. But my solution is different. I am expecting results like:

id
----
  3
  4
  6
(3 rows) 

so, my code (for postgreSql):

SELECT series AS id 
FROM generate_series(1, (SELECT ID FROM names ORDER BY ID DESC LIMIT 1), 1)
series LEFT JOIN names ON series = names.id 
WHERE id IS NULL;
1

There are 1 answers

0
Philippe On

Use max(id) to get the biggest one

Result here

SELECT series AS id 
FROM generate_series(1, (select max(id) from names), 1)
series LEFT JOIN names ON series = names.id 
WHERE id IS NULL;