Click here to Skip to main content
15,897,891 members
Articles / Programming Languages / SQL

How to find a gap in the table between min and max value using pure SQL

Rate me:
Please Sign up or sign in to vote.
5.00/5 (6 votes)
14 Nov 2012CPOL 0  
While Shanalal Kasims solution is cool, it doesn't work when you have a larger gap in the sequence.This is pure SQL and should work for all cases:WITH M AS ( SELECT Max(SEQUENCE) s FROM table1 WHERE id = 1 ),numbers(n) AS ( SELECT 1 AS n UNION ALL...

Alternatives

Members may post updates or alternatives to this current article in order to show different approaches or add new features.

Please Sign up or sign in to vote.
12 Nov 2012Herman<T>.Instance
CREATE FUNCTION [dbo].[GetMissingNumbers](@ID int)RETURNS @MissingNr TABLE(MissingNumber int)ASbegin DECLARE @minValue int DECLARE @maxValue int Declare @checkValue int select @minValue = min(Sequence) from Table1 where ID = @ID select @maxValue = max(Sequence) from Table1...
Please Sign up or sign in to vote.
12 Nov 2012Shanalal Kasim
Use Below queryselect Sequence+1 from Table1 where Sequence+1 not in (select Sequence from Table1 where id = 1) and id = 1 and Sequence not in (select max(Sequence) from Table1 where id = 1)
Please Sign up or sign in to vote.
14 Nov 2012sahabiswarup 5 alternatives  
Here is my tableTable1ID Sequence1 11 31 41 61 81 10and i want this following output2579I've tried thisSELECT Sequence FROM Table1 WHERE Sequence NOT IN ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10') and ID ='1'but it not works.
Please Sign up or sign in to vote.
12 Nov 2012__TR__
If I understand correctly you want to retreive the list of numbers which are not in the sequence for a given ID.Here is one approach. Create a table to hold all the numbers from 1 to 10.CREATE TABLE #Sequence( ID INT)DECLARE @MaxValue INTDECLARE @Value INTSET @Value =...
Please Sign up or sign in to vote.
16 Nov 2012sahabiswarup
select sequence from SequenceTable where sequence NOT IN (select sequence FROM Table1 WHERE id=8)I've created another table named SequenceTable and stored value from 1 to 10 and then applying the above query.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Database Developer
Sweden Sweden
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions