Part 08 / Topic 4 of 10
Date spines with generate_series
The growth report above has a quiet bug: a month with no delivered orders produces no row — it doesn't show as zero, it vanishes, and nobody notices the hole. The fix is a date spine: generate every period, then LEFT JOIN the facts onto it:
SELECT generate_series(DATE '2025-01-01', DATE '2025-06-01',
INTERVAL '1 month')::date AS month;
month
------------
2025-01-01
2025-02-01
2025-03-01
2025-04-01
2025-05-01
2025-06-01
(6 rows)
generate_series manufactures rows — numbers, dates, timestamps. Spine on the left, facts on the right, COALESCE the holes to zero:
WITH months AS (
SELECT generate_series(DATE '2025-01-01', DATE '2025-06-01',
INTERVAL '1 month')::date AS month
),
revenue AS (
SELECT date_trunc('month', o.order_date)::date AS month,
sum(oi.quantity * oi.unit_price) AS revenue
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id
WHERE o.status = 'delivered'
GROUP BY 1
)
SELECT m.month, COALESCE(r.revenue, 0) AS revenue
FROM months AS m
LEFT JOIN revenue AS r ON r.month = m.month
ORDER BY m.month;
month | revenue
------------+---------
2025-01-01 | 2069.00
2025-02-01 | 135.00
2025-03-01 | 150.00
2025-04-01 | 1709.00
2025-05-01 | 0
2025-06-01 | 0
(6 rows)
May and June: zero, visibly. Every time-series report you ever publish should stand on a spine — "no data" and "zero" are different facts, and charts drawn without spines lie by omission.
🧪 Quick quiz — answer from memory, then check.
- What goes wrong without a date spine?
- Which side of the LEFT JOIN is the spine on?
Show the answers
- Periods with no facts disappear instead of showing 0 — holes in charts, averages computed over the wrong number of months.
- The left — every spine row must survive; facts attach where they exist.
Done here? The practice set for Part 8 — 8 exercises with solutions — is on the part page.