SQL JOIN Practice: Customers and Their Orders

Data is usually split across tables so that facts are stored once. A customer lives in one table and the orders that refer to the customer live in another. A JOIN reconnects them. This exercise matches the customer id in orders to the id in customers.

Before you start: SELECT, WHERE and the idea of a key shared between two tables.

Your task

List each customer name together with the amount of each of their orders. Include only customers who have orders, and order the rows by name and then amount.

Starter code

CREATE TABLE customers (id INTEGER, name TEXT);
CREATE TABLE orders (customer_id INTEGER, amount INTEGER);
INSERT INTO customers VALUES (1, 'Asha'), (2, 'Ravi'), (3, 'Meera');
INSERT INTO orders VALUES (1, 120), (2, 80), (1, 200);

-- Join the two tables to list customer names and order amounts.

Expected result

name | amount
Asha | 120
Asha | 200
Ravi | 80

Compare column names and values rather than exact spacing.

Open this exercise

Loads the starter in the workspace. Save or export existing work first. Return here for hints and the explanation.

Need a hint?

Start from customers, JOIN orders ON orders.customer_id = customers.id, then select customers.name and orders.amount.

Show the complete solution and walkthrough
CREATE TABLE customers (id INTEGER, name TEXT);
CREATE TABLE orders (customer_id INTEGER, amount INTEGER);
INSERT INTO customers VALUES (1, 'Asha'), (2, 'Ravi'), (3, 'Meera');
INSERT INTO orders VALUES (1, 120), (2, 80), (1, 200);

-- Join the two tables to list customer names and order amounts.
SELECT customers.name, orders.amount
FROM customers
JOIN orders ON orders.customer_id = customers.id
ORDER BY customers.name, orders.amount;
  1. Select customers.name and orders.amount. Prefixing each column with its table name makes the query clear.
  2. Write FROM customers JOIN orders ON orders.customer_id = customers.id. Each order is matched to the customer whose id it stores.
  3. Add ORDER BY customers.name, orders.amount. The result has three rows: Asha 120, Asha 200 and Ravi 80.

A common mistake

Forgetting the ON condition (or joining on the wrong columns) pairs every customer with every order. Selecting a bare id column can be ambiguous when both tables use the same name.

Try an edge case

Meera has no orders, so she is absent from an inner join. Use LEFT JOIN when you also want customers without orders; their amount will be NULL.

Take it one step further

Change JOIN to LEFT JOIN and see Meera appear. Then combine the join with GROUP BY to total each customer’s orders.

Read the sql tool guide