Skip to main content

Chapter 5 · JOINs

SQL JOINs Practice

Real data is split across tables: customers in one, orders in another, products in a third. JOINs put them back together using the keys that link them, such as orders.customer_id = customers.id.

The key decision is which rows to keep. INNER JOIN keeps only matches; LEFT JOIN keeps every row from the left table, so you can find customers with no orders or products that never sold.

Start practising75 exercises · 10 easy, 63 medium, 2 hard

Key ideas

INNER JOIN
Rows that match in both tables. Unmatched rows disappear.
LEFT JOIN
Every row from the left table; columns from the right are NULL when there is no match.
Anti-join
LEFT JOIN … WHERE right.id IS NULL finds rows with no match (customers who never ordered).
Self join
Join a table to itself, e.g. to compare rows within the same table.

Example: Customers with the most orders (including those with none)

SELECT c.first_name, c.last_name,
       COUNT(o.id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.first_name, c.last_name
ORDER BY orders DESC
LIMIT 5;

LEFT JOIN keeps customers without orders, and COUNT(o.id) counts them as 0 instead of 1.

In interviews

Expect "find customers who never placed an order". Show the LEFT JOIN + IS NULL pattern, then mention NOT EXISTS as an alternative.

All 75 JOINs exercises

Ordered from easiest to hardest. Each one runs on a real database with instant feedback.