SQL - Find missing int values in mostly ordered sequential series

前端 未结 6 626
有刺的猬
有刺的猬 2020-12-06 08:59

I manage a message based system in which a sequence of unique integer ids will be entirely represented at the end of the day, though they will not necessarily arrive in orde

6条回答
  •  感情败类
    2020-12-06 09:13

    You didn't state your DBMS, so I'm assuming PostgreSQL:

    select aid as missing_id
    from generate_series( (select min(id) from message), (select max(id) from message)) as aid
      left join message m on m.id = aid
    where m.id is null;  
    

    This will report any missing value in a sequence between the minimum and maximum id in your table (including gaps that are bigger than one)

    psql (9.1.1)
    Type "help" for help.
    
    postgres=> select * from message;
     id
    ----
      1
      2
      3
      4
      5
      7
      8
      9
     11
     14
    (10 rows)
    
    
    postgres=> select aid as missing_id
    postgres-> from generate_series( (select min(id) from message), (select max(id) from message)) as aid
    postgres->   left join message m on m.id = aid
    postgres-> where m.id is null;
     missing_id
    ------------
              6
             10
             12
             13
    (4 rows)
    postgres=>

提交回复
热议问题