Overview
Count each customer's orders, including customers with zero, with LEFT JOIN, and avoid the WHERE that silently turns it back into an inner join.
- LEFT JOIN keeps every left row
- Right-table conditions go in ON
- COUNT(column) gives 0 for no match
Short Course
LEFT JOIN keeps every row of the left table and fills in NULL where nothing
matched. Trap: a condition on the right table in WHERE throws those NULL
rows away again; put it in the ON clause. Count with COUNT(column), which
gives 0 for no match.
SELECT p.name, COUNT(r.id) AS five_stars
FROM products AS p
LEFT JOIN reviews AS r
ON r.product_id = p.id AND r.stars = 5 -- in ON, not in WHERE
GROUP BY p.id, p.name;
Task
Return every customer's name with their number of orders placed in 2024,
including customers with 0, ordered by name. In the database below, Bo only
ordered in 2023, so Bo has 0.
Database
Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.
| idINTEGER | nameTEXT |
|---|---|
| 1 | Ana |
| 2 | Bo |
| 3 | Cy |
| idINTEGER | customer_idINTEGER | created_atTEXT |
|---|---|---|
| 10 | 1 | 2024-02-01 |
| 11 | 1 | 2024-05-01 |
| 12 | 2 | 2023-12-30 |
| 13 | 1 | 2023-06-01 |
Test Suites
Pending
Next
Output