Skip to content
Visual explainer 4h to learn 4 steps

Practice: reporting queries

Write twenty reporting queries against a sample schema without looking up syntax.

By Invicly Tech, , in SQL & PostgreSQL. About 9 minutes to read.

Topic 8 of 30

In short

Reporting queries turn business questions into SQL. Practise the same routine on a sample schema until joins, grouping and top-N patterns come without looking anything up.

Explained simply

Reading about joins is like reading about swimming. You only get good by doing it. Reporting queries are the best practice because they mix everything you have learned: joins, filters, grouping and sorting.

A reporting query starts as a plain-English question from someone else: "Which city brought in the most revenue last quarter?" Your job is to translate it, one piece at a time, into SQL that gives a correct and checkable answer.

Use a sample database with realistic tables, such as a shop with customers, orders, order items and products. Free ones like pgexercises or the dvdrental sample load in minutes and come with questions to answer.

The goal is speed with confidence. After twenty or so queries, the common shapes (totals per group, top N, "who never did X", month by month) start to feel familiar, and you write them without looking up syntax.

Press Play on a diagram to walk through it one step at a time.

CycleWriting a reporting query
  1. 1
    Restate the question

    What does one output row represent?

  2. 2
    Find the tables

    Follow foreign keys between them

  3. 3
    Join & filter

    Start small; check row counts

  4. 4
    Aggregate

    GROUP BY the grain you chose

  5. 5
    Verify

    Spot-check totals against a simpler query

  6. Back to step 1
MapA typical practice schema (online shop)
shop database
  • customers
    • id, name, city, created_at
  • orders
    • id, customer_id -> customers
    • ordered_at, status
  • order_items
    • order_id -> orders
    • product_id -> products
    • qty, unit_price
  • products
    • id, name, category, price

In depth

The handful of shapes behind most reports

Almost every report is one of a few patterns. Learn to spot them and you already know the skeleton of the query.

Totals per group use JOIN plus GROUP BY. Trends over time group by date_trunc('month', ts). Top N overall uses ORDER BY and LIMIT. Top N per group needs ROW_NUMBER() OVER (PARTITION BY ...) or a LATERAL join. "Never did X" is an anti-join with NOT EXISTS. Shares of a whole divide each group's sum by SUM(...) OVER (). Comparisons between periods use FILTER or LAG.

  • Per group: JOIN + GROUP BY
  • Over time: date_trunc + GROUP BY
  • Top N per group: ROW_NUMBER or LATERAL
  • Never did X: NOT EXISTS
  • Share of total: x / SUM(x) OVER ()

Checking your answer like an analyst

A query that runs is not the same as a query that is right. Build in checks.

First, count rows after each join. If you started with 1,000 orders and now have 3,400 rows, something fanned out. Second, reconcile: the sum of revenue per country should equal total revenue from a simple SELECT SUM(...). Third, test edge cases: a customer with no orders, an order on the last second of the month, a NULL country. Finally, read three or four result rows and check them by hand against the raw tables.

FlowChecking a report before you trust it
  1. Step 1
    Count rows after each join

    1,000 orders became 3,400 rows? Fan-out

  2. Step 2
    Reconcile totals

    Sum per country equals the overall SUM

  3. Step 3
    Test edge cases

    No orders, last second of month, NULL country

  4. Step 4
    Hand-check rows

    Compare 3 or 4 rows with the raw tables

Half-open date ranges

Timestamps have times, so "all of March" is safest written as ordered_at >= '2026-03-01' AND ordered_at < '2026-04-01'. This is called a half-open range: the start is included, the end is not. It works for any precision, never double-counts a row that falls exactly on midnight, and lets Postgres use an index on ordered_at.

Avoid wrapping the column in a function such as date(ordered_at) = '2026-03-15' in filters on big tables. It is correct, but a normal index on ordered_at cannot be used for it.

CompareFiltering one month or day
Half-open range
  • ordered_at >= '2026-03-01'
  • AND ordered_at < '2026-04-01'
  • Works for any time precision
  • Can use an index on ordered_at
Function on the column
  • date(ordered_at) = '2026-03-15'
  • Correct result
  • Plain index on ordered_at not used

Making queries readable for the next person

Reports get reused and edited. Write them so the next person can follow.

Put each selected column, each JOIN and each condition on its own line. Use short, meaningful aliases (o for orders, c for customers). Name output columns for the reader: revenue_eur, not sum. Break long queries into named steps with WITH (a CTE), so each step can be run and checked on its own. Add a one-line comment saying what one row of the result represents.

Learn it in 4 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Load a sample schema~1h
  2. 2
    Write sales and revenue reports~1h
  3. 3
    Write top-N and per-group queries~1h
  4. 4
    Finish twenty queries without lookups~1h

Key points

  • Decide the grain first: per day, per customer, per product?
  • Build queries step by step and run each step.
  • Top-N per group needs a window function or LATERAL join, not just LIMIT.
  • Cross-check totals: the sum of parts should equal the whole.

Key terms

Tap a card to flip it. 0/4 known

Examples

sql
-- monthly revenue for 2026
SELECT date_trunc('month', o.ordered_at) AS month,
       SUM(oi.qty * oi.unit_price)     AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
WHERE o.ordered_at >= '2026-01-01' AND o.ordered_at < '2027-01-01'
GROUP BY month
ORDER BY month;

Top city by revenue last quarter

Step 1: grain is one row per city. Step 2: revenue lives in order_items (qty times unit_price), city lives in customers, so the path is order_items to orders to customers. Step 3: filter last quarter with a half-open range on orders.ordered_at. Step 4: GROUP BY city and sum. Step 5: order by revenue and take the top 5. Step 6: check that the city totals add up to SELECT SUM over the same filter.

sql
SELECT c.city, SUM(oi.qty * oi.unit_price) AS revenue
FROM order_items oi
JOIN orders o    ON o.id = oi.order_id
JOIN customers c ON c.id = o.customer_id
WHERE o.ordered_at >= date_trunc('quarter', now()) - interval '3 months'
  AND o.ordered_at <  date_trunc('quarter', now())
  AND o.status = 'paid'
GROUP BY c.city
ORDER BY revenue DESC
LIMIT 5;

Best-selling product in each category

"Top 1 per group" cannot be done with LIMIT alone. Step 1: in a CTE, sum units per product. Step 2: in a second step, number the products within each category by units, highest first, with ROW_NUMBER. Step 3: keep rows numbered 1. Each step can be run on its own to check it.

sql
WITH sales AS (
  SELECT p.category, p.name, SUM(oi.qty) AS units
  FROM order_items oi JOIN products p ON p.id = oi.product_id
  GROUP BY p.category, p.name
), ranked AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY units DESC) AS rn
  FROM sales
)
SELECT category, name, units
FROM ranked
WHERE rn = 1;

Quick reference

  • Say what one result row means before you write any SQL
  • Date ranges: ts >= start AND ts < next_start (half-open)
  • Count rows after each join to catch fan-out
  • Parts must add up: per-group totals = overall total
  • Top N per group: ROW_NUMBER() OVER (PARTITION BY g ORDER BY x DESC) then rn <= N
  • Share of total: SUM(x) / SUM(SUM(x)) OVER () in a grouped query
  • Name output columns for humans: revenue_eur, orders_count

Common mistakes

  • Writing the whole query at once and not knowing which part is wrong.
  • Using BETWEEN with timestamps and missing the last day's times.
  • Not checking for duplicated rows after a join.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Your revenue-per-country query totals 1.4 million, but SELECT SUM(total) FROM orders says 1.0 million. What is the most likely cause?

Question 2

2Which filter correctly selects all orders placed on 15 March 2026?

Question 3

3Which pattern answers "customers who never placed an order"?

Question 4

4Why use WITH (CTEs) in a long report query?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Using the shop schema, count how many orders each status has.

  2. Exercise 2medium

    Show monthly paid revenue for 2026 with each month's share of the year's total as a percentage.

  3. Exercise 3hard

    List customers whose 2026 spending fell by more than half compared with 2025, with both totals.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Where can I find a sample database to practise on?
pgexercises.com has a ready schema and graded questions in the browser. The dvdrental and Pagila samples load into a local Postgres in a minute.
How do I know my report is correct?
Reconcile it: compare totals against a simpler query, count rows after every join, and check a few rows by hand.
Should I memorise SQL syntax?
You will remember the common shapes naturally through practice. For rarer functions, looking them up in the PostgreSQL docs is normal even for experts.

Go deeper

ShareXLinkedInWhatsApp