Calendar Spine With generate_series
Build a gap-free calendar with generate_series and LEFT JOIN daily totals, so missing dates report zero instead of disappearing.
Code
WITH bounds AS (
SELECT date '2026-11-01' AS start_date, date '2026-11-10' AS end_date
),
spine AS (
SELECT day::date AS day
FROM bounds,
generate_series(bounds.start_date, bounds.end_date, interval '1 day') AS day
),
events (event_date, signups) AS (
VALUES
(date '2026-11-01', 4),
(date '2026-11-03', 7),
(date '2026-11-03', 2),
(date '2026-11-08', 5)
)
SELECT
spine.day,
coalesce(sum(events.signups), 0) AS signups
FROM spine
LEFT JOIN events ON events.event_date = spine.day
GROUP BY spine.day
ORDER BY spine.day;How the snippet works
At its core this is a single SELECT statement against bounds, spine and events.
Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.
Applying it
Run the statement against the bounds table.
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Age CalculatorCalculate exact age in years, months, and days between a birth date and a reference date, plus total days and the next birthday countdown.Business Days CalculatorCount the weekdays between two dates, excluding weekends and any holidays you list, and see how many calendar and weekend days are involved.
FAQ
- What objects does the SQL involve?
- `bounds`, `spine`, `events`, combined through a join.
Report a problem with this exampleOpens a pre-filled issue on GitHub.