Full answer
sql
CREATE TABLE daily_sales (
day TEXT PRIMARY KEY,
amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);The sales table has gaps on 4, 7 and 8 March. Grouping it directly shows only days with data. A generated calendar fills the gaps:
sql
WITH RECURSIVE days(day) AS (
SELECT '2026-03-01'
UNION ALL
SELECT date(day, '+1 day') FROM days WHERE day < '2026-03-09'
)
SELECT d.day, COALESCE(s.amount, 0) AS amount
FROM days d
LEFT JOIN daily_sales s ON s.day = d.day
ORDER BY d.day;| day | amount |
|---|---|
| 2026-03-01 | 120 |
| 2026-03-02 | 80 |
| 2026-03-03 | 150 |
| 2026-03-04 | 0 |
| 2026-03-05 | 90 |
| 2026-03-06 | 60 |
| 2026-03-07 | 0 |
| 2026-03-08 | 0 |
| 2026-03-09 | 200 |
The calendar drives the query, so every day appears. COALESCE turns the missing totals into 0 for the chart.
PostgreSQL has generate_series, which replaces the recursive CTE:
sql
SELECT d::date AS day, COALESCE(s.amount, 0) AS amount
FROM generate_series(DATE '2026-03-01', DATE '2026-03-09', INTERVAL '1 day') AS d
LEFT JOIN daily_sales s ON s.day = d::date
ORDER BY day;| day | amount |
|---|---|
| 2026-03-01 | 120 |
| 2026-03-02 | 80 |
| 2026-03-03 | 150 |
| 2026-03-04 | 0 |
| 2026-03-05 | 90 |
| 2026-03-06 | 60 |
| 2026-03-07 | 0 |
| 2026-03-08 | 0 |
| 2026-03-09 | 200 |
Many teams keep a permanent calendar table (one row per date, with columns such as weekday, month and holiday flag) instead of generating dates in every query. It is easy to index, easy to join, and makes questions such as "sales per working day" simple.
sql
CREATE TABLE daily_sales (
day TEXT PRIMARY KEY,
amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);
WITH RECURSIVE days(day) AS (
SELECT '2026-03-01'
UNION ALL
SELECT date(day, '+1 day') FROM days WHERE day < '2026-03-09'
)
SELECT d.day, COALESCE(s.amount, 0) AS amount
FROM days d
LEFT JOIN daily_sales s ON s.day = d.day
ORDER BY d.day;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- Generate the full list of dates first
- LEFT JOIN the facts onto the calendar
- COALESCE missing totals to 0 when zero is meaningful
- generate_series in PostgreSQL; a calendar table for reuse
Common mistakes
- Grouping the fact table and expecting missing days to appear
- Inner joining to the calendar and losing the empty days again
Follow-ups
- How would you show every week instead of every day?
- What columns would you put in a calendar table?
Tips
- Explain why the calendar must be on the left side of the join