Join predicates: match rows with ON and USING
Overview
A join combines rows from two table expressions. A join predicate specifies which pair qualifies as a match. In the shop database, orders.customer_id references customers.id; an equality predicate connects each order with its customer. Read the relationship first, then write the predicate.
First example
SELECT o.id, c.nameFROM orders AS o JOIN customers AS c ON o.customer_id = c.idORDER BY o.id;Observed SQLite result (rows in JSON):
[ [ 101, "Alice" ], [ 102, "Alice" ], [ 103, "David" ]]How it works
ON accepts a Boolean expression: only TRUE matches; FALSE and UNKNOWN do not. Qualify id with the table alias to avoid ambiguity. USING (product_id) is appropriate only when both inputs have that column name; it merges the named output columns in an unqualified SELECT *. The second example uses a derived table (a parenthesized SELECT with an alias) to expose products.id as product_id. NATURAL JOIN infers all shared names, so schema changes can silently alter matching; prefer explicit ON or USING. The logical pairing model does not require the database to physically build every pair.
Practical example
SELECT i.order_id, product_id, p.nameFROM order_items AS iJOIN (SELECT id AS product_id, name FROM products) AS pUSING (product_id)ORDER BY i.order_id, product_id;Observed SQLite result (rows in JSON):
[ [ 101, 1, "Notebook" ], [ 101, 2, "Pen" ], [ 102, 3, "Bag" ], [ 103, 2, "Pen" ]]Practice and mistakes
Practice: join order_items to products with ON instead of USING, returning order_id and name for order 101. Predict two rows. Do not match orders.id to customers.id merely because both columns are called id. For a composite relationship, include every key component; an additional test compares complete and incomplete predicates.