// SQL snippet

Fill gaps with a calendar spine

Build the date range first, then attach the facts. Charts stop lying about missing days.

Main statement
PostgreSQL
同時涵蓋
SQL Server MySQL

The task

Your revenue chart skips days with no orders, which makes quiet periods invisible. You want every day in the range, with a zero where nothing sold.

The snippet

Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.

PostgreSQL
WITH days AS (
  SELECT generate_series(DATE '2026-06-01', DATE '2026-06-30',
                         INTERVAL '1 day')::date AS day
),
sales AS (
  SELECT CAST(order_date AS date) AS day, SUM(amount) AS total
  FROM orders
  GROUP BY 1
)
SELECT d.day, COALESCE(s.total, 0) AS total
FROM days d
LEFT JOIN sales s ON s.day = d.day
ORDER BY d.day;

它的運作方式

The CTE builds every day in the range with generate_series, regardless of whether orders exist. LEFT JOINing the sales onto the spine keeps all days; COALESCE turns the missing totals into zero. Other engines build the same spine with a recursive CTE; SQLite can use either a recursive CTE or the generate_series table-valued function from its series extension, which the sqlite3 CLI includes.

Variations

MySQL: recursive-CTE spine

MySQL
WITH RECURSIVE days AS (
  SELECT DATE '2026-06-01' AS day
  UNION ALL
  SELECT day + INTERVAL 1 DAY
  FROM days
  WHERE day < DATE '2026-06-30'
)
SELECT d.day, COALESCE(SUM(o.amount), 0) AS total
FROM days d
LEFT JOIN orders o
       ON o.order_date >= d.day
      AND o.order_date <  d.day + INTERVAL 1 DAY
GROUP BY d.day
ORDER BY d.day;

SQL Server: recursive CTE without the RECURSIVE keyword

SQL Server
WITH days AS (
  SELECT CAST('2026-06-01' AS date) AS day
  UNION ALL
  SELECT DATEADD(day, 1, day)
  FROM days
  WHERE day < '2026-06-30'
)
SELECT d.day, COALESCE(SUM(o.amount), 0) AS total
FROM days d
LEFT JOIN orders o
       ON o.order_date >= d.day
      AND o.order_date <  DATEADD(day, 1, d.day)
GROUP BY d.day
ORDER BY d.day;

Questions that come up

Why a LEFT JOIN and not an INNER JOIN?

An INNER JOIN joins only the days that have sales, which is exactly the skipping you are trying to fix. The spine drives the row set; the facts attach to it.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.