Sub topic 5
Linking Tables with Foreign Keys
Prerequisites
Assume you know basic SELECT, INSERT, UPDATE, and DELETE statements. You also need a running PostgreSQL 12 or newer database and a basic understanding of tables, rows, and columns.
A foreign key is a column, or group of columns, that points to a key in another table. It creates a relationship between rows and prevents references to data that does not exist.
For a book-tracking database, an author and a book are separate entities. A book can refer to an existing author through an author identifier. PostgreSQL checks that the referenced author exists before it accepts the book row.
Defining a Foreign Key
The referenced column must usually be a primary key or have a unique constraint. The referencing and referenced columns should use compatible data types.
CREATE TABLE authors (
author_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE books (
book_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
author_id bigint NOT NULL
REFERENCES authors (author_id)
);Here, books.authorid is the foreign key. The REFERENCES clause tells PostgreSQL to look for the value in authors.authorid.
An insert that uses a missing author fails:
INSERT INTO books (title, author_id)
VALUES ('A Missing Author', 999999);PostgreSQL rejects this statement with a foreign-key violation. That failure protects the database from an orphaned book, which is a row pointing to a nonexistent parent row.
A valid insert first creates the author:
INSERT INTO authors (name)
VALUES ('Example Author')
RETURNING author_id;Use the returned identifier when inserting the book. In application code, parameterized statements should pass this value rather than building SQL with string concatenation.
Choosing Delete Behavior
A foreign key also controls what happens when someone tries to delete the referenced row. The default behavior is restrictive: PostgreSQL refuses to delete an author while books still refer to that author.
You can state this behavior explicitly:
CREATE TABLE books (
book_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
author_id bigint NOT NULL
REFERENCES authors (author_id)
ON DELETE RESTRICT
);ON DELETE RESTRICT is useful when deleting an author should require a deliberate decision about their books. Other actions suit different ownership rules.
CASCADEdeletes dependent rows automatically.SET NULLclears the foreign key, so the column must allow NULL.RESTRICTblocks the delete while dependent rows exist.
Use CASCADE carefully. It is appropriate for rows that have no meaning without their parent, such as a book-author link. It is usually inappropriate for a historical reading record that you may need to preserve.
Checking the Relationship
To find books and their authors, join the tables on the matching key:
SELECT b.title, a.name AS author
FROM books AS b
JOIN authors AS a
ON a.author_id = b.author_id;The join returns only books with matching authors. A LEFT JOIN also returns books whose author reference is NULL, if the schema permits NULL values.
Foreign keys protect relationships during writes. Joins let you use those relationships during reads.
Exercise
What happens when you insert a book whose author_id does not exist in authors?
Show answer
PostgreSQL rejects the insert with a foreign-key violation.