Pergunta

In a table I have records with id's 2,4,5,8. How can I receive a list with values 1,3,6,7. I have tried in this way

SELECT t1.id + 1
FROM table t1
WHERE NOT EXISTS (
    SELECT * 
    FROM table t2
    WHERE t2.id = t1.id + 1
)

but it's not working correctly. It doesn't bring all available positions.

Is it possible without another table?

Foi útil?

Solução

You can get all the missing ID's from a recursive CTE, like this:

with recursive numbers as (
  select 1 number
    from rdb$database
  union all
  select number+1
    from rdb$database
         join numbers on numbers.number < 1024
)
select n.number
  from numbers n
 where not exists (select 1 
                     from table t
                    where t.id = n.number)

the number < 1024 condition in my example limit the query to the max 1024 recursion depth. After that, the query will end with an error. If you need more than 1024 consecutive ID's you have either run the query multiple times adjusting the interval of numbers generated or think in a different query that produces consecutive numbers without reaching that level of recursion, which is not too difficult to write.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top