liveBook · Manning

Foreign key

As explained in Just Use Postgres!

A foreign key constraint requires values in a column or set of columns to match existing unique or primary-key values in a referenced table.

A foreign key constraint keeps related tables consistent by requiring values in one column or column set to match existing unique or primary-key values in another table. In an eCommerce database, reviews can reference only existing products and customers. section 2.3.1 section 2.3.2

Rejecting an invalid review

The catalog contains product 4, but not product 1004. Inserting a review with product_id = 1004 fails with a foreign-key violation; using product_id = 4 succeeds when the customer also exists.

Protecting referenced customers

After customer 1 posts a review, deleting that account fails because the account is still referenced by products.reviews. Marking the account as deleted preserves the relationship instead.

How Just Use Postgres! covers it

How deep it goes
Explains references, uniqueness requirements, index-based verification, failed inserts, and blocked deletes without covering cascading actions.
Examples
Demonstrates product reviews, customer accounts, invalid product identifiers, valid inserts, blocked account deletion, and soft deletion.
What it assumes
Requires related tables and a referenced primary or unique key, while demonstrating account-table creation before adding its foreign key.
What you can do after
Apply it via PostgreSQL ALTER TABLE statements and diagnose rejected inserts or deletes caused by broken references.
How it connects
Connects foreign keys with primary keys, unique constraints, table relationships, indexes, and data integrity.

Also explained in

Compare how 18 books explain foreign key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Just Use Postgres!. The section links point to the parts of the book it draws on.