Date spine: fill the missing days
A GROUP BY day only returns the days that have rows: a day without orders is missing, not zero, and a chart, a LAG
or a 7-day average built on it is wrong. Generate the days first (the spine), then join the data onto them.
WITH days AS (
SELECT CAST(d AS DATE) AS day
FROM generate_series(DATE '2025-04-01', DATE '2025-04-30', INTERVAL '1 day') AS t(d)
),
daily AS (
SELECT CAST(ordered_at AS DATE) AS day, COUNT(*) AS orders
FROM orders
GROUP BY CAST(ordered_at AS DATE)
)
SELECT days.day, COALESCE(daily.orders, 0) AS orders
FROM days
LEFT JOIN daily ON daily.day = days.day;
For one row per day and category, CROSS JOIN the days with the categories first. In a real project the spine is a
calendar table (a date dimension), or dbt's dbt_utils.date_spine.
The trap. A COUNT(*) after the LEFT JOIN counts 1 on an empty day, since the day's row is there: aggregate
before joining, as above, or count a column of the joined table. A WHERE on that table's columns removes the empty
days again: put the condition in the ON or inside daily.
On your warehouse. Postgres and DuckDB use generate_series, as above. Snowflake: TABLE(GENERATOR(ROWCOUNT => 30))
with DATEADD(day, ROW_NUMBER() OVER (ORDER BY SEQ4()) - 1, '2025-04-01'::DATE). BigQuery:
UNNEST(GENERATE_DATE_ARRAY('2025-04-01', '2025-04-30')). Databricks:
explode(sequence(DATE'2025-04-01', DATE'2025-04-30')).
The trap
SELECT CAST(ordered_at AS DATE) AS day, COUNT(*) AS orders FROM orders WHERE ordered_at >= DATE '2025-04-08' AND ordered_at < DATE '2025-04-15' GROUP BY CAST(ordered_at AS DATE) ORDER BY day;
| day | orders |
|---|---|
| 2025-04-08 | 6 |
| 2025-04-09 | 6 |
| 2025-04-11 | 3 |
| 2025-04-13 | 5 |
| 2025-04-14 | 5 |
The fix
WITH days AS ( SELECT CAST(d AS DATE) AS day FROM generate_series(DATE '2025-04-08', DATE '2025-04-14', INTERVAL '1 day') AS t(d) ), daily AS ( SELECT CAST(ordered_at AS DATE) AS day, COUNT(*) AS orders FROM orders GROUP BY CAST(ordered_at AS DATE) ) SELECT days.day, COALESCE(daily.orders, 0) AS orders FROM days LEFT JOIN daily ON daily.day = days.day ORDER BY days.day;
| day | orders |
|---|---|
| 2025-04-08 | 6 |
| 2025-04-09 | 6 |
| 2025-04-10 | 0 |
| 2025-04-11 | 3 |
| 2025-04-12 | 0 |
| 2025-04-13 | 5 |
| 2025-04-14 | 5 |