Detect missing days in date data
Walk the calendar between the earliest and latest dates and keep the days that have no matching row, so broken feeds show up as holes.
The task
daily_revenue (or any table with one row per day) should be continuous, but the chart has holes. This finds exactly which days are missing.
The snippet
Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.
SELECT d::date AS missing_day
FROM generate_series(
(SELECT MIN(order_date) FROM orders),
(SELECT MAX(order_date) FROM orders),
INTERVAL '1 day'
) AS d
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.order_date = d::date
)
ORDER BY missing_day;
작동 방식
generate_series produces one timestamp per day across the table's date range; casting back to date aligns it with the stored values. NOT EXISTS keeps only days with no order row. If several rows share a day, the anti-join still behaves: it only checks existence, not counts. Engines without generate_series build the calendar with a recursive CTE instead; on SQLite that is the MySQL variant with date(day, '+1 day') as the step.
Variations
MySQL 8.0+: recursive CTE calendar
MySQLWITH RECURSIVE days(day) AS (
SELECT MIN(order_date) FROM orders
UNION ALL
SELECT day + INTERVAL 1 DAY FROM days
WHERE day < (SELECT MAX(order_date) FROM orders)
)
SELECT d.day AS missing_day
FROM days d
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.order_date = d.day
)
ORDER BY d.day;
SQL Server: recursive CTE with DATEADD
SQL ServerWITH bounds AS (
SELECT MIN(order_date) AS first_day, MAX(order_date) AS last_day
FROM orders
),
days(day) AS (
SELECT first_day FROM bounds
UNION ALL
SELECT DATEADD(DAY, 1, d.day)
FROM days d, bounds b
WHERE d.day < b.last_day
)
SELECT d.day AS missing_day
FROM days d
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.order_date = d.day
)
ORDER BY d.day
OPTION (MAXRECURSION 0);
Count missing days per month (PostgreSQL date_trunc)
PostgreSQLWITH RECURSIVE days(day) AS (
SELECT (SELECT MIN(order_date) FROM orders)
UNION ALL
SELECT day + 1 FROM days
WHERE day < (SELECT MAX(order_date) FROM orders)
),
missing AS (
SELECT d.day
FROM days d
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.order_date = d.day
)
)
SELECT date_trunc('month', day)::date AS month_start,
COUNT(*) AS missing_days
FROM missing
GROUP BY 1
ORDER BY 1;
Questions that come up
Why is a missing day suspicious but a missing id not?
Ids can legitimately skip values when transactions roll back, but a calendar gap means no rows exist for a whole day: a load failure, an outage, or a silent filter change. In one-row-per-day tables the sequence is a contract, so every hole is a data-quality defect worth explaining.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.