AI Hints
Home›PostgreSQL Tutorial›Foreign Keys and RETURNING
PostgreSQL · Lesson 19 of 120

Foreign Keys

Links between tables.

⏱ 2 min read▶ Video at 15:51🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Customers book seats at events. A booking must point at a real customer and a real event. A foreign key makes Postgres check that for you.

  • Bookings
  • Real customer?
  • Real event?

A bookings table

Each reference says which table the value must exist in. On delete cascade removes bookings if their event is deleted. Then we book a seat for a real event, and for event ninety nine, which doesn't exist. Run it. The first works, and the second is refused.

query.sqlsql
CREATE TABLE bookings (
  booking_id  integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  event_id    integer NOT NULL REFERENCES events ON DELETE CASCADE,
  customer_id integer NOT NULL REFERENCES customers,
  seats       integer NOT NULL DEFAULT 1
);
INSERT INTO bookings (event_id, customer_id) VALUES (1, 7);
INSERT INTO bookings (event_id, customer_id) VALUES (99, 7);
Output
CREATE TABLE
INSERT 0 1
ERROR:  insert or update on table "bookings" violates foreign key constraint
"bookings_event_id_fkey"
DETAIL:  Key (event_id)=(99) is not present in table "events".
Also uses _setup.sql
CREATE TABLE events (
  event_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  title    text NOT NULL,
  seats    integer NOT NULL CHECK (seats > 0));
INSERT INTO events (title, seats) VALUES ('Poetry Night', 30), ('Kids Story Hour', 20);

On delete options

When the parent row is deleted, restrict refuses, which is the default. Cascade deletes the children too. Set null clears the link. Pick the one that matches your business rules.

OptionWhen parent is deleted
RESTRICT / NO ACTIONrefuse (default)
CASCADEdelete children
SET NULLclear the link
SET DEFAULTuse the default

Summary

Foreign keys make sure links point at real rows, and on delete decides what happens to children. Next, inserting and getting values back.

Key takeaways
  • REFERENCES
  • ON DELETE
  • Real links
Next up: INSERT ... RETURNING — get the new ID back