SQL Examples
Work through a few shop questions as if you were building a small reporting screen. Each question should state the rows it needs, the meaning of each amount, and the order a user expects to see.
Understand the idea
Start with a product list, then a paid-order summary, then a customer report. Keep each result's grain clear. For the worked example, the result has one row per customer and counts only paid orders. A left join keeps customers with none. Try explaining why the status condition belongs in ON before opening the solution.
Where to try it
Run this example in the SQL playground. The lesson link loads the shop tables and sample rows before this query. Select Run when you are ready. Every run starts fresh, so your changes do not affect the website or a previous run.
SQLite sample data · MySQL / MariaDB sample data · See the sample tables
Your task
Before viewing the solution, write a report that keeps every customer and shows paid order count and paid total. Verify the two zero-count customers explicitly.
Show the worked solution
SELECT c.name, COUNT(o.order_id) AS paid_orders,
COALESCE(SUM(o.total_cents), 0) AS paid_cents
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id AND o.status = 'paid'
GROUP BY c.customer_id, c.name
ORDER BY c.customer_id;
Check your result
Mira has 1 paid order worth 2300 cents, Dev has 1 worth 1350, and Asha and Noor each have 0 and 0. All four customers remain.