2

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.

Community
  • 1
  • 1
Kimvais
  • 38,306
  • 16
  • 108
  • 142

5 Answers5

8

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

Praveen Prasannan
  • 7,093
  • 10
  • 50
  • 70
4

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;
ajmalmhd04
  • 2,582
  • 6
  • 23
  • 41
  • That is in fact not Oracle specific. It uses standard ANSI SQL window function which would also work in Postgres, SQL Server 2012, DB2 and many other modern DBMS. –  Jul 22 '13 at 09:04
1

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)
agarici
  • 602
  • 1
  • 5
  • 9
0

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
        )
        ;
wildplasser
  • 43,142
  • 8
  • 66
  • 109
0

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
aminj
  • 1
  • 1