SQL · Level 2 Joins

SQL LEFT JOIN

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

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;

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.

Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.

customers 3 rows
idINTEGERnameTEXT
1Ana
2Bo
3Cy
orders 4 rows
idINTEGERcustomer_idINTEGERcreated_atTEXT
1012024-02-01
1112024-05-01
1222023-12-30
1312023-06-01
solution.sql
Test Suites Pending
Output