A sales query grouped by date returns only dates that have rows. That can make a chart skip quiet days instead of showing zero. If a shop recorded sales on 1 and 3 December, a report for 1–5 December should still have five rows.
This SQLite example builds a date spine: one row for every requested calendar date. It separately aggregates sales, then attaches those totals to the full sequence. The downloadable project contains the complete SQL, Python runner, twelve tests, setup notes and exact expected output. It uses fictional sales in memory and never opens an existing database.
Run the report locally
Use Python 3.10 or later with its standard sqlite3 module, backed by SQLite 3.8.3 or later for recursive CTE support. No pip package, database server or account is required. Extract the ZIP, enter sql-date-spine and run:
python report.py
python -m unittest -v
The output is:
day,orders,revenue_cents
2026-12-01,2,2000
2026-12-02,0,0
2026-12-03,1,900
2026-12-04,0,0
2026-12-05,1,0
The available verification environment was Python 3.13.3 with SQLite 3.49.1 on Windows. The first day has two sales totaling 2,000 cents; the third has one sale of 900 cents. The second and fourth dates have no rows. The final day has a real zero-value order, so its order count is one even though its revenue is zero.
Generate dates before attaching sales
Save the query as report.sql. SQLite's WITH documentation explains recursive CTEs: an initial row seeds the sequence and the recursive term extends it. Here the start date is the seed, and the query adds a day while the current date is below the inclusive end date.
WITH RECURSIVE days(day) AS (
SELECT :start_day
UNION ALL
SELECT date(day, '+1 day')
FROM days
WHERE day < :end_day
),
totals AS (
SELECT sold_on, COUNT(*) AS orders, SUM(amount_cents) AS revenue_cents
FROM sales
WHERE sold_on BETWEEN :start_day AND :end_day
GROUP BY sold_on
)
SELECT days.day,
COALESCE(totals.orders, 0) AS orders,
COALESCE(totals.revenue_cents, 0) AS revenue_cents
FROM days
LEFT JOIN totals ON totals.sold_on = days.day
ORDER BY days.day;
The SQLite date-function reference documents date text and modifiers. The next-day expression handles month lengths and leap dates rather than adding one to the text's day number. All inputs here are exact calendar dates, not timestamps awaiting timezone conversion.
The totals CTE groups only real sales in the requested interval. Joining one total per day avoids multiplying a daily total across individual sale rows. The final LEFT JOIN preserves every generated date; COALESCE turns missing totals into integer zero. Keep the date-spine rows on the preserved side of the join.
Count real orders before zero filling
COUNT(*) is correct inside totals because it operates directly on source sales. Applying it after a direct left join to individual sales would also count the placeholder row for a day with no matching sale. That is why the report aggregates before joining, instead of counting the final result rows.
The aggregate-function documentation distinguishes counting rows, counting non-null values and summing values. It also documents integer SUM overflow. This fixture uses bounded nonnegative integer cents; that avoids floating-point money in the demo but is not a guarantee against aggregate overflow in an arbitrarily large production dataset.
Validate the range before executing the SQL
Save this complete runner as report.py beside the SQL file. It validates exact real dates and limits the inclusive range to 1–366 days. The Python sqlite3 documentation describes passing query values through placeholders. The runner binds its canonical start and end values instead of interpolating them into SQL.
from contextlib import closing
from datetime import date
from pathlib import Path
import re
import sqlite3
QUERY = Path(__file__).with_name('report.sql').read_text(encoding='utf-8')
SAMPLE = [
('2026-12-01', 1250),
('2026-12-01', 750),
('2026-12-03', 900),
('2026-12-05', 0),
]
def parse_day(value):
if not isinstance(value, str) or re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}', value) is None:
raise ValueError('Use an exact YYYY-MM-DD date.')
return date.fromisoformat(value)
def daily_report(connection, start_day, end_day):
start = parse_day(start_day)
end = parse_day(end_day)
day_count = (end - start).days + 1
if not 1 <= day_count <= 366:
raise ValueError('Range must contain 1 to 366 days, inclusive.')
parameters = {
'start_day': start.isoformat(),
'end_day': end.isoformat(),
}
cursor = connection.execute(QUERY, parameters)
return cursor.fetchall()
def make_database(rows):
connection = sqlite3.connect(':memory:')
try:
connection.execute(
'CREATE TABLE sales ('
'id INTEGER PRIMARY KEY, '
'sold_on TEXT NOT NULL, '
'amount_cents INTEGER NOT NULL CHECK (amount_cents >= 0))'
)
connection.execute('CREATE INDEX sales_by_day ON sales(sold_on)')
for sold_on, amount in rows:
parse_day(sold_on)
if type(amount) is not int or not 0 <= amount <= 1_000_000:
raise ValueError('Sample amounts must be integer cents from 0 to 1000000.')
connection.executemany(
'INSERT INTO sales (sold_on, amount_cents) VALUES (?, ?)',
rows,
)
connection.commit()
except Exception:
connection.close()
raise
return connection
def main():
with closing(make_database(SAMPLE)) as connection:
rows = daily_report(connection, '2026-12-01', '2026-12-05')
print('day,orders,revenue_cents')
for day, orders, revenue in rows:
print(f'{day},{orders},{revenue}')
if __name__ == '__main__':
main()
The range guard is part of the example's contract. If the raw SQL is executed with a reversed interval, the seed still exists; it does not automatically become an empty report. Run it through the wrapper or provide equivalent validation in your own application. The 366-day cap also prevents an accidental request from generating an unexpectedly large sequence.
make_database expects a reusable list of date/amount tuples. It validates that fixture dates are real and amounts are integer cents within the sample's stated bounds, rejecting booleans as amounts. The schema and index are created only in a new in-memory connection. The final reporting query reads sales without changing them.
Twelve executed tests, including boundary dates
Save the complete verifier as test_report.py. Its expected rows are independent of the query's output, so a plausible-looking report is not enough to pass.
from contextlib import closing
import unittest
from report import SAMPLE, daily_report, make_database, parse_day
class ReportTests(unittest.TestCase):
def run_report(self, rows, start='2026-12-01', end='2026-12-05'):
with closing(make_database(rows)) as connection:
return daily_report(connection, start, end)
def test_exact_sample_with_gaps(self):
expected = [
('2026-12-01', 2, 2000),
('2026-12-02', 0, 0),
('2026-12-03', 1, 900),
('2026-12-04', 0, 0),
('2026-12-05', 1, 0),
]
self.assertEqual(self.run_report(SAMPLE), expected)
def test_empty_source_still_has_every_day(self):
result = self.run_report([])
self.assertEqual(len(result), 5)
self.assertTrue(all(orders == 0 and revenue == 0 for _, orders, revenue in result))
def test_single_day_is_inclusive(self):
expected = [('2026-12-03', 1, 900)]
self.assertEqual(self.run_report(SAMPLE, '2026-12-03', '2026-12-03'), expected)
def test_outside_rows_are_excluded(self):
rows = SAMPLE + [('2026-11-30', 999), ('2026-12-06', 999)]
self.assertEqual(self.run_report(rows), self.run_report(SAMPLE))
def test_leap_day_and_month_transition(self):
expected = [('2024-02-28', 0, 0), ('2024-02-29', 0, 0), ('2024-03-01', 0, 0)]
self.assertEqual(self.run_report([], '2024-02-28', '2024-03-01'), expected)
def test_year_transition(self):
expected = [('2026-12-31', 0, 0), ('2027-01-01', 0, 0)]
self.assertEqual(self.run_report([], '2026-12-31', '2027-01-01'), expected)
def test_maximum_range_and_rejection(self):
self.assertEqual(len(self.run_report([], '2024-01-01', '2024-12-31')), 366)
with self.assertRaises(ValueError):
self.run_report([], '2024-01-01', '2025-01-01')
def test_reversed_range_rejected(self):
with self.assertRaises(ValueError):
self.run_report([], '2026-12-05', '2026-12-01')
def test_invalid_and_noncanonical_dates(self):
invalid = ['2026-02-29', '2026-2-01', '20261201', '2026-12-01Z', None]
for value in invalid:
with self.subTest(value=value):
with self.assertRaises(ValueError):
parse_day(value)
def test_sql_like_date_rejected_and_table_preserved(self):
with closing(make_database(SAMPLE)) as connection:
with self.assertRaises(ValueError):
daily_report(connection, "2026-12-01'; DROP TABLE sales; --", '2026-12-05')
count = connection.execute('SELECT COUNT(*) FROM sales').fetchone()[0]
self.assertEqual(count, 4)
def test_report_does_not_change_source(self):
with closing(make_database(SAMPLE)) as connection:
before = connection.execute('SELECT * FROM sales ORDER BY id').fetchall()
daily_report(connection, '2026-12-01', '2026-12-05')
after = connection.execute('SELECT * FROM sales ORDER BY id').fetchall()
self.assertEqual(after, before)
def test_invalid_fixture_amounts_rejected(self):
for amount in [-1, True, 1.5, 1_000_001]:
with self.subTest(amount=amount):
rows = [('2026-12-01', amount)]
with self.assertRaises(ValueError):
make_database(rows)
if __name__ == '__main__':
unittest.main()
The original source and independently extracted ZIP each passed twelve tests and produced the exact sample output shown above. Both Python files passed syntax parsing. A temporary negative-control copy changed LEFT JOIN to an inner JOIN; the missing-date and boundary tests failed, confirming that the verifier detects lost spine rows.
| Case | Expected behavior |
|---|---|
| Sample sales and empty source | Every requested day exists; quiet days have zero orders and revenue. |
| Single day and out-of-range sales | Inclusive endpoints and no leakage from neighboring dates. |
| Leap day, month/year changes and 366-day range | A complete ordered calendar sequence. |
| Reversed/oversized ranges and invalid dates | Rejected before query execution. |
| SQL-like input, invalid amounts and repeat reporting | Input is rejected appropriately and source rows remain unchanged. |
Define what zero means in the real report
Zero here means no recorded sales for a date in a complete input dataset. If yesterday's import failed, zero filling can conceal missing ingestion rather than reveal a quiet business day. Keep completeness checks separate from this SQL presentation step.
The dates are already assigned business-calendar dates. If your source stores timestamps, decide which timezone defines a sales day before adapting the query. Refunds, multiple currencies, tax rounding and currency conversion are outside the fixture. For repeated reporting over a large calendar, compare a maintained calendar table and an appropriate index with generating a short sequence each time; this example makes no performance claim.
If Python cannot import sqlite3, use a distribution that includes that optional standard-library module. If the SQL file is missing, extract the whole project and keep it beside report.py. When adapting the schema, preserve canonical date storage and an explicit data-completeness policy rather than assuming arbitrary date strings will sort as a calendar.
Comments (0)
Join the discussion