man postgres/joins
lesson 4 of 34 · Querying
Joins
The task: list every customer, with their paid orders if they have any. A LEFT JOIN keeps customers without a match, so this looks right:
SELECT c.name, o.id AS order_id, o.total
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
WHERE o.status = 'paid'
ORDER BY c.id, o.id;name | order_id | total ------+----------+------- Ada | 107 | 27.50 Ben | 105 | 31.00 Dara | 110 | 64.00 (3 rows)
Three customers, not six. Chen, Eli and Farah have no paid order, and they are gone, although the LEFT JOIN was there to keep them. The join did keep them; the WHERE clause removed them afterwards. To see why, and to stop guessing where a condition goes, it helps to know exactly which rows each kind of join produces. That is what this lesson builds up, one pair of rows at a time.
The data
The customers and orders of the lesson on NULL, unchanged, plus the cities the roaster has a shipping zone for. Braga and Coimbra have customers but no zone; Faro has a zone but no customers yet. The data is in the setup script.
CREATE TABLE shipping_zones (
city text PRIMARY KEY,
zone text NOT NULL,
fee numeric(5,2) NOT NULL
);
SELECT * FROM shipping_zones ORDER BY city;city | zone | fee --------+------+------ Faro | B | 5.00 Lisbon | A | 3.50 Porto | A | 3.50 (3 rows)
SELECT id, name, city, referred_by FROM customers ORDER BY id;id | name | city | referred_by ----+-------+---------+------------- 1 | Ada | Lisbon | 2 | Ben | Porto | 1 3 | Chen | Lisbon | 1 4 | Dara | Braga | 5 | Eli | Porto | 3 6 | Farah | Coimbra | (6 rows)
The orders are the twelve from before. Every box on this page gives the same output live as recorded.
Every join starts as all the pairs
A CROSS JOIN pairs every row of the left table with every row of the right one. Six customers and three zones make eighteen pairs:
SELECT count(*) AS pairs
FROM customers CROSS JOIN shipping_zones; pairs
-------
18
(1 row)(FROM customers, shipping_zones, with a comma, means the same.) On its
own a cross join is rarely what you want, but it is how every other join is
defined. An inner join with a condition is the cross join, filtered to the
pairs for which the ON condition is true. The outer joins then add rows
back for the rows that found no partner. This is the logical meaning, as in
the first lesson: the server does not build all the pairs. It picks a plan
(nested loop, hash join, merge join) that returns the same rows.
Step through the pairs for one customer at a time:
Each of the six customers is compared with the three shipping zones on z.city = c.city. Ada, Ben, Chen and Eli match one zone each and form the four rows of the inner join. Dara (Braga) and Farah (Coimbra) match none. The left join adds Dara and Farah with NULL zone columns; the full join also adds the Faro zone with NULL customer columns. (This figure steps through a recorded run; it needs JavaScript.)
The pairs and their ON results come from a CROSS JOIN query, run against
PostgreSQL 19.0 by the lesson’s trace.py, and the three results are
checked against the real INNER, LEFT and FULL JOIN queries. This is what a
join means, not the order in which the executor works.
INNER JOIN
The pairs for which ON is true, and nothing else. JOIN on its own means
INNER JOIN:
SELECT c.name, c.city, z.city, z.zone
FROM customers AS c
JOIN shipping_zones AS z ON z.city = c.city
ORDER BY c.id;name | city | city | zone ------+--------+--------+------ Ada | Lisbon | Lisbon | A Ben | Porto | Porto | A Chen | Lisbon | Lisbon | A Eli | Porto | Porto | A (4 rows)
A row without a partner disappears, from either side. Dara and Farah are not here, and neither is Faro. ON is an ordinary condition with the three-valued logic of the previous lesson: a pair is kept only when it is true, so a NULL key never matches anything, not even another NULL.
LEFT, RIGHT and FULL JOIN
An outer join is the inner join plus rows for the rows that matched nothing. A LEFT JOIN adds one row for each left row without a partner, with NULL in every column from the right:
SELECT c.name, c.city, z.city, z.zone
FROM customers AS c
LEFT JOIN shipping_zones AS z ON z.city = c.city
ORDER BY c.id;name | city | city | zone -------+---------+--------+------ Ada | Lisbon | Lisbon | A Ben | Porto | Porto | A Chen | Lisbon | Lisbon | A Dara | Braga | | Eli | Porto | Porto | A Farah | Coimbra | | (6 rows)
A RIGHT JOIN does the same for the right table. It is a LEFT JOIN with the tables written the other way round, and most people write it that way:
SELECT c.name, c.city, z.city, z.zone
FROM customers AS c
RIGHT JOIN shipping_zones AS z ON z.city = c.city
ORDER BY c.id, z.city; name | city | city | zone
------+--------+--------+------
Ada | Lisbon | Lisbon | A
Ben | Porto | Porto | A
Chen | Lisbon | Lisbon | A
Eli | Porto | Porto | A
| | Faro | B
(5 rows)A FULL JOIN adds both kinds: the unmatched customers with NULL zones, and the unmatched zone with NULL customer columns.
SELECT c.name, c.city, z.city, z.zone
FROM customers AS c
FULL JOIN shipping_zones AS z ON z.city = c.city
ORDER BY c.id, z.city; name | city | city | zone
-------+---------+--------+------
Ada | Lisbon | Lisbon | A
Ben | Porto | Porto | A
Chen | Lisbon | Lisbon | A
Dara | Braga | |
Eli | Porto | Porto | A
Farah | Coimbra | |
| | Faro | B
(7 rows)So the size of the result follows: 4 matched pairs; a LEFT JOIN adds 2 rows, the unmatched customers; a RIGHT JOIN adds 1, the unmatched zone; a FULL JOIN adds all 3. (A left row that matches several right rows appears once per match, in every kind of join; a later section comes back to this.)
The rows an outer join adds are recognisable by their NULLs. In the FULL
JOIN, c.city is NULL only on the rows added for an unmatched zone, since
the table does not allow a NULL city. That is the basis of the anti-join
below.
ON or WHERE
Back to the first query. WHERE runs after FROM, joins included. The LEFT
JOIN kept every customer: Chen and Eli with their orders, none of them
paid, and Farah, who has no orders, on one row with NULL in every order
column. Then WHERE o.status = 'paid' tested each row. For Chen’s and
Eli’s orders it is false. For Farah’s row it asked whether NULL equals
'paid', which does not evaluate to true either, so that row went too,
exactly as an inner join would have dropped it.
The condition belongs in ON. There it decides which orders count as a match, and a customer with no matching order is still added back with NULLs:
SELECT c.name, o.id AS order_id, o.total
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id AND o.status = 'paid'
ORDER BY c.id, o.id;name | order_id | total -------+----------+------- Ada | 107 | 27.50 Ben | 105 | 31.00 Chen | | Dara | 110 | 64.00 Eli | | Farah | | (6 rows)
The rule for an outer join: a condition on the table whose rows may be missing (the right table of a LEFT JOIN) goes in ON if it should only choose partners, and in WHERE only if you really mean to drop the rows without one. For an inner join the two places give the same result.
The mirror image is a trap too. A condition on the left table in the ON of a LEFT JOIN does not remove left rows. It only stops them from finding partners, and the join adds them back with NULLs anyway:
SELECT c.name, c.city, o.id AS order_id
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id AND c.city = 'Lisbon'
ORDER BY c.id, o.id;name | city | order_id -------+---------+---------- Ada | Lisbon | 101 Ada | Lisbon | 103 Ada | Lisbon | 107 Ben | Porto | Chen | Lisbon | 104 Chen | Lisbon | 109 Dara | Braga | Eli | Porto | Farah | Coimbra | (9 rows)
Every customer is still there. Only the two Lisbon customers got their orders. To list only Lisbon customers, the condition goes in WHERE.
USING and NATURAL
When the join columns have the same name on both sides, USING (city)
says the same as ON z.city = c.city, with one difference: the output has
a single city column instead of two, placed first in SELECT *.
SELECT *
FROM customers AS c
JOIN shipping_zones AS z USING (city)
ORDER BY c.id;city | id | name | email | referred_by | zone | fee --------+----+------+------------------+-------------+------+------ Lisbon | 1 | Ada | ada@example.org | | A | 3.50 Porto | 2 | Ben | | 1 | A | 3.50 Lisbon | 3 | Chen | chen@example.org | 1 | A | 3.50 Porto | 5 | Eli | | 3 | A | 3.50 (4 rows)
In an outer join, that single column is the value from whichever side has
one, the way coalesce(c.city, z.city) would be. In a FULL JOIN the Faro
row keeps its city, which c.city would show as NULL:
SELECT city, c.name, z.zone
FROM customers AS c
FULL JOIN shipping_zones AS z USING (city)
ORDER BY c.id, city;city | name | zone ---------+-------+------ Lisbon | Ada | A Porto | Ben | A Lisbon | Chen | A Braga | Dara | Porto | Eli | A Coimbra | Farah | Faro | | B (7 rows)
NATURAL JOIN goes one step further: it joins on every column name the two
tables have in common, without listing them. It is short and fragile. The
customers and orders tables share one column name, id, so a natural join
matches customer 1 with order 1:
SELECT count(*)
FROM customers NATURAL JOIN orders; count
-------
0
(1 row)No error, no rows. Adding a column to either table later can silently change what a NATURAL JOIN means, so name the columns.
Joining a table to itself
referred_by points at another row of customers. Joining the table to
itself, under two aliases, turns the id into a name:
SELECT c.name, r.name AS referred_by
FROM customers AS c
LEFT JOIN customers AS r ON r.id = c.referred_by
ORDER BY c.id;name | referred_by -------+------------- Ada | Ben | Ada Chen | Ada Dara | Eli | Chen Farah | (6 rows)
The two aliases are two separate roles: c is the customer, r the
referrer. The join must be LEFT: for Ada, Dara and Farah referred_by is
NULL, the ON condition is never true, and an inner join would drop them.
Joins multiply rows
A join returns one row per matching pair, so a customer with three orders appears three times. Join the same customer to a second table with several matches, and the rows multiply. Ada has three orders and referred two customers:
SELECT c.name, o.id AS order_id, o.total, r.name AS referred
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
LEFT JOIN customers AS r ON r.referred_by = c.id
WHERE c.id = 1
ORDER BY o.id, r.id;name | order_id | total | referred ------+----------+-------+---------- Ada | 101 | 42.00 | Ben Ada | 101 | 42.00 | Chen Ada | 103 | 60.00 | Ben Ada | 103 | 60.00 | Chen Ada | 107 | 27.50 | Ben Ada | 107 | 27.50 | Chen (6 rows)
Six rows: each order once per referral. Any aggregate over these rows counts each order twice. Here is what each customer “spent”, with how many people they referred, computed over such a join:
SELECT c.name, sum(o.total) AS spent, count(r.id) AS referred
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
LEFT JOIN customers AS r ON r.referred_by = c.id
GROUP BY c.id
ORDER BY c.id;name | spent | referred ------+--------+---------- Ada | 259.00 | 6 Ben | 91.50 | 0 Chen | 99.00 | 2 Dara | 76.00 | 0 Eli | 114.90 | 0 (5 rows)
Ada’s 129.50 shows as 259.00, and her 2 referrals as 6. The query runs, and the numbers look plausible. The fix is to aggregate each table on its own first, so that each subquery returns one row per customer, and to join those:
SELECT c.name, o.spent, coalesce(r.referred, 0) AS referred
FROM customers AS c
LEFT JOIN (SELECT customer_id, sum(total) AS spent
FROM orders GROUP BY customer_id) AS o ON o.customer_id = c.id
LEFT JOIN (SELECT referred_by, count(*) AS referred
FROM customers GROUP BY referred_by) AS r ON r.referred_by = c.id
ORDER BY c.id;name | spent | referred -------+--------+---------- Ada | 129.50 | 2 Ben | 91.50 | 0 Chen | 99.00 | 1 Dara | 76.00 | 0 Eli | 114.90 | 0 Farah | | 0 (6 rows)
Farah appears now too, with no amount spent: this version starts from the customers and keeps them all with LEFT JOINs, where the one above dropped her in its inner join with the orders. Whenever a query joins one row to two independent lists, check that the aggregates are not counting the product of the two.
Semi-joins: EXISTS
“Customers with at least one shipped order” is not a question about pairs. A join answers it with one row per shipped order, so Ben and Chen appear twice:
SELECT c.name
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
WHERE o.status = 'shipped'
ORDER BY c.id;name ------ Ada Ben Ben Chen Chen Eli (6 rows)
DISTINCT would hide the duplicates, but EXISTS asks the question
directly: keep each customer once if a matching order exists. This is a
semi-join, and PostgreSQL can execute it as one, which needs only the first
matching order for each customer:
SELECT c.name
FROM customers AS c
WHERE EXISTS (SELECT 1 FROM orders AS o
WHERE o.customer_id = c.id AND o.status = 'shipped')
ORDER BY c.id;name ------ Ada Ben Chen Eli (4 rows)
What the subquery selects does not matter, only whether it returns a row;
SELECT 1 is the usual way to say so. The subquery refers to c, the row
of the outer query being tested: a correlated subquery, which a later
lesson covers in more depth.
Anti-joins: NOT EXISTS
The opposite question, “customers with no paid order”, is an anti-join. The
previous lesson showed why NOT IN gets it wrong when the list can hold a
NULL. NOT EXISTS is always safe:
SELECT c.name
FROM customers AS c
WHERE NOT EXISTS (SELECT 1 FROM orders AS o
WHERE o.customer_id = c.id AND o.status = 'paid')
ORDER BY c.id;name ------- Chen Eli Farah (3 rows)
The same question can be written with an outer join: keep the rows that the LEFT JOIN added, recognised by a NULL in a column that cannot be NULL in a real match, such as the primary key:
SELECT c.name
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id AND o.status = 'paid'
WHERE o.id IS NULL
ORDER BY c.id;name ------- Chen Eli Farah (3 rows)
PostgreSQL recognises both forms. Their plans, recorded here with psql against tables that were never analyzed, are identical, with an anti-join node at the top (PGlite printed the same plans when this lesson was checked):
EXPLAIN (COSTS OFF)
SELECT c.name
FROM customers AS c
WHERE NOT EXISTS (SELECT 1 FROM orders AS o
WHERE o.customer_id = c.id AND o.status = 'paid'); QUERY PLAN
-----------------------------------------------
Hash Anti Join
Hash Cond: (c.id = o.customer_id)
-> Seq Scan on customers c
-> Hash
-> Seq Scan on orders o
Filter: (status = 'paid'::text)
(6 rows)EXPLAIN (COSTS OFF)
SELECT c.name
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id AND o.status = 'paid'
WHERE o.id IS NULL; QUERY PLAN
-----------------------------------------------
Hash Anti Join
Hash Cond: (c.id = o.customer_id)
-> Seq Scan on customers c
-> Hash
-> Seq Scan on orders o
Filter: (status = 'paid'::text)
(6 rows)Choose the one that reads better. NOT EXISTS states the question; the
LEFT JOIN form is handy when you also want columns from the joined table
for the rows that did match, in a variant of the query.
Try it yourself
Use any box above: press “edit”, replace the query, press “run”. The queries in the answers can be pasted the same way.
- For each shipping zone city, count the customers who live there. Faro must appear, with 0.
Answer
Start from the zones, so that a LEFT JOIN keeps Faro, and count a column
from the customers’ side. count(*) would count the row the LEFT JOIN
added for Faro and give 1; count(c.id) skips its NULL:
SELECT z.city, count(c.id) AS customers
FROM shipping_zones AS z
LEFT JOIN customers AS c ON c.city = z.city
GROUP BY z.city
ORDER BY z.city;
Faro 0, Lisbon 2, Porto 2.
- Show each customer’s shipping fee. Customers in a city without a zone pay 7.50.
Answer
A LEFT JOIN keeps Dara and Farah with a NULL fee, and coalesce fills it
in:
SELECT c.name, c.city, coalesce(z.fee, 7.50) AS fee
FROM customers AS c
LEFT JOIN shipping_zones AS z ON z.city = c.city
ORDER BY c.id;
- Which customers have a shipped order but no paid one?
Answer
Chen and Eli. One semi-join and one anti-join, both on the same customer:
SELECT c.name
FROM customers AS c
WHERE EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.id AND o.status = 'shipped')
AND NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.id AND o.status = 'paid')
ORDER BY c.id;
- List each customer with the name of whoever referred their referrer.
Answer
Two self-joins, both LEFT so that every customer stays. Only Eli has one: he was referred by Chen, whom Ada referred.
SELECT c.name, r.name AS referrer, rr.name AS referrers_referrer
FROM customers AS c
LEFT JOIN customers AS r ON r.id = c.referred_by
LEFT JOIN customers AS rr ON rr.id = r.referred_by
ORDER BY c.id;
- Without running it, how many rows does
SELECT * FROM customers AS c LEFT JOIN orders AS o ON o.customer_id = c.idreturn? And withFULL JOIN?
Answer
13 both times. All 12 orders have a customer, so the matched pairs are 12;
Farah has no order and adds one row. No order lacks a customer (the foreign
key and NOT NULL on customer_id see to that), so a FULL JOIN adds
nothing more.
SELECT count(*) AS left_join
FROM customers AS c LEFT JOIN orders AS o ON o.customer_id = c.id;
SELECT count(*) AS full_join
FROM customers AS c FULL JOIN orders AS o ON o.customer_id = c.id;
Sources
The PostgreSQL 19 documentation:
- Table expressions: the join types, what each adds to the inner join, ON against USING and NATURAL, and the difference between a condition in ON and in WHERE for an outer join.
- Joins between tables in the tutorial: self-joins and outer joins.
- Subquery expressions:
EXISTSandNOT EXISTS. - SELECT: the FROM clause reference, including CROSS JOIN and the comma form.
- Using EXPLAIN.
ls postgres/
Querying
- 01 How a SELECT runs, clause by clause draftThe logical order of FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY and LIMIT, and the everyday errors it explains.
- 02 Tables and the types worth knowing draftinteger and bigint, numeric against double precision, text, boolean, uuid (including uuidv7), identity columns, and casts.
- 03 NULL and three-valued logic draftWhy x = NULL is never true, IS DISTINCT FROM, coalesce, NOT IN with a NULL in the list, and how aggregates skip NULLs.
- 04 Joins draftInner, left, right, full and cross joins; ON against USING; semi- and anti-joins with EXISTS; the rows an outer join adds.
- 05 Aggregates and GROUP BY plannedcount(*) against count(x), FILTER, ordered string_agg and array_agg, any_value, and grouping by a primary key.
- 06 Subqueries and set operations plannedScalar, IN, EXISTS, ANY and ALL subqueries, correlated subqueries, and UNION, INTERSECT and EXCEPT with and without ALL.
- 07 Sorting and paging plannedNULLS FIRST and LAST, collations, ties and FETCH ... WITH TIES, and keyset pagination instead of large OFFSETs.
- 08 Dates, times and time zones plannedtimestamp against timestamptz, the session time zone, intervals, date_trunc, and generate_series for calendars.
- 09 Changing data plannedINSERT, UPDATE and DELETE with RETURNING, including OLD and NEW values in RETURNING, and UPDATE ... FROM.
Analytical queries
- 10 Window functions plannedPARTITION BY, ORDER BY and frames; ranking, running totals and moving averages; lag, lead and first_value with IGNORE NULLS.
- 11 WITH queries plannedCommon table expressions for readability, MATERIALIZED and NOT MATERIALIZED, and data-modifying statements in WITH.
- 12 Recursive queries plannedWITH RECURSIVE over trees and graphs, the SEARCH and CYCLE clauses, and how to stop a recursion that never ends.
- 13 LATERAL plannedSubqueries and functions that see the row beside them: top N per group, and set-returning functions per row.
- 14 GROUPING SETS, ROLLUP and CUBE plannedSeveral groupings in one query, subtotals and grand totals, and telling them apart with GROUPING().
Richer data
- 15 JSONB plannedOperators, containment, jsonpath, updating documents, and the GIN indexes that make the queries fast.
- 16 SQL/JSON and JSON_TABLE plannedThe standard JSON functions: JSON_VALUE, JSON_QUERY, JSON_EXISTS, IS JSON, and JSON_TABLE to turn documents into rows.
- 17 Arrays plannedBuilding and slicing arrays, unnest WITH ORDINALITY, = ANY, array_agg, array_sort, and when a table is better.
- 18 Ranges and temporal keys plannedRange and multirange types, overlap and containment, exclusion constraints, and primary keys WITHOUT OVERLAPS.
- 19 Full-text search plannedtsvector and tsquery, configurations and dictionaries, ranking, highlighting, and indexing a search column.
Keeping data correct
- 20 Constraints plannedCHECK, NOT NULL, UNIQUE with NULLS NOT DISTINCT, foreign keys and their actions, deferrable constraints, NOT VALID.
- 21 Generated columns plannedColumns computed from others, virtual (the default) or stored, and what each costs on reads and writes.
- 22 Transactions and isolation levels plannedWhat READ COMMITTED, REPEATABLE READ and SERIALIZABLE let two sessions see, the anomalies each allows, and retrying serialization failures.
- 23 Row locks and queues plannedSELECT ... FOR UPDATE and its weaker forms, NOWAIT, SKIP LOCKED for job queues, and advisory locks.
- 24 Upsert and MERGE plannedINSERT ... ON CONFLICT DO NOTHING, DO UPDATE and DO SELECT; MERGE with WHEN NOT MATCHED BY SOURCE and RETURNING merge_action().
Performance from the query side
- 25 Indexes plannedWhat a B-tree index can answer: column order in multicolumn indexes, partial, expression and covering (INCLUDE) indexes.
- 26 GIN, GiST, BRIN and hash plannedWhich queries each index type serves, with the operators that use it: containment, overlap, nearest neighbour, ranges of a big table.
- 27 Reading EXPLAIN plannedPlan nodes, estimated against actual rows, buffers, and the questions to ask of a slow plan. How statistics feed the estimates.
- 28 Partitioning plannedRange, list and hash partitions, partition pruning in plans, and attaching and detaching partitions.
Logic and access in the database
- 29 Views and materialized views plannedNaming a query, updatable views, WITH CHECK OPTION, and refreshing a materialized view concurrently.
- 30 SQL and PL/pgSQL functions plannedFunctions and procedures, volatility, set-returning functions, and PL/pgSQL control flow and error handling.
- 31 Triggers plannedRow and statement triggers, BEFORE and AFTER, transition tables, and keeping an audit log.
- 32 LISTEN and NOTIFY plannedMessages between sessions, how they interact with transactions, and a small change feed.
- 33 Row-level security plannedPolicies that filter rows per role, USING against WITH CHECK, and the roles that bypass them.
- 34 Extensions worth knowing plannedpg_trgm, pgcrypto, citext, btree_gist, postgres_fdw and pg_stat_statements: what each adds and when to reach for it.