So let's say I have the following data samples:
Sample 1:
id|name
-------
0 |0
0 |1
0 |2
0 |3
-------
Sample 2:
id|name
-------
0 |0
1 |1
3 |3
4 |4
-------
Sample 3:
id|name
-------
0 |0
1 |1
2 |2
3 |3
-------
What I want is to be able to return the smallest missing value in the sequence, if possible. If not, I want to return the MAX(id)+1
as the available value.
To get the smallest missing value, I do the following:
SELECT temptable.id+1 FROM (
SELECT id, LEAD(id, 1) OVER (ORDER BY id) AS lead FROM mytable) AS temptable
WHERE (lead - id) > 1;
This will return NULL
for Sample 1, 2 for Sample 2, and NULL
for Sample 3.
Now is it possible to first check if temptable.id
is NULL
and if so, return the MAX(mytable.id)
in a single query?