← Back to SQL, page 20

sql-0389 · Medium mid

Fill in missing days of sales with zero using PostgreSQL's generate_series.

Generate every date in the range with generate_series(start, end, interval '1 day'), LEFT JOIN the sales table on the day, and COALESCE missing amounts to 0. This produces one row per calendar day, which charts and moving averages need.

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;
dayamount
2026-03-01120
2026-03-0280
2026-03-03150
2026-03-040
2026-03-0590
2026-03-0660
2026-03-070
2026-03-080
2026-03-09200

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;
dayamount
2026-03-01120
2026-03-0280
2026-03-03150
2026-03-040
2026-03-0590
2026-03-0660
2026-03-070
2026-03-080
2026-03-09200

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