Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL - check gap in datetime data for every minute

We have a database that records data from a system every minute

+---------+-------------------------+  
| Id      | EntryDate               |     
+---------+-------------------------+   
| 8093562 | 2019-05-17 15:01:25.000 |  
| 8093563 | 2019-05-17 15:02:25.000 |  
| 8093564 | 2019-05-17 15:03:25.000 |  
| 8093565 | 2019-05-17 15:04:25.000 |  
| 8093566 | 2019-05-17 15:05:25.000 |  
| 8093568 | 2019-05-17 15:07:25.000 |  
| 8093569 | 2019-05-17 15:08:25.000 |  
| 8093780 | 2019-05-17 15:09:25.000 |  
| 8093781 | 2019-05-17 15:10:25.000 |  
+---------+-------------------------+   

I am trying to make a query that can find if there is any gap between the minutes. For example in the above data, data at 15:06 is missing.

Can't figure out how to do this in SQL query.

like image 800
Ansar Muhammad Avatar asked Sep 05 '25 03:09

Ansar Muhammad


1 Answers

Using LEAD() with CASE, you can get your expected result:

SELECT ResultDate FROM (
    SELECT CASE WHEN (DATEDIFF(MINUTE, LEAD(EntryDate, 1) OVER(ORDER BY EntryDate),EntryDate) < -1) THEN DATEADD(MINUTE, +1, EntryDate) END AS ResultDate
    FROM TableName
) Q WHERE ResultDate IS NOT NULL

Demo with given sample data:

DECLARE  @TestTable TABLE (Id INT, EntryDate DATETIME);

INSERT INTO @TestTable (Id, EntryDate) VALUES  
(8093562, '2019-05-17 15:01:25.000'),
(8093563, '2019-05-17 15:02:25.000'),
(8093564, '2019-05-17 15:03:25.000'),
(8093565, '2019-05-17 15:04:25.000'),
(8093566, '2019-05-17 15:05:25.000'),
(8093568, '2019-05-17 15:07:25.000'),
(8093569, '2019-05-17 15:08:25.000'),
(8093780, '2019-05-17 15:09:25.000'),
(8093781, '2019-05-17 15:10:25.000');

SELECT ResultDate FROM (
    SELECT CASE WHEN (DATEDIFF(MINUTE, LEAD(EntryDate, 1) OVER(ORDER BY EntryDate),EntryDate) < -1) THEN DATEADD(MINUTE, +1, EntryDate) END AS ResultDate
    FROM @TestTable
) Q WHERE ResultDate IS NOT NULL

Output:

ResultDate
-----------------------
2019-05-17 15:06:25.000

Demo on db<>fiddle

like image 161
Arulkumar Avatar answered Sep 07 '25 21:09

Arulkumar