Sub topic 5
Join conditions in the ON clause
This chapter assumes you can write a basic INNER JOIN between two tables and that you know what primary and foreign keys are. It uses the customers and orders tables from the sample schema. Order 104 has a NULL customer, and Chloe has no orders.
What the ON clause does
The ON clause is the rule that decides which pairs of rows belong together. Conceptually, the database considers each pair made from one row of the left table and one row of the right table. It evaluates the ON condition for that pair. If the result is true, the pair becomes a row of the join. If the result is false or unknown (NULL), the pair is discarded.
This is a model of the result, not the actual execution. The optimizer may use indexes or hash tables, but it must return the same rows.
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 is the typical shape: a foreign key column on one side compared with the primary key it references.
Conditions that combine several predicates
An ON clause can hold any boolean expression. You can join predicates with AND and OR, group them with parentheses, and call functions.
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
AND o.total > 30;This returns Ada's orders 101 and 102. Ben's order 103 has a matching customer, but its total of 20 fails the second predicate, so the pair is discarded.
For an inner join, putting a filter in ON or in WHERE gives the same result. The next chapter covers why that stops being true for outer joins. A common convention is to keep the relationship between the tables in ON and the question you are asking in WHERE. A reader can then see how the tables connect without scanning the filters.
Composite keys: one predicate per key column
When a key spans several columns, the ON clause must compare every one of them. The tables below use a two-column primary key.
CREATE TABLE price_list (
region CHAR(2) NOT NULL,
sku VARCHAR(20) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
PRIMARY KEY (region, sku)
);
CREATE TABLE stock (
region CHAR(2) NOT NULL,
sku VARCHAR(20) NOT NULL,
quantity INTEGER NOT NULL,
PRIMARY KEY (region, sku)
);
INSERT INTO price_list (region, sku, price) VALUES
('EU', 'A1', 10.00),
('EU', 'B2', 12.00),
('US', 'A1', 11.00);
INSERT INTO stock (region, sku, quantity) VALUES
('EU', 'A1', 5),
('US', 'A1', 7),
('US', 'B2', 3);
SELECT p.region, p.sku, p.price, s.quantity
FROM price_list AS p
INNER JOIN stock AS s
ON s.region = p.region
AND s.sku = p.sku;The result has two rows: EU/A1 and US/A1. The pairs EU/B2 (no stock row) and US/B2 (no price row) have no match.
If you compare only sku, each A1 price row matches both A1 stock rows, and B2 matches across regions. The result grows to five rows, and some of them pair a price with the wrong region's stock. Nothing warns you about this. The query runs and returns plausible-looking numbers.
Predicates that do not compare the two tables
A predicate does not have to reference both tables. A condition on one table only, such as o.total > 30, works as a filter on that side. A condition that references both sides is what links them. A join with no linking predicate is a Cartesian product with filters.
SELECT COUNT(*) AS pairs
FROM customers AS c
INNER JOIN orders AS o
ON 1 = 1;This returns 12, which is 3 customers times 4 orders. The condition is always true, so every pair survives. Accidental versions of this happen, for example when a predicate compares a column to itself (ON o.id = o.id) or when one table's alias is mistyped.
Some databases, such as MySQL, accept INNER JOIN without an ON clause and treat it as a cross join. PostgreSQL and the SQL standard require ON (or USING) for an inner join and report a syntax error. Do not depend on the permissive behavior.
Scope: what an ON clause can reference
An ON clause can refer to its own two join inputs and to any tables already joined to the left of it. It cannot refer to tables that appear later in the FROM clause.
-- Fails in most databases: alias i is not defined yet at this ON clause.
SELECT c.name
FROM customers AS c
INNER JOIN orders AS o
ON o.id = i.order_id
INNER JOIN order_items AS i
ON i.order_id = o.id;The first ON mentions i, which is introduced one line later. Move the condition to the join that introduces i, and keep each ON focused on the table it adds:
SELECT c.name, o.id AS order_id, i.quantity
FROM customers AS c
INNER JOIN orders AS o
ON o.customer_id = c.id
INNER JOIN order_items AS i
ON i.order_id = o.id;NULL in join conditions
A comparison with NULL yields unknown, never true, and that includes NULL = NULL. Order 104 has customer_id as NULL, so o.customer_id = c.id is unknown for every customer. The order is dropped.
If you really want NULL keys to match each other, you must say so explicitly. The standard form is IS NOT DISTINCT FROM, supported by PostgreSQL and several others. MySQL uses the <=> operator.
-- PostgreSQL: treats two NULLs as equal.
SELECT o.id, c.name
FROM orders AS o
INNER JOIN customers AS c
ON o.customer_id IS NOT DISTINCT FROM c.id;Here customers.id is a primary key and can never be NULL, so this query returns the same rows as the plain equality. The operator matters only when both sides can be NULL. Be sure that is the meaning you want, because most data models treat NULL as "unknown", not as a value that equals other unknowns.
Types and expressions in the condition
Both sides of a comparison should have compatible types. If you compare an integer to a text column, the database must convert one side. Depending on the system, this can produce errors or surprising matches (for example '01' and 1). It can also prevent the database from using an index on the converted column.
The same applies to expressions. ON LOWER(a.email) = LOWER(b.email) works, but a regular index on email cannot serve it. Prefer clean, typed key columns that you compare directly.
Debugging an ON clause
- Run the join as
SELECT *and read a few rows. Check that paired values really belong together. - Compare
COUNT(*)of the join with your expectation. Fewer rows than expected points to a too-strict condition orNULLkeys. More rows usually points to a missing key column or a one-to-many relationship. - Check for each table whether every key column appears in some
ONpredicate.
| Symptom | Likely cause |
|---|---|
| Row count equals the product of both table sizes | Condition always true or missing |
| Extra, partly wrong pairings | One column of a composite key left out |
| Rows with `NULL` keys missing | `=` with `NULL` is never true |
| Error about an unknown column or alias | `ON` references a table joined later |
Exercise
Write a query that returns each customer name with the ids of their orders worth 50.00 or more, using a single INNER JOIN with all conditions in ON. How many rows does it return for the sample data?
Show answer
SELECT c.name, o.id AS orderid FROM customers AS c INNER JOIN orders AS o ON o.customerid = c.id AND o.total >= 50; It returns 2 rows: Ada with order 101 (50.00) and Ada with order 102 (75.00). Ben's order totals 20.00, and order 104 has a NULL customer_id.
Exercise
In the price_list and stock example, you change the join to ON s.sku = p.sku and drop the region predicate. How many rows come back, and why?
Show answer
Five rows. Each of the two A1 price rows (EU and US) matches both A1 stock rows (2 x 2 = 4), and the EU B2 price row matches the US B2 stock row on sku alone (1 more). The region column is part of the key, so omitting it pairs rows that should not match.