MintQueryStart free
← All guides

SQL JOIN practice: 5 exercises you can run in the browser

You are the first analyst at a newly opened online coffee shop. It has four customers so far, four orders, and a founder who keeps asking questions. Each exercise below is one of those questions, easiest first. The tables are small enough to check every answer by eye, and there is nothing to install and no account needed.

The tables

customers
idname
1Ana
2Ben
3Chloe
4Dev
orders
order_idcustomer_idamount
101150
102130
103220
104375

Dev has no orders. Exercise 5 uses a third table, employees, shown there.

Exercise 1: your first INNER JOIN

Which customer placed each order?

List every order with the name of the customer who placed it. Show order_id and name, sorted by order_id.

Hint

Match orders.customer_id to customers.id.

Show solution
SELECT o.order_id, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id
ORDER BY o.order_id;
order_idname
101Ana
102Ana
103Ben
104Chloe

Exercise 2: keep everyone with a LEFT JOIN

Give me everyone on the customer list with what they bought, even the ones who bought nothing.

Show every customer's name with the amount of each of their orders. Customers with no orders must still appear. Sort by name, then order_id.

Hint

Start from the table you want to keep in full.

Show solution
SELECT c.name, o.amount
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
ORDER BY c.name, o.order_id;
nameamount
Ana50
Ana30
Ben20
Chloe75
DevNULL

Exercise 3: find who is missing

Who signed up and never ordered? I want to email them.

Show the name of every customer who has never placed an order.

Hint

After a LEFT JOIN, a customer with no orders has NULL in the order columns.

Show solution
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.order_id IS NULL;
name
Dev

Exercise 4: join, then total

How much has each customer spent so far?

Show each customer's name and the total they spent as total_spent. Customers with no orders should show 0. Sort by name.

Hint

SUM over no orders gives NULL. COALESCE turns it into 0.

Show solution
SELECT c.name, COALESCE(SUM(o.amount), 0) AS total_spent
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.name
ORDER BY c.name;
nametotal_spent
Ana80
Ben20
Chloe75
Dev0

Exercise 5: join a table to itself

We hired a few people. Who reports to whom?
employees
idnamemanager_id
1MayaNULL
2Omar1
3Lena1
4Raj2

Show every employee with their manager's name, as employee and manager. Maya has no manager and should still appear. Sort by employee.

Hint

Use the employees table twice, with two different aliases.

Show solution
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id
ORDER BY e.name;
employeemanager
LenaMaya
MayaNULL
OmarMaya
RajOmar

You just wrote five JOINs. MintQuery has 500+ more exercises like these, in lessons of a few minutes.

Start freeGet the app