PostgreSQL Foreign Keys and JOIN
Split data into linked tables with primary and foreign keys, insert rows in the right order, then put it back together with JOIN.

The basic queries post used a single users table. Real
apps need more than one table: users write posts, posts belong to a topic, and
readers leave comments. This post links those tables together with keys, fills
them with data, and then uses JOIN to read them back as one view.
All the queries
-- Tables that point to each otherCREATE TABLE users ( id SERIAL, name VARCHAR(128), email VARCHAR(128) UNIQUE, PRIMARY KEY(id));
CREATE TABLE topics ( id SERIAL, name VARCHAR(128) UNIQUE, PRIMARY KEY(id));
CREATE TABLE posts ( id SERIAL, title VARCHAR(128), created_at TIMESTAMP DEFAULT NOW(), user_id INTEGER REFERENCES users(id) ON DELETE CASCADE, topic_id INTEGER REFERENCES topics(id) ON DELETE CASCADE, UNIQUE(title, user_id), PRIMARY KEY(id));
CREATE TABLE comments ( id SERIAL, body TEXT, post_id INTEGER REFERENCES posts(id) ON DELETE CASCADE, PRIMARY KEY(id));
-- Read them back as one viewSELECT comments.body, posts.title, users.name, topics.nameFROM comments JOIN posts ON comments.post_id = posts.id JOIN users ON posts.user_id = users.id JOIN topics ON posts.topic_id = topics.id;Why split the data at all?
Picture the screen a reader sees: a list of posts, each with its author and topic.
Basic Queries Ted ted@example.com PostgreSQLData Types Ted ted@example.com PostgreSQLJWT Explained Charles charles@example.com SecuritySessions Explained Charles charles@example.com SecurityYou could store it exactly like that, in one table. But "Ted", "ted@example.com" and "PostgreSQL" are repeated on every row, and with a million posts they'd be repeated a million times. If Ted changes his email, you'd have to update every one of his posts and hope you don't miss any.
Instead, store each string once, in its own table, and give it a number.
Other tables then point at that number. Numbers are smaller than strings, so
this also compresses the data, and changing Ted's email is a one-row UPDATE.
The picture to keep in mind is boxes and arrows:
comments ──► posts ──► users │ └─────► topicsEach arrow starts on the many side and points to the one side. One user writes many posts, one topic holds many posts, and one post gets many comments.
Three kinds of key
Every table above uses the same three patterns.
Primary key: SERIAL + PRIMARY KEY
id SERIAL,PRIMARY KEY(id)SERIAL: an integer PostgreSQL fills in for you, counting 1, 2, 3… (more in the data types post). It's a PostgreSQL feature, so other databases spell it differently.PRIMARY KEY(id): this column identifies the row, and PostgreSQL builds an index on it so looking a row up byidis fast.
Run \d users in psql and you'll see what SERIAL really is:
integer not null default nextval('users_id_seq'::regclass).
Logical key: UNIQUE
email VARCHAR(128) UNIQUEUNIQUE: only one row can have each value. Insertingted@example.coma second time fails.- To check that quickly, PostgreSQL indexes the column, so searching by email is fast too.
The primary key is for the database. The logical key is what a person would look a row up by: an email, a topic name.
Foreign key: REFERENCES
user_id INTEGER REFERENCES users(id) ON DELETE CASCADEuser_id INTEGER: a plain number column. It lives on the many side, at the start of the arrow.REFERENCES users(id): the number must match anidinusers. Try to insert a post withuser_id99 when there's no user 99 and it fails.ON DELETE CASCADE: if that user is deleted, delete their posts too. More on this further down.
The naming habit matters: the foreign key is the other table's name in the
singular plus _id. posts.user_id points to users.id, and you can see
that at a glance.
Unique together: UNIQUE(title, user_id)
UNIQUE(title, user_id)Post titles aren't unique across the whole site. Ted and Charles could both write a post called "Hello World". But one person writing two posts with the same title is probably a mistake.
UNIQUE(title, user_id) makes the pair unique: one "Hello World" per
user. Base your constraints on what's true about the data, not on what's
easiest to type.
Inserting: from the outside in
A foreign key can only point to a row that already exists. So insert into the
tables that don't point anywhere first (users, topics), then posts, then
comments.
1. Tables with no foreign keys
INSERT INTO users (name, email) VALUES ('Ted', 'ted@example.com'); -- id 1INSERT INTO users (name, email) VALUES ('Charles', 'charles@example.com'); -- id 2
INSERT INTO topics (name) VALUES ('PostgreSQL'); -- id 1INSERT INTO topics (name) VALUES ('Security'); -- id 2idis left out of the column list.SERIALfills it in.- From now on Ted is 1 and Security is 2. The numbers aren't a ranking, just labels.
2. Tables that point to them
Foreign keys aren't filled in for you. You have to know which number to use: Ted is 1, Charles is 2, PostgreSQL is 1, Security is 2.
INSERT INTO posts (title, user_id, topic_id) VALUES ('Basic Queries', 1, 1); -- id 1INSERT INTO posts (title, user_id, topic_id) VALUES ('Data Types', 1, 1); -- id 2INSERT INTO posts (title, user_id, topic_id) VALUES ('JWT Explained', 2, 2); -- id 3INSERT INTO posts (title, user_id, topic_id) VALUES ('Sessions Explained', 2, 2); -- id 4- The values are in the same order as the columns.
created_atis left out too, soDEFAULT NOW()stamps the current time.
3. The last link in the chain
INSERT INTO comments (body, post_id) VALUES ('Saved this cheat sheet', 1);INSERT INTO comments (body, post_id) VALUES ('NUMERIC finally makes sense', 2);INSERT INTO comments (body, post_id) VALUES ('The diagrams helped', 3);JOIN: put it back together
The data is now stored as numbers, but nobody wants to read
Basic Queries, 1, 1. JOIN follows the foreign keys and rebuilds the
readable view whenever you ask for it.
SELECT posts.title, users.nameFROM posts JOIN users ON posts.user_id = users.id;FROM posts JOIN users: read from both tables at once. Start from the many side and follow the arrow: posts → users.ON posts.user_id = users.id: how the rows match up, foreign key = primary key.SELECT posts.title, users.name: with more than one table, name columns astable.column. Both tables have anid, so a bareidwould be ambiguous.
title nameBasic Queries TedData Types TedJWT Explained CharlesSessions Explained CharlesThe ids did their job and stayed out of the result. To see how the match works, select them too:
SELECT posts.title, posts.user_id, users.id, users.nameFROM posts JOIN users ON posts.user_id = users.id;Every row has user_id equal to id. That's the ON clause at work.
CROSS JOIN vs JOIN
A CROSS JOIN has no ON clause. It pairs every row with every row:
SELECT posts.title, posts.topic_id, topics.id, topics.nameFROM posts CROSS JOIN topics;4 posts × 2 topics = 8 rows, half of them nonsense ("JWT Explained" next to "PostgreSQL").
A plain JOIN is short for INNER JOIN, and the easiest way to think of it
is: make every combination, then keep only the rows where ON is true.
SELECT posts.title, topics.nameFROM posts JOIN topics ON posts.topic_id = topics.id;That leaves the 4 rows that match, with "PostgreSQL, PostgreSQL, Security, Security" repeated down the column exactly like the screen at the top of the post. The repetition comes back when you read, but it's never stored.
You'll also see joins written as FROM posts, topics WHERE posts.topic_id = topics.id. It returns the same rows, but JOIN ... ON keeps "how the tables
connect" separate from "which rows I want", so it's easier to read.
Joining four tables
Each extra table is one more line with the same pattern:
SELECT comments.body, posts.title, users.name, topics.nameFROM comments JOIN posts ON comments.post_id = posts.id JOIN users ON posts.user_id = users.id JOIN topics ON posts.topic_id = topics.id;body title name nameSaved this cheat sheet Basic Queries Ted PostgreSQLNUMERIC finally makes sense Data Types Ted PostgreSQLThe diagrams helped JWT Explained Charles SecurityStart at comments and follow every arrow. This is where consistent naming
pays off: every ON line reads thing_id = things.id, so you can write them
without looking at the schema.
You can still add WHERE and ORDER BY after the joins, like any SELECT:
SELECT posts.title, users.nameFROM posts JOIN users ON posts.user_id = users.idWHERE users.email = 'ted@example.com'ORDER BY posts.created_at DESC;ON DELETE: what happens to the children?
Call the one side the parent (a topic) and the many side the children (its posts). What should happen to the posts when the topic is deleted?
DELETE FROM topics WHERE name = 'Security';You decide when you create the foreign key.
CASCADE: delete the children too
topic_id INTEGER REFERENCES topics(id) ON DELETE CASCADEDeleting Security also deletes "JWT Explained" and "Sessions Explained". And
because comments.post_id cascades too, the comment on "JWT Explained" goes
with it. Nothing is left pointing at a row that no longer exists, which is why
this is a common default.
RESTRICT: refuse the delete
topic_id INTEGER REFERENCES topics(id) ON DELETE RESTRICTThe DELETE fails while any post still uses the topic:
ERROR: update or delete on table "topics" violates foreign key constraint "posts_topic_id_fkey" on table "posts"Use it when deleting the parent by accident would be costly, so you have to
move or delete the children yourself first. If you write no ON DELETE at
all, PostgreSQL uses NO ACTION, which behaves almost the same way.
SET NULL: keep the children, drop the link
topic_id INTEGER NULL REFERENCES topics(id) ON DELETE SET NULLThe posts stay, but their topic_id becomes NULL: they no longer belong to
any topic. The column has to allow NULL for this to work. If it's declared
NOT NULL, the delete fails instead.
Which should I use?
- Every table:
id SERIAL+PRIMARY KEY(id) - What a person looks a row up by (email, name):
UNIQUE - Unique only within a parent (title per user):
UNIQUE(title, user_id) - A link to another table:
other_id INTEGER REFERENCES others(id) - Children that mean nothing without the parent:
ON DELETE CASCADE - Children that must be dealt with first:
ON DELETE RESTRICT - Children that can live on their own:
ON DELETE SET NULL - Reading linked tables:
JOIN ... ON child.parent_id = parent.id, starting from the many side