×

sql · level 3 · unit 7 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Shipped queries survive edge cases, not only the sample data.

A query that works on today's data can fail tomorrow. Professionals hunt for every : a day with no sales, two customers tied, a NULL amount, broken JSON, a customer with no orders. Then they test the same query on several datasets.

The checklist: filter bad rows once, in a view or CTE. Fill gaps with a series and COALESCE. Break every tie in ORDER BY. Handle NULL on purpose.

This report works even for Bath, where nobody has ordered yet.

WITH city_spend AS (
  SELECT c.city, COALESCE(SUM(o.total), 0) AS spent
  FROM customers AS c
  LEFT JOIN orders AS o ON o.customer_id = c.id
  GROUP BY c.city
)
SELECT city, spent,
  RANK() OVER (ORDER BY spent DESC) AS place,
  ROUND(100.0 * spent / SUM(spent) OVER (), 1) AS pct
FROM city_spend
ORDER BY place, city;

Ask what each query does with no rows at all. It should still give a sensible answer.