Joining tables
- Version
- 19
- Review
- Draft
Summary#
A join combines rows from two table expressions. An inner join keeps matching pairs, while a left join also keeps each unmatched left row and fills the right columns with null.
Syntax#
SELECT column_list
FROM left_table
[INNER | LEFT | RIGHT | FULL] JOIN right_table
ON join_condition;
SELECT column_list
FROM left_table
JOIN right_table USING (shared_column);
SELECT left_table.*
FROM left_table
WHERE NOT EXISTS (
SELECT 1 FROM right_table WHERE join_condition
);
Example#
The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.
BEGIN;
CREATE TEMPORARY TABLE customers (
customer_id integer PRIMARY KEY,
name text NOT NULL
);
CREATE TEMPORARY TABLE orders (
order_id integer PRIMARY KEY,
customer_id integer NOT NULL REFERENCES customers,
status text NOT NULL
);
INSERT INTO customers VALUES (1, 'Ada'), (2, 'Grace'), (3, 'Linus');
INSERT INTO orders VALUES (10, 1, 'paid'), (11, 1, 'open'), (12, 2, 'open');
-- Inner join: only customers with a matching paid order.
SELECT name, order_id
FROM customers
JOIN orders USING (customer_id)
WHERE status = 'paid'
ORDER BY order_id;
-- Left join: the condition in ON keeps customers without a match.
SELECT c.name, o.order_id
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id AND o.status = 'paid'
ORDER BY c.customer_id, o.order_id;
-- Anti-join: customers with no orders at all.
SELECT c.name
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id
)
ORDER BY c.customer_id;
ROLLBACK;
Expected output#
name|order_id
Ada|10
(1 row)
name|order_id
Ada|10
Grace|NULL
Linus|NULL
(3 rows)
name
Linus
(1 row)
Common mistakes#
A WHERE condition on a right-table column of a left join, such as o.status = 'paid', removes the null-filled rows and turns the result into that of an inner join. Put the condition in ON when unmatched left rows must remain. Each left row still appears once per match. Use EXISTS if you just need to check whether a match exists.
Version applicability#
These join forms work in PostgreSQL 19.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0