Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write SQL that lists every product with its total quantity sold in the last 30 days, showing 0 for products that sold nothing. Tables: products(id, name), order_lines(product_id, qty, sold_at).

We start from products and LEFT JOIN order_lines with both the product match and the 30 day date condition in the ON clause, then group by product and show COALESCE(SUM(l.qty), 0). Putting the date filter in WHERE instead would remove every product that sold nothing, because its NULL sold_at fails the comparison. An index on order_lines(product_id, sold_at) serves the join and the date range together.

Why this question is asked

Lists that must include everything, even items with no activity, are common in dashboards and stock reports: every product, every branch, every sales rep, with zero where nothing happened. The query is short but has three places where a small slip makes rows disappear or shows the wrong number. Interviewers use it to test outer joins, NULL handling in aggregates and the difference between COUNT(*) and COUNT(column). In this answer, we will write the query, see why the date filter must sit in ON, look at how COALESCE and COUNT behave on unmatched rows, and choose the index that makes it fast.

1A Quick Recap: Keeping Rows With No Match

An inner join between products and order_lines returns only products that have at least one matching line, so unsold products vanish. A LEFT JOIN keeps every row of the left table, products, and for a product with no matching line it returns one row with the order_lines columns set to NULL. That NULL row is what lets an unsold product appear in the report.

Aggregates treat those NULLs in a specific way. SUM ignores NULL inputs and, if every input is NULL, returns NULL rather than 0. COUNT(*) counts rows, including the NULL-padded one, while COUNT(column) counts only non-NULL values. Both facts matter here.

2Writing the Query

Tables are products(id, name) and order_lines(product_id, qty, sold_at).

SQL
SELECT p.id,
p.name,
COALESCE(SUM(l.qty), 0) AS sold_last_30_days
FROM products p
LEFT JOIN order_lines l
ON l.product_id = p.id
AND l.sold_at >= now() - interval '30 days'
GROUP BY p.id, p.name
ORDER BY sold_last_30_days DESC, p.id;
-- 7 | Desk lamp | 412
-- 3 | Notebook A5 | 128
-- 12 | Umbrella | 0 sold last winter, nothing in the last 30 days
-- 15 | Gift card | 0 never sold
Step throughHow an unsold product reaches the result
  1. Start from productsevery product is preserved
  2. LEFT JOIN on product and date in ONUmbrella's old lines fail the date test
  3. No matching line?
    Yesone row with NULL qtyNoone row per matching line
  4. GROUP BY productSUM(NULL) gives NULL
  5. COALESCE(SUM(l.qty), 0)Umbrella shows 0

5 steps in order. Play them, or step through them one at a time.

Every product appears exactly once. Products that sold in the window show their total quantity, and products with no line in the window show 0. We group by p.id as well as p.name, because two products may share a name, and sort by p.id as a tiebreaker so the order is stable.

3Why the Date Filter Must Be in ON

The most common mistake is to write the date condition in WHERE.

SQL
SELECT p.id, p.name, COALESCE(SUM(l.qty), 0) AS sold
FROM products p
LEFT JOIN order_lines l ON l.product_id = p.id
WHERE l.sold_at >= now() - interval '30 days'
GROUP BY p.id, p.name;
-- 7 | Desk lamp | 412
-- 3 | Notebook A5 | 128 Umbrella and Gift card are gone

WHERE runs after the join. The Gift card's NULL-padded row has sold_at NULL, and NULL >= some date is unknown, so WHERE drops it. The Umbrella has old lines, which fail the date test and are dropped too, and then it has no rows left at all. The result is an inner join in disguise, and COALESCE never gets a chance to produce a 0, because the rows it would have worked on no longer exist.

In the ON clause, the date test is part of matching instead. The Umbrella's old lines simply do not match, so the LEFT JOIN treats it like a product with no lines and keeps it with NULLs. Conditions that describe which child rows count belong in ON; conditions that choose which parent rows to report, such as WHERE p.active, belong in WHERE.

4COALESCE, COUNT(*) and COUNT(column)

For an unsold product, the group contains a single row whose qty is NULL. SUM over it returns NULL, which a dashboard may show as an empty cell or which Java may read as null and fail on unboxing. COALESCE(SUM(l.qty), 0) returns the first non-NULL argument, turning that NULL into 0.

If the report also counts how many lines each product had, the choice of COUNT matters.

SQL
SELECT p.name,
COUNT(*) AS wrong_lines, -- Gift card: 1 (counts the NULL-padded row)
COUNT(l.product_id) AS lines -- Gift card: 0 (ignores NULLs)
FROM products p
LEFT JOIN order_lines l
ON l.product_id = p.id AND l.sold_at >= now() - interval '30 days'
GROUP BY p.id, p.name;

COUNT(*) counts rows, and the unsold product still has its one padded row, so it reports 1 line sold. COUNT on a column from order_lines, ideally one that is never NULL in a real line, such as product_id or the line's primary key, ignores the padding and gives the correct 0.

5The Index That Makes It Fast

An index on order_lines(product_id, sold_at) fits this query well. Entries are sorted by product first and by date within each product, so for each product the database can jump to that product's entries and read only the last 30 days, skipping the older history. Adding qty as an included column, INCLUDE (qty) in PostgreSQL, lets it answer from the index alone.

For a report over all products, the planner may instead scan the last 30 days of order_lines through an index on sold_at, aggregate by product, and join the small result to products. A variant that encourages that shape is to aggregate first in a subquery, SELECT product_id, SUM(qty) FROM order_lines WHERE sold_at >= now() - interval '30 days' GROUP BY product_id, and LEFT JOIN it to products. Here the date filter may live in the subquery's WHERE, because that WHERE runs before the outer join and only removes lines, never products. EXPLAIN on realistic data decides which form is faster.

6Follow-up questions

Should the 30 days be rolling or calendar days?

now() - interval '30 days' is a rolling window from this moment, so the result changes during the day. For a report that should be stable for a whole day, compare with current_date - 30, or better, with explicit boundaries in the business time zone, using a half-open range.

How would this look in MySQL?

The same query works with the interval written as NOW() - INTERVAL 30 DAY. MySQL also lets IFNULL replace COALESCE, but COALESCE is standard and works in both.

What if order_lines has hundreds of millions of rows?

The index on (product_id, sold_at) keeps the query reading only recent lines. If the report runs constantly, a daily summary table of quantity per product per day makes it a sum over 30 small rows per product.

7Conclusion

In this answer, we listed every product with its quantity sold in the last 30 days by starting from products and LEFT JOINing order_lines with the date condition in ON, so products with no recent sales keep their NULL-padded row. COALESCE turns their NULL sum into 0, COUNT on a column of order_lines counts their lines as 0 where COUNT(*) would say 1, and an index on order_lines(product_id, sold_at) serves the join and the date range.

What to say in the interviewAbout 90 seconds aloud

Open with

I would start from products, because every product must appear, and LEFT JOIN order_lines on product_id, with the date condition, sold_at within the last 30 days, also in the ON clause.

Then, if they want more

Then group by p.id and p.name and select COALESCE of SUM of qty with 0. The placement of the date filter is the important part.

If I put it in WHERE, it runs after the join: a product that never sold has a NULL sold_at, and NULL compared to a date is unknown, so the row is dropped, and a product whose sales are all older loses all its rows too. The outer join silently becomes an inner join and those products vanish.

In ON, the date is part of matching, so old lines just do not match and the product is kept with NULLs. COALESCE is needed because SUM over only NULLs returns NULL, not zero.

If I also count lines, I count a column from order_lines, like l.product_id, because COUNT star counts the NULL-padded row and would report one line for an unsold product. I group by the id as well as the name since names may repeat.

For performance, an index on order_lines product_id and sold_at, possibly including qty, lets the database read only the recent lines for each product. Alternatively I can aggregate recent lines first in a subquery and left join that to products.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write SQL that lists every product with its total quantity sold in the last 30 days...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/00e0b1a809/