Posts

Showing posts from December, 2018

Find missing sequence number. Get the numbers where sequence is missing.

Most of the time the question was asked while having Database interview that we have number sequence present in a table but some numbers are missing. Can you write the query to detect where number is missing from sequence and if possible then also can get the missing number? OK, it’s not a rocket science so let’s begin. Please give me a paper and a pen to write query Sir. I am using a Temporary variable table here. DECLARE @Temp TABLE (        Id INT IDENTITY ( 1 , 1 ),        Num INT ) INSERT INTO @Temp ( Num ) VALUES ( 1 ) ,( 2 ), ( 4 ), ( 6 ), ( 7 ), ( 9 ) SELECT * FROM @Temp SELECT a . Id , a . Num , b . Num , ( a . Num - b . Num ) as Diff , ( b . Num + 1 ) as MissingNum FROM @Temp a LEFT JOIN @Temp b ON b . Id = ( a . Id - 1 ) WHERE ( a . Num - b . Num ) > 1 You see it’s just a simple SELECT statement but tricky. OK, yes it will produce my result but we do not have any Id field in our database, w