I would like to know a sql query to find all missing dates between two dates , suppose my sql table is as below
ID |
Date |
1 |
2018-1-10 |
2 |
2018-1-12 |
3 |
2018-1-13 |
4 |
2018-1-15 |
5 |
2018-1-17 |
6 |
2018-1-18 |
7 |
2018-1-20 |
8 |
2018-1-21 |
I need to run sql query which will return missing dates from date column like ‘2018-1-11’ , ‘2018-1-14’.
You can use the EXCEPT operator to compare a set of continuous dates to the dates with gaps.
Suppose my table is like below
Then you can use the below SQL command to get the list of missing dates between two dates
DECLARE @MaxDate DATE,
@MinDate DATE,
@iDate DATE
-- SQL Server table variable
DECLARE @DateSequence TABLE(
DATE DATE
)
SELECT @MaxDate = Convert(DATE,Max(Dates)),
@MinDate = Convert(DATE,Min(Dates))
FROM [Students].[dbo].[DatesTable]
SET @iDate = @MinDate
WHILE (@iDate <= @MaxDate)
BEGIN
INSERT @DateSequence
SELECT @iDate
SET @iDate = Convert(DATE,Dateadd(DAY,1,@iDate))
END
SELECT Gaps = DATE
FROM @DateSequence
EXCEPT
SELECT DISTINCT Convert(DATE,Dates)
FROM [Students].[dbo].[DatesTable]
GO
Output:
hope it helps.
If you want to select just dates between two dates, then you can have query
select DateColumn from TableName where Id = 1
and DateColumn between '2021/02/25' and '2021/02/27'
And then you can loop through all dates to find missing dates.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly