Reading history

Fill Missing Dates in SQL Reports With a Calendar

5 min read 0 views

Show every day and month in SQL reports: generate dates with a recursive CTE, LEFT JOIN the data, use COALESCE for zeros, and add a running total.

A daily sales report should show every day, including the quiet ones with zero sales. But GROUP BY day can only show days that exist in the data, so the quiet days silently disappear and charts skip them. The fix is to generate a complete calendar of dates and LEFT JOIN the data to it. This lesson builds daily and monthly calendars with a recursive query and adds a running total.

In this lesson you will learn

  • Why grouped reports skip days with no data
  • Generating a series of dates with a recursive CTE
  • Filling the gaps with LEFT JOIN and COALESCE
  • Building a monthly report with an empty month and a running total
  • Keeping a permanent calendar table

You should know date functions, LEFT JOIN and recursive CTEs.

A Daily Report With Every Day

-- Sales exist only on days with orders, so a plain GROUP BY skips quiet days
CREATE TABLE sales (day TEXT, amount INTEGER);
INSERT INTO sales VALUES
 ('2026-04-01', 500), ('2026-04-01', 300), ('2026-04-02', 900),
 ('2026-04-05', 400), ('2026-04-07', 650), ('2026-04-07', 150);

SELECT day, SUM(amount) AS total FROM sales GROUP BY day;

-- Build every date in the range with a recursive CTE, then LEFT JOIN the sales
WITH RECURSIVE calendar(day) AS (
  SELECT '2026-04-01'
  UNION ALL
  SELECT date(day, '+1 day') FROM calendar WHERE day < '2026-04-07'
)
SELECT c.day,
       strftime('%w', c.day) AS weekday_no,
       COALESCE(SUM(s.amount), 0) AS total
FROM calendar c
LEFT JOIN sales s ON s.day = c.day
GROUP BY c.day
ORDER BY c.day;

Output

+------------+-------+
| day        | total |
+------------+-------+
| 2026-04-01 | 800   |
| 2026-04-02 | 900   |
| 2026-04-05 | 400   |
| 2026-04-07 | 800   |
+------------+-------+
(4 rows)

+------------+------------+-------+
| day        | weekday_no | total |
+------------+------------+-------+
| 2026-04-01 | 3          | 800   |
| 2026-04-02 | 4          | 900   |
| 2026-04-03 | 5          | 0     |
| 2026-04-04 | 6          | 0     |
| 2026-04-05 | 0          | 400   |
| 2026-04-06 | 1          | 0     |
| 2026-04-07 | 2          | 800   |
+------------+------------+-------+
(7 rows)
  • The first query has only four rows. April 3, 4 and 6 are missing because no sale happened, and a chart drawn from it would join April 2 straight to April 5.
  • The recursive CTE starts at April 1 and adds one day with date(day, '+1 day') until it reaches April 7, giving all seven dates.
  • LEFT JOIN keeps every calendar day even when no sales row matches. For those days SUM(s.amount) is NULL, and COALESCE(..., 0) turns it into 0.
  • strftime('%w', day) gives the day of the week, 0 for Sunday to 6 for Saturday. April 1, 2026 is a Wednesday (3).

A Monthly Report With a Running Total

-- Monthly report for January to April 2026, with an empty month and a running total
WITH RECURSIVE months(m) AS (
  SELECT '2026-01-01'
  UNION ALL
  SELECT date(m, '+1 month') FROM months WHERE m < '2026-04-01'
), monthly AS (
  SELECT strftime('%Y-%m', mo.m) AS month,
         COUNT(o.id) AS orders,
         COALESCE(SUM(o.amount), 0) AS revenue
  FROM months mo
  LEFT JOIN orders o
    ON strftime('%Y-%m', o.order_date) = strftime('%Y-%m', mo.m)
   AND o.status = 'delivered'
  GROUP BY mo.m
)
SELECT month, orders, revenue,
       SUM(revenue) OVER (ORDER BY month) AS running_total
FROM monthly;

Output

+---------+--------+---------+---------------+
| month   | orders | revenue | running_total |
+---------+--------+---------+---------------+
| 2026-01 | 2      | 1650    | 1650          |
| 2026-02 | 1      | 2300    | 3950          |
| 2026-03 | 2      | 1800    | 5750          |
| 2026-04 | 0      | 0       | 5750          |
+---------+--------+---------+---------------+
(4 rows)
  • The months CTE steps one month at a time with date(m, '+1 month'), from January to April.
  • The status filter sits inside the ON clause, not in WHERE. In WHERE it would remove the empty April row, because April has no order whose status could be “delivered”.
  • COUNT(o.id) counts only matched orders, so April shows 0. COUNT(*) would count the calendar row itself and show 1.
  • The window SUM(revenue) OVER (ORDER BY month) adds a running total, which stays flat through the empty month.

A Permanent Calendar Table

Reports that run every day can use a stored calendar table instead of generating dates each time. It can also hold extra facts that SQL cannot work out by itself, such as public holidays.

CREATE TABLE calendar (day TEXT PRIMARY KEY, weekday INTEGER, is_holiday INTEGER DEFAULT 0);
WITH RECURSIVE d(day) AS (
  SELECT '2026-01-01'
  UNION ALL
  SELECT date(day, '+1 day') FROM d WHERE day < '2026-12-31'
)
INSERT INTO calendar (day, weekday) SELECT day, strftime('%w', day) FROM d;
UPDATE calendar SET is_holiday = 1 WHERE day IN ('2026-02-21', '2026-03-26', '2026-12-16');

Other databases have built-in series generators: generate_series in PostgreSQL, and recursive CTEs or numbers tables in MySQL and SQL Server.

Common Mistakes

  1. Filtering the joined table in WHERE, which turns the LEFT JOIN back into an inner join and removes empty days.
  2. COUNT(*) instead of COUNT(column), which reports 1 for empty days.
  3. Comparing dates stored in different formats. ‘2026-04-01’ and ‘2026-04-01 10:30:00’ are not equal; use date(column) to compare only the date part.
  4. No stop condition in the recursive CTE, which makes it run for ever.

Practice Exercises

Exercise 1. Generate the 7 dates of the week starting 2026-04-06 with each day’s name (Mon, Tue, …).

Show answer
WITH RECURSIVE w(day) AS (
  SELECT '2026-04-06'
  UNION ALL
  SELECT date(day, '+1 day') FROM w WHERE day < '2026-04-12'
)
SELECT day,
       substr('SunMonTueWedThuFriSat', 1 + 3 * strftime('%w', day), 3) AS name
FROM w;

Exercise 2. In the daily report, how many days had no sales at all?

Show answer

Wrap the report in a subquery and count rows where total = 0. The answer is 3 (April 3, 4 and 6).

Frequently Asked Questions

Why not just fill the gaps in Excel or in the chart?

You can, but every report and every person would have to remember to do it. Filling the gaps in SQL makes the data correct at the source, so averages per day and charts are right everywhere.

How do I generate weeks instead of days?

Step by 7 days with date(day, '+7 days'), and group the data by the start of its week, for example date(day, 'weekday 0', '-6 days') for weeks starting on Monday.

Summary

  • GROUP BY cannot show days that have no rows.
  • Generate the full date range with a recursive CTE or a calendar table.
  • LEFT JOIN the data to the calendar and use COALESCE(..., 0).
  • Put filters on the joined table in the ON clause.

Next: Full-Text Search in SQL.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *