PostgreSQL Joins & INNER JOIN
Good database design splits data into several tables: books in one, authors in another, so an author's name is stored only once. A join puts the pieces back together in a query by matching rows from two tables.
The join types at a glance
| Join | Returns |
|---|---|
INNER JOIN (or just JOIN) |
only rows that have a match in both tables |
LEFT JOIN |
all rows of the left table, plus matches from the right (NULLs where none) |
RIGHT JOIN |
all rows of the right table, plus matches from the left |
FULL JOIN |
all rows of both tables, matched where possible |
CROSS JOIN |
every combination of rows (no condition) |
INNER LEFT RIGHT FULL
(A∩B) A + (A∩B) (A∩B) + B A ∪ BINNER JOIN
Each book stores an author_id. To show the author's name next to each title, join books to authors where the ids match:
SELECT books.title, authors.name AS author
FROM books
INNER JOIN authors ON authors.id = books.author_id
WHERE books.category_id = 2; title | author
--------------------+----------------
Signal from Kepler | Lars Henriksen
The Last Orbit | Lars Henriksen
Clockwork Garden | Aiko Tanaka
(3 rows)
The ON clause is the join condition. For every book, PostgreSQL finds the author rows that satisfy it. The keyword INNER is optional: JOIN alone means an inner join.
Rows without a match disappear
An inner join keeps only pairs that match. Grace Liu has written no book in the shop, so she is missing here, and Poetry (a category without books) is missing too:
SELECT count(*) AS authors FROM authors;
SELECT count(DISTINCT a.id) AS authors_with_books
FROM authors a
JOIN books b ON b.author_id = a.id; authors
---------
10
(1 row)
authors_with_books
--------------------
9
(1 row)
To keep unmatched rows, you need an outer join: see LEFT JOIN.
Joining more than two tables
Joins can be chained. Each new JOIN adds a table and its own ON condition. Here is the content of order 8, with the customer's name and the book titles:
SELECT o.id AS order_id,
c.first_name || ' ' || c.last_name AS customer,
b.title,
oi.quantity,
oi.unit_price
FROM orders o
JOIN customers c ON c.id = o.customer_id
JOIN order_items oi ON oi.order_id = o.id
JOIN books b ON b.id = oi.book_id
WHERE o.id = 8
ORDER BY b.title; order_id | customer | title | quantity | unit_price
----------+------------+---------------------------+----------+------------
8 | Ben Carter | Algorithms on a Napkin | 1 | 35.00
8 | Ben Carter | Learning SQL the Calm Way | 1 | 39.90
8 | Ben Carter | Rust for Curious Minds | 1 | 42.50
(3 rows)
Table aliases (o, c, oi, b) keep long join queries readable.
USING and NATURAL
If both tables have a column with the same name, USING (column) is a shorter way to write the condition, and the shared column appears only once in SELECT *:
CREATE TABLE shelf (book_id integer, shelf_code text);
INSERT INTO shelf VALUES (1, 'A1'), (3, 'B4'), (6, 'C2');
SELECT book_id, shelf_code, quantity
FROM shelf
JOIN order_items USING (book_id)
ORDER BY book_id, quantity;CREATE TABLE
INSERT 0 3
book_id | shelf_code | quantity
---------+------------+----------
1 | A1 | 1
1 | A1 | 1
1 | A1 | 2
3 | B4 | 1
3 | B4 | 1
3 | B4 | 2
6 | C2 | 1
6 | C2 | 1
(8 rows)
Note:
NATURAL JOINjoins on all columns with the same name automatically. Avoid it: adding an unrelated column such ascreated_atto both tables would silently change every query.
Joins and aggregates
Joins combine naturally with GROUP BY. Copies sold per category:
SELECT cat.name AS category, sum(oi.quantity) AS copies_sold
FROM order_items oi
JOIN books b ON b.id = oi.book_id
JOIN categories cat ON cat.id = b.category_id
GROUP BY cat.name
ORDER BY copies_sold DESC, category; category | copies_sold
-----------------+-------------
Children | 12
Programming | 9
Science Fiction | 8
Fiction | 7
Mystery | 7
History | 3
(6 rows)
A common mistake: forgetting the condition
If you list two tables without a join condition, every row is combined with every row (a cross join). With 20 books and 10 authors, that is 200 rows of nonsense:
SELECT count(*) FROM books, authors;
SELECT count(*) FROM books, authors WHERE authors.id = books.author_id; count
-------
200
(1 row)
count
-------
20
(1 row)
The comma syntax with the condition in WHERE is an older way of writing an inner join. The explicit JOIN … ON form keeps the join logic separate from filtering and is easier to read.
Test yourself
What does an INNER JOIN return?
- All rows of both tables
- Only rows that have a match in both tables
- All rows of the left table
- Every combination of rows
Is JOIN without a keyword in front an inner or an outer join?
- Inner
- Left outer
- Full outer
- Cross
When can you use JOIN ... USING (book_id)?
- When the column has the same name in both tables
- Only for primary keys
- Only with LEFT JOIN
- Always, instead of ON