Sub topic 5
Join Conditions in the `ON` Clause
Assume you know basic SELECT, FROM, and WHERE syntax, plus primary and foreign keys. This chapter focuses on how the ON clause decides which rows an inner join pairs.
The `ON` clause defines a match
An inner join examines rows from two tables. The condition after ON determines which combinations count as matches. Only matching combinations appear in the result.
Using the sample customers and orders tables:
SELECT c.name, o.id AS order_id, o.total
FROM customers AS c
INNER JOIN orders AS o
ON o.customer_id = c.id;The condition o.customer_id = c.id connects each order to its customer. It compares the foreign key in orders with the primary key in customers.
| Customer | Order | Match condition |
|---|---|---|
| Ada | 101 | `1 = 1` |
| Ada | 102 | `1 = 1` |
| Ben | 103 | `2 = 2` |
Chloe has no matching order, so she is excluded. Order 104 has a NULL customer ID, so it does not match any customer.
Think in terms of candidate pairs
Conceptually, the database considers possible pairs of rows and keeps the pairs for which the ON expression is true.
The database optimizer usually avoids literally comparing every possible pair. This conceptual model explains the result, while indexes and other execution strategies determine how the database finds matches efficiently.
Add conditions to the match
An ON clause can contain multiple conditions. Use AND when both conditions must be true.
SELECT c.name, o.id AS order_id, o.order_date
FROM customers AS c
INNER JOIN orders AS o
ON o.customer_id = c.id
AND o.total >= 50;This query matches an order to its customer only when the customer ID matches and the order total is at least 50. Ada's orders 101 and 102 qualify. Ben's order does not.
The ON clause can also use other comparison operators:
| Operator | Meaning |
|---|---|
| `=` | Values are equal |
| `<>` | Values are different |
| `>=` | Left value is at least the right value |
| `BETWEEN` | A value is inside a range |
For example, a range condition can match orders to discount tiers:
SELECT o.id, o.total, t.label
FROM orders AS o
INNER JOIN discount_tiers AS t
ON o.total >= t.min_total
AND o.total < t.max_total;This is called a non-equality join because it does not rely on one equality comparison.
`ON` versus `WHERE`
For an inner join, moving a condition between ON and WHERE often produces the same rows:
SELECT c.name, o.id
FROM customers AS c
INNER JOIN orders AS o
ON o.customer_id = c.id
WHERE o.total > 30;Here, ON establishes the customer-order relationship. WHERE filters the already joined rows. Keeping those roles separate makes the query easier to read and becomes important when you later use outer joins.
Exercise
What rows does this query return: SELECT c.name, o.id FROM customers AS c INNER JOIN orders AS o ON o.customer_id = c.id AND o.total > 60;?
Show answer
It returns Ada with order 102 only. Order 101 is below 60, Ben's order is below 60, Chloe has no order, and order 104 has no customer match.