Saltar al contenido

Lección 18 · Automating Reports

SQL for Reports

Write reliable reporting SQL with parameters, CTEs, a calendar table for missing days, conditional totals and half-open date ranges, with runnable SQLite examples.

Automation starts with a query that you trust. A report query runs again and again, often without anyone watching, so it must handle empty days, new categories and period boundaries correctly. This lesson shows patterns that make reporting SQL dependable. The examples run on SQLite. Other databases have different date functions, so check your database's documentation. If SQL is new to you, begin with the SQL tutorial.

Build in steps with CTEs

A common table expression (CTE), written with WITH, names an intermediate result. A good report query reads like a short recipe: set the period, filter the records, summarize and format. See CTEs for the basics.

Set the period once

Write the start and end dates in one place so that every part of the report uses the same window. In production, pass them as query parameters from your application or tool. Do not build SQL by joining user input into a string.

Use a half-open range: on or after the start and before the end. It works for both dates and timestamps. With timestamps, BETWEEN '2026-11-01' AND '2026-11-30' misses events later on November 30, because a bare date is compared as the very start of that day, or in text comparisons as a shorter string.

SQL One period, defined once

Press Run (or Ctrl + Enter) to see the result here.

The late sale on November 30 is included, while the rows just outside the month are not. The CASE expressions give several measures in one pass. This is called conditional aggregation.

Fill the gaps with a calendar

GROUP BY only returns groups that exist. A day with no orders disappears, and a chart may join the neighboring days with a straight line. Create a list of all dates, then left join the data to it.

SQL A complete daily series

Press Run (or Ctrl + Enter) to see the result here.

COUNT(o.order_date) counts only matched rows, while COUNT(*) would report 1 for an empty day. Turning an empty sum into 0 is right only if you know that data for that day arrived and there were truly no orders. If a feed failed, zero is false. Check freshness first, as in dashboard basics.

Many data warehouses keep a permanent calendar table with columns for week, month, fiscal period and working day. That keeps date rules in one place.

Totals and subtotals

You can produce detail rows and a total in one result with UNION ALL. Some databases also support ROLLUP or grouping sets. SQLite does not support ROLLUP.

SQL Detail rows and a total row

Press Run (or Ctrl + Enter) to see the result here.

Note two habits. The total row recalculates the percentage from the summed parts. NULLIF turns a zero denominator into NULL, and 100.0 avoids integer division.

Habits for maintainable report queries

  • Give columns clear names, because those names often become headers.
  • Name the grain of each CTE in a comment.
  • List columns explicitly instead of using SELECT *.
  • Order the result with ORDER BY; without it, row order is not guaranteed.
  • Keep queries in version control and record who changed what.
  • Run reports on a read-only connection, and prefer a replica or warehouse to a busy production database.
  • Watch for slow queries, and pre-aggregate when needed.

Check a query as you build it

Do not write fifty lines and then look at the result. Build one CTE at a time and inspect each step.

  • After filtering, check the earliest and latest dates and count the rows.
  • After each join, compare the row count and a key total with their values before the join. A rise may mean that rows were multiplied. A drop may mean that an inner join removed unmatched records.
  • After grouping, look for NULL groups and unexpected category spellings.
  • At the end, compare the grand total with a very simple query on the source table.

Keep a few of these checks as saved queries and run them after every change.

Be careful with late-arriving data. A query for a past week can return a different total today than it did last Monday. If readers need to see what was known then, store each published result in a snapshot table with its period and run time. Rerunning the live query cannot reliably reconstruct that view.

Make performance predictable

A report query that takes seconds today may take minutes after the data grows. Filter to the needed period as early as you can, and select only the columns you use. Compare a plain date column with boundary values, as the half-open range does, and avoid wrapping that column in a function inside WHERE, because that often prevents the database from using an index.

When many reports need the same daily totals, build a summary table once on a schedule and read from it. Record when it was last built. It adds one more thing that can be stale, so include it in your freshness checks. Keep sums and counts in it, not finished percentages, so that you can still combine days correctly.

Finally, write a short comment at the top of each query with its purpose, grain, owner and the definition version it implements. The next person to edit it, who may be you, will know what must not change.

A query that runs without errors can still be wrong. After any change, compare its totals with an independent count, as described in checking your numbers.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which condition safely includes all timestamps in November 2026?

    A half-open range includes every moment from the start up to, but not including, December 1.
  2. 2. Why join your data to a calendar list?

    GROUP BY alone cannot create groups for days that have no rows.
  3. 3. With a left join to a calendar, which counts orders correctly on empty days?

    COUNT of a column from the joined table ignores the NULLs on empty days.
  4. 4. What does NULLIF(delivered, 0) protect against?

    It returns NULL when the value is zero, so the division gives NULL.

Summary

  • Break report queries into named CTEs and set the period once.
  • Use half-open date ranges and query parameters.
  • Use conditional aggregation for several measures.
  • Left join to a calendar, and confirm that zeros are real.
  • Recalculate total rates from parts and keep queries under version control.

Next: Generating Reports with Python

Tu progreso se guarda en este navegador. No necesitas una cuenta.