Question

This question explains how to find the first "unused" number in a table, but how can I find the same so that I can define extra constraints. How do I alter the query so that I get the first unused number after that's greater than 100

e.g. If I have 23, 56, 100, 101, 103 in my table i should get 102.

Was it helpful?

Solution

in mysql and postgresql

SELECT  id + 1
FROM    test mo
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    test mi 
        WHERE   mi.id = mo.id + 1
        ) and mo.id> 100
ORDER BY
        id
LIMIT 1

fiddle for mysql and fiddle for postgresql

in ms sql

SELECT  TOP 1
        id + 1
FROM    test mo
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    test mi 
        WHERE   mi.id = mo.id + 1
        )
          and mo.id > 100
ORDER BY
        id

fiddle

OTHER TIPS

In Oracle Sql, you may try:

SELECT id
FROM
     (SELECT ID, lead(ID) OVER(ORDER BY ID) next_val FROM my_table t
     )
WHERE id +1 <> next_val
 AND id      >100;

hope this will help you

SELECT MIN (id) + 1
  FROM myTable T1
 WHERE id >= 100
   AND NOT EXISTS (SELECT *
                     FROM myTable T2
                    WHERE T1.id + 1 = T2.id)

Using generate_series() for fun & profit:

CREATE table islands (num INTEGER NOT NULL PRIMARY KEY);

INSERT INTO islands (num ) VALUES
(23), (56), (100), (101), (103) ;

WITH total AS (
        SELECT generate_series(mima.bot, mima.top) AS num
        FROM ( SELECT MIN(num) AS bot , MAX(num) AS top FROM islands) mima
        )
SELECT num
FROM total tt
WHERE num >=100
AND NOT EXISTS (
        SELECT *
        FROM islands ii
        WHERE ii.num = tt.num
        )
        ;

use this:

SELECT TOP 1 a1.id + 1 FROM test a1 left JOIN test a2 
ON a1.id = a2.id - 1 
WHERE a2.id IS NULL AND a1.id > 100
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top