Joins and Queries
Reassemble normalized tables with inner and left joins, predict how many rows a join returns, and aggregate data with GROUP BY.
Welcome back!
Step 1 of 13Learn
Putting the pieces back together
Normalization splits data into many tables. Joins put it back together at query time. To list orders with customer names:
SELECT o.order_id, o.order_date, c.name
FROM orders AS o
JOIN customer AS c ON c.customer_id = o.customer_id;For each order row, the database finds the customer row whose customer_id matches and combines them. The ON clause states the matching condition, almost always "foreign key equals primary key." The short aliases (o, c) keep the query readable.
You can chain joins across several tables. To list which books each customer bought:
SELECT c.name, b.title, ol.quantity
FROM customer AS c
JOIN orders AS o ON o.customer_id = c.customer_id
JOIN order_line AS ol ON ol.order_id = o.order_id
JOIN book AS b ON b.book_id = ol.book_id;Notice how the joins follow the foreign keys in the design, like walking along the lines of the ER diagram. A clean design makes queries predictable: if you know the diagram, you know how to write the join. A design with missing or ambiguous keys forces awkward string matching on names, which is slow and wrong whenever two customers share a name.
Step 2 of 13Practice · Code challenge · SQL
Code challenge · SQL
List which books each customer bought: return the customer name, the book title and the quantity, one row per order line.
Follow the foreign keys: customer → orders → order_line → book.
The database for this exercise (tables and rows)
CREATE TABLE customer (
customer_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
city TEXT
);
CREATE TABLE book (
book_id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
price REAL NOT NULL CHECK (price >= 0)
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
order_date TEXT NOT NULL,
customer_id INTEGER NOT NULL REFERENCES customer (customer_id)
);
CREATE TABLE order_line (
order_id INTEGER NOT NULL REFERENCES orders (order_id),
book_id INTEGER NOT NULL REFERENCES book (book_id),
quantity INTEGER NOT NULL CHECK (quantity > 0),
unit_price REAL NOT NULL,
PRIMARY KEY (order_id, book_id)
);
INSERT INTO customer VALUES
(1, 'Ana Silva', 'ana@example.com', 'Lisbon'),
(2, 'Ben Carter', 'ben@example.com', 'Leeds'),
(3, 'Chen Wei', 'chen@example.com', 'Austin'),
(4, 'Dana Moore', 'dana@example.com', 'Austin');
INSERT INTO book VALUES
(10, 'Designing Data', 39.00),
(11, 'SQL Pocket Guide', 18.50),
(12, 'Keys and Tables', 24.00);
INSERT INTO orders VALUES
(501, '2026-02-01', 1),
(502, '2026-02-03', 2),
(503, '2026-02-10', 1);
INSERT INTO order_line VALUES
(501, 10, 1, 39.00),
(501, 11, 2, 18.50),
(502, 12, 1, 24.00),
(503, 11, 1, 18.50);- Result matches the expected table
Step 3 of 13Practice · Choose one
Which ON condition correctly joins order_line to book?
Step 4 of 13Learn
Inner joins and left joins
The plain JOIN above is an INNER JOIN: it returns only rows that have a match on both sides. A customer with no orders doesn't appear in a customer–orders inner join at all.
Often you want every row from one table, matched or not. A LEFT JOIN (LEFT OUTER JOIN) keeps every row from the left table; where there's no match, the right table's columns come back as NULL:
SELECT c.name, o.order_id
FROM customer AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id;Customers without orders appear once, with order_id NULL. That makes LEFT JOIN the tool for questions like "which customers have never ordered?": add WHERE o.order_id IS NULL.
A classic mistake is putting a condition on the right table in the WHERE clause of a LEFT JOIN. WHERE o.order_date >= '2026-01-01' throws away the NULL rows, silently turning the query back into an inner join. If you want "all customers, with their orders from 2026 if any," put the date condition in the ON clause instead.
RIGHT JOIN is the mirror image and is rarely needed (swap the table order). FULL OUTER JOIN keeps unmatched rows from both sides.
Step 5 of 13Practice · Code challenge · SQL
Code challenge · SQL
Which customers have never placed an order? Return their name.
The starter uses an inner join, which can never show a customer without orders.
The database for this exercise (tables and rows)
CREATE TABLE customer (
customer_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
city TEXT
);
CREATE TABLE book (
book_id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
price REAL NOT NULL CHECK (price >= 0)
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
order_date TEXT NOT NULL,
customer_id INTEGER NOT NULL REFERENCES customer (customer_id)
);
CREATE TABLE order_line (
order_id INTEGER NOT NULL REFERENCES orders (order_id),
book_id INTEGER NOT NULL REFERENCES book (book_id),
quantity INTEGER NOT NULL CHECK (quantity > 0),
unit_price REAL NOT NULL,
PRIMARY KEY (order_id, book_id)
);
INSERT INTO customer VALUES
(1, 'Ana Silva', 'ana@example.com', 'Lisbon'),
(2, 'Ben Carter', 'ben@example.com', 'Leeds'),
(3, 'Chen Wei', 'chen@example.com', 'Austin'),
(4, 'Dana Moore', 'dana@example.com', 'Austin');
INSERT INTO book VALUES
(10, 'Designing Data', 39.00),
(11, 'SQL Pocket Guide', 18.50),
(12, 'Keys and Tables', 24.00);
INSERT INTO orders VALUES
(501, '2026-02-01', 1),
(502, '2026-02-03', 2),
(503, '2026-02-10', 1);
INSERT INTO order_line VALUES
(501, 10, 1, 39.00),
(501, 11, 2, 18.50),
(502, 12, 1, 24.00),
(503, 11, 1, 18.50);- Result matches the expected table
Step 6 of 13Try the calculator
How many rows will a join return?
Customers place orders. An inner join returns one row per matching order; a left join adds one row for each customer with no orders.
- Rows from customer INNER JOIN orders
- 250
- Rows from customer LEFT JOIN orders
- 280
- Rows from a cross join with no ON condition
- 25,000
Step 7 of 13Practice · Work it out
A school has 40 students. 30 of them have enrolled in courses, with 95 enrollment rows in total; the other 10 have no enrollments. How many rows does student LEFT JOIN enrollment return?
Step 8 of 13Learn
Aggregating with GROUP BY
Many questions are about totals: revenue per book, orders per customer, average order size. Aggregate functions, COUNT, SUM, AVG, MIN and MAX, combined with GROUP BY, answer them:
SELECT b.title, SUM(ol.quantity) AS copies_sold
FROM book AS b
JOIN order_line AS ol ON ol.book_id = b.book_id
GROUP BY b.book_id, b.title
ORDER BY copies_sold DESC;GROUP BY collapses all rows with the same book into one output row, and SUM adds their quantities. Every column in the SELECT list must either be in the GROUP BY or be inside an aggregate. HAVING filters groups after aggregation (HAVING SUM(ol.quantity) > 100), while WHERE filters individual rows before it.
Here the design pays off again. Because quantities live in one place (order_line) and titles in another (book), the totals can't double count: each sale is one row. In the original flat spreadsheet, where books were packed into a text cell, this query would have been impossible without parsing strings.
Watch out for joins that multiply rows before aggregating. Joining orders to both order lines and payments in one query pairs every line with every payment, and sums come out inflated. Aggregate each child table separately, then join the results.
Step 9 of 13Note
Step 10 of 13Practice · True or false
In a query with GROUP BY, WHERE filters rows before they are grouped, while HAVING filters the groups after aggregation.
Step 11 of 13Practice · Diagram
The logical order a SELECT runs in
You write SELECT first, but the database works through the clauses in this order. That is why WHERE cannot use an aggregate and HAVING can.
A filter "only customers with more than 5 orders" belongs in which clause?
Tap the shape that answers the question, then press Check.
- FROM and JOIN
Build the combined rows.
- WHERE
Filter individual rows.
- GROUP BY
Collapse rows into groups.
- HAVING
Filter whole groups, using aggregates.
- SELECT
Compute the output columns and aliases.
- ORDER BY
Sort the final result; it can use aliases.
Step 12 of 13Practice · What would you do?
What would you do?
A report must list every customer with the number of orders they have placed, including customers with zero orders. Which query shape is correct?
Step 13 of 13Practice · Choose one
A query joins orders to order_line (average 3 lines per order) and to payment (average 2 payments per order) at the same time, then sums the payment amounts per order. What goes wrong?
Lesson complete!