Its possible to return list of dates doesn't having record on one request SQL? Example:
Table A
Id | date. | value |
---|---|---|
1 | 2025-01-02 | 5 |
2 | 2025-01-03 | 6 |
3 | 2025-01-06 | 7 |
4 | 2025-01-09 | 8 |
Its possible to return list of dates doesn't having record on one request SQL? Example:
Table A
Id | date. | value |
---|---|---|
1 | 2025-01-02 | 5 |
2 | 2025-01-03 | 6 |
3 | 2025-01-06 | 7 |
4 | 2025-01-09 | 8 |
I want return list of date who doesn't have record between two dates [dateStart,dateEnd]
For example if dateStard = '2025-01-01' and dateEnd='2025-01-09'
I expect result:
date |
---|
2025-01-04 |
2025-01-05 |
2025-01-07 |
2025-01-08 |
2 Answers
Reset to default 1You can obtain the result by generating the dates and then comparing them with the table to identify the missing ones.
For example let's start from 2025-02-17' The recursive part adds one day to the date, as long as dt is less than the final date.
Then go and select all the dates generated by the recursive part and check where they are not present in the table.
Basically you check if there is no record on those dates.
I hope I explained myself:
WITH RECURSIVE date_series AS (
SELECT DATE_ADD('2025-02-17', INTERVAL 1 DAY) AS dt
UNION ALL
SELECT DATE_ADD(dt, INTERVAL 1 DAY)
FROM date_series
WHERE dt < DATE_SUB('2025-02-27', INTERVAL 1 DAY)
)
SELECT dt AS missing_date
FROM date_series
WHERE dt NOT IN (SELECT date_col FROM A);
My Table:
MariaDB [TEST]> select * from A;
+----+------------+-------+
| id | date_col | value |
+----+------------+-------+
| 1 | 2025-01-02 | 5 |
| 2 | 2025-01-03 | 6 |
| 3 | 2025-01-06 | 7 |
| 4 | 2025-01-08 | 8 |
| 5 | 2025-02-16 | 5 |
| 6 | 2025-02-18 | 6 |
| 7 | 2025-02-20 | 7 |
| 8 | 2025-02-22 | 8 |
+----+------------+-------+
Result from my DB:
+--------------+
| missing_date |
+--------------+
| 2025-02-17 |
| 2025-02-19 |
| 2025-02-21 |
| 2025-02-23 |
| 2025-02-24 |
| 2025-02-25 |
| 2025-02-26 |
+--------------+
I would say:
-- Generate the list of all dates between dateStart and dateEnd. This is really Oracle-specific.
with fromto as
(
select to_date('2025-01-01') + rownum - 1 as d from dual -- Remove the "- 1" if you want to start reporting missing dates from dateStart + 1 instead of dateStart.
connect by to_date('2025-01-01') + rownum - 1 <= to_date('2025-01-09')
)
-- Now keep only those with no match in your data table.
select * from fromto where not exists (select 1 from t where t.d = fromto.d)
order by fromto.d;
See it in a fiddle.
2025-01-01
be part of expected results as well since your date range starts from2025-01-01
? – samhita Commented Feb 17 at 22:42plsql
. PL/SQL is Oracle's programming language. In your request you say you are looking for a SQL solution, though. Please remove the PL/SQL tag and tag the request with your DBMS instead. Are you using Oracle? Is this what you tried to say with that tag? – Thorsten Kettner Commented Feb 18 at 5:52