Menu▾

Link orders to customers with an enforced, cascading foreign key

customers and orders exist as two separate tables, but nothing stops orders.customer_id from pointing at a customer that doesn't exist — the two tables aren't actually linked at the database level yet.

Add a FOREIGN KEY from orders.customer_id to customers.id. A customer who closes their account should have their orders removed automatically, so the constraint needs ON DELETE CASCADE.

Schema

▸customers
idINT
nameTEXT
▸orders
idINT
customer_idINT
amountNUMERIC

Example input

Why

The foreign key itself is what makes orders.customer_id honest — Postgres now rejects any insert or update that points at a customers.id that doesn't exist, the exact gap the table had before. ON DELETE CASCADE changes what happens when the referenced customer row is deleted: instead of blocking the delete (the default, ON DELETE RESTRICT, which is what you'd get by leaving the clause off), Postgres automatically deletes every order that referenced that customer, in the same transaction. That's a real, load-bearing decision, not just syntax — cascading is right when the child rows have no meaning without the parent (an order without a customer), and wrong when you'd rather find out a delete would orphan data and stop it, which is why the plain, no-ON DELETE version exists as its own choice.

↑ Read the question

Keep going

Company names are trademarks of their respective owners, used here only to describe practice material. mahir_data is not affiliated with, endorsed by, or sponsored by any company named on this site. Terms.