Search code examples
sqlsql-serverqsqlquery

How find last number of sequence numbers in sql?


I want find last number of sequence in sql query for fill automatically suggestion field value. forexample my code field(column) is :1,2,3,4,10,20 so i want found 4 in my query


Solution

  • If your table is called table_name and looks like this:

    id
    1
    2
    3
    4
    10
    20

    Then this should work:

    select min(previd) from 
    (select id, lag(id) over(order by id) as previd
    from table_name) t
    where id - previd > 1;
    

    Fiddle