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);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 = to_char(d, 'YYYY-MM-DD')
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 |
The series supplies the 4th, 7th and 8th even though the table has no rows for them, and COALESCE shows 0 instead of NULL. generate_series with timestamps returns timestamps, so the cast to date makes the join and the output clean. In SQLite the same calendar comes from a recursive CTE:
sql
WITH RECURSIVE cal(day) AS (SELECT '2026-03-01' UNION ALL SELECT date(day, '+1 day') FROM cal WHERE day < '2026-03-09')
SELECT c.day, COALESCE(s.amount, 0) AS amount FROM cal c LEFT JOIN daily_sales s ON s.day = c.day ORDER BY c.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 |
Both runs return nine rows. A permanent calendar table (one row per day for many years, with flags such as weekday and holiday) is a common alternative that also serves reporting joins.
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 cal(day) AS (SELECT '2026-03-01' UNION ALL SELECT date(day, '+1 day') FROM cal WHERE day < '2026-03-09')
SELECT c.day, COALESCE(s.amount, 0) AS amount FROM cal c LEFT JOIN daily_sales s ON s.day = c.day ORDER BY c.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_series creates a date spine
- LEFT JOIN facts onto the spine
- COALESCE gaps to zero
- Recursive CTEs do the same in SQLite
- Calendar tables are a reusable option
Common mistakes
- Joining the spine with an inner join
- Forgetting the cast from timestamp to date
Follow-ups
- How would you compute a 7-day moving average over the filled series?
- What should happen when zero and missing mean different things?
Tips
- Show both engines