Sub topic 1
Quick recap: how a join matches rows
Self joins and cross joins use the same matching rule as every other join. If you picture that rule clearly, both new join types are easy to follow. This chapter rebuilds the rule step by step, using a small data set whose results you can check by hand.
Prerequisites
This chapter assumes you can already do the following:
- Write basic
SELECT,WHERE, andORDER BYqueries. - Write
INNER JOINandLEFT JOINqueries with anONcondition. - Explain what primary keys and foreign keys are.
- Predict how
NULLbehaves in comparisons. - Use
GROUP BYwith aggregate functions such asSUMandCOUNT.
The examples use standard SQL and run in PostgreSQL, MySQL, and SQL Server. Where the dialects differ, the text says so.
The sample data
Two small tables are enough. Each order may belong to a customer through the foreign key customer_id. One order has no customer, and one customer has no orders. Both cases show up later.
CREATE TABLE customers (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE orders (
id INT PRIMARY KEY,
customer_id INT REFERENCES customers(id),
total INT NOT NULL
);
INSERT INTO customers (id, name) VALUES
(1, 'Ava'),
(2, 'Ben'),
(3, 'Chen');
INSERT INTO orders (id, customer_id, total) VALUES
(101, 1, 40),
(102, 1, 25),
(103, 2, 60),
(104, NULL, 15);The data has these properties:
- Ava has two orders.
- Ben has one order.
- Chen has none.
- Order 104 has a
NULLcustomer.
The matching rule
A join combines two row sources into one. Conceptually, the database does this:
- Take every possible pairing of one row from the left source and one row from the right source.
- Evaluate the
ONcondition for each pair. - Keep the pair only if the condition is true.
The second step has three possible outcomes: true, false, or unknown. Unknown happens when the condition involves NULL. A pair is kept only when the result is true. False and unknown are both discarded.
Real database engines do not build every pairing. They use indexes, hash tables, or sorted merges to find matches faster. The result is guaranteed to be the same as if they had built them all. This model is useful because you can predict the result of any join from it, and it explains the cross join later in this tutorial.
INNER JOIN: only matched pairs
An inner join returns only the pairs for which the condition is true.
SELECT c.name, o.id AS order_id, o.total
FROM customers c
INNER JOIN orders o ON o.customer_id = c.id
ORDER BY c.id, o.id;The result has three rows:
| name | order_id | total |
|---|---|---|
| Ava | 101 | 40 |
| Ava | 102 | 25 |
| Ben | 103 | 60 |
Chen is missing because no order matches him. Order 104 is missing because NULL = 1, NULL = 2, and NULL = 3 are all unknown, so no pair is true. Ava appears twice because two orders match her. A join returns one row per matching pair, not one row per customer.
LEFT JOIN: keep every left row
A left join starts with the inner join result. Then, for each left row that has no matching pair, it adds one row with NULL in every right-side column.
SELECT c.name, o.id AS order_id, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
ORDER BY c.id, o.id;The result has four rows:
| name | order_id | total |
|---|---|---|
| Ava | 101 | 40 |
| Ava | 102 | 25 |
| Ben | 103 | 60 |
| Chen | NULL | NULL |
Chen is kept with NULL values. Order 104 is still absent, because it is on the right side and has no match. A RIGHT JOIN would keep it instead. A FULL JOIN would keep both Chen and order 104. MySQL has no FULL JOIN.
This "keep the row with NULLs" behavior is what lets a later chapter keep the top of an employee hierarchy, because the top person has no manager.
Summary of join types
| Join type | Keeps unmatched left rows | Keeps unmatched right rows |
|---|---|---|
| INNER JOIN | No | No |
| LEFT JOIN | Yes, with NULLs | No |
| RIGHT JOIN | No | Yes, with NULLs |
| FULL JOIN | Yes, with NULLs | Yes, with NULLs |
The upcoming chapters need only the first two rows of this table, plus one more join type, CROSS JOIN, which has no ON condition at all.
Qualified names and aliases
The queries above already use two habits that the rest of the tutorial depends on.
First, each table gets a short alias in the FROM clause (customers c, orders o). Second, every column is written with its alias (c.name, o.total). Both customers and orders have a column named id, so an unqualified id would be ambiguous. Most databases reject it with an error such as column reference "id" is ambiguous.
Aliases are optional when each table appears once and the column names are unique. They become required when the same table appears twice in one query, because then the table name alone cannot say which copy you mean. The next chapter covers that case.
Two details are worth knowing now:
- After you alias a table, you must use the alias. In PostgreSQL,
FROM customers cfollowed bycustomers.nameis an error, because the original name is hidden. ASis optional for table aliases, socustomers AS candcustomers care equivalent. Oracle does not acceptASfor table aliases, so omitting it is the more portable choice.
Where the condition goes: ON versus WHERE
For an inner join, a condition in ON and the same condition in WHERE give the same rows. For a left join they do not, and this is the most common mistake in join queries.
Suppose you want every customer, along with only their orders above 30. Putting the filter in WHERE looks natural:
SELECT c.name, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.total > 30
ORDER BY c.id;This returns Ava (40) and Ben (60). Chen is gone. The left join first produced his row with o.total set to NULL. Then WHERE evaluated NULL > 30, got unknown, and discarded the row. The WHERE clause runs after the join, so it quietly turned the left join into an inner join.
Moving the filter into ON makes it part of the matching rule:
SELECT c.name, o.total
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.id
AND o.total > 30
ORDER BY c.id;| name | total |
|---|---|
| Ava | 40 |
| Ben | 60 |
| Chen | NULL |
Now Ava's 25-unit order fails the condition, so it is not a match. Chen has no matches, so he is kept with NULL. As a rule, put conditions that define which rows match in ON, and put conditions that filter the final result in WHERE.
Matches multiply rows
A join returns one row per matching pair. When the relationship is one-to-many, as with one customer and many orders, each left row is repeated once per match. This matters as soon as you add aggregates. Counting rows after a join counts pairs, not customers.
SELECT c.name, COUNT(o.id) AS order_count, COALESCE(SUM(o.total), 0) AS spent
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY c.id;| name | order_count | spent |
|---|---|---|
| Ava | 2 | 65 |
| Ben | 1 | 60 |
| Chen | 0 | 0 |
Two details make this query correct:
COUNT(o.id)counts only non-NULLvalues, so Chen'sNULL-extended row counts as 0.COUNT(*)would report 1 for him, which is wrong.SUMover onlyNULLvalues returnsNULL, soCOALESCE(..., 0)converts that to 0.
Later chapters use this same pattern, a left join followed by COUNT or SUM with COALESCE, to report zeros for combinations that have no data.
The mental checklist
Before you run a join, answer these questions:
- Which table is on the left, and do I need all of its rows? If yes, use
LEFT JOIN. - What is the matching rule in
ON, and can a left row match zero, one, or many right rows? - Can the key columns be
NULL? Those rows never match with=. - How many rows should the result have? Estimate it, then compare with what the query returns.
Question 4 is the habit that catches most join bugs. For the inner join above, you can reason that the answer equals the number of orders with a non-NULL customer, which is 3. A result that differs from your estimate means either the data or the condition is not what you thought.
Common errors at a glance
| Symptom | Likely cause |
|---|---|
| `column reference "id" is ambiguous` | An unqualified column name exists in both tables. |
| Left rows with no match disappear | A right-side filter in `WHERE` instead of `ON`. |
| Totals are too large | A one-to-many join repeated rows before `SUM`. |
| A count is 1 instead of 0 for unmatched rows | `COUNT(*)` used instead of `COUNT(right_column)`. |
| Rows with a `NULL` key never match | `NULL = NULL` is unknown, not true. |
Where this goes next
Every join so far connects two different tables. The next chapter shows that the same rule works when both sides are the same table, and why aliases then become mandatory. Later chapters drop the ON condition entirely and look at what the first step of the matching rule produces by itself: every possible pairing.
Exercise
Using the sample customers and orders tables, how many rows does SELECT c.name, o.id FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.id IS NOT NULL return, and why is it the same as the inner join result?
Show answer
It returns 3 rows: Ava with orders 101 and 102, and Ben with order 103. The left join first adds Chen with a NULL order id, and the WHERE clause then removes every row whose o.id is NULL. That deletes exactly the rows the left join added, so the outcome equals the inner join.
Exercise
Write a query that lists every customer with the number of orders over 30 they placed, showing 0 for customers with none. What does it return for Ava, Ben, and Chen?
Show answer
SELECT c.name, COUNT(o.id) AS bigorders FROM customers c LEFT JOIN orders o ON o.customerid = c.id AND o.total > 30 GROUP BY c.id, c.name ORDER BY c.id; The condition o.total > 30 goes in ON so that Chen is kept. The result is Ava 1 (order 101), Ben 1 (order 103), Chen 0. COUNT(o.id) ignores the NULL on Chen's row.