liveBook · Manning

Foreign key

As explained in Crack Any Codebase with AI

A foreign key is a database field or set of fields that references a key in another table to represent a relationship between records.

A foreign key links a field in one table to a key in another, turning separate records into a relationship. In a schema, tables name the business's nouns while foreign keys reveal how those nouns connect. section 7.0 section 7.1

A booking points to an event type

In `booking`, `event_type_id INT NOT NULL REFERENCES event_type(id)` requires each booking to point to an existing event type. The relationship connects a booking record to the event type it belongs to, while `NOT NULL` makes that link required. section 7.1

Use foreign keys to read an unfamiliar schema as a map:

  • Find the table receiving the most incoming foreign keys; it is a candidate for the schema's central business entity. section 7.3
  • Follow that table's outgoing foreign keys one hop to identify the surrounding cluster of related records. section 7.3
  • Trace one user action across the linked tables to expose runtime reads, writes, and failure points that a static relationship list hides. section 7.8
Listing 7.1 A minimal_booking_schema defining the tables and columns for a simple booking system in SQL.
CREATE TABLE booking (
  id              SERIAL PRIMARY KEY,
  event_type_id   INT NOT NULL REFERENCES event_type(id),
  start_time      TIMESTAMPTZ NOT NULL,
  attendee_email  TEXT NOT NULL,
  status          booking_status NOT NULL DEFAULT 'pending',
  metadata        JSONB
);
CREATE INDEX ON booking (start_time, event_type_id);
CREATE UNIQUE INDEX ON booking (attendee_email);

Inspect the minimal booking schema to see a foreign key alongside a primary key, required field, status type, and indexes. section 7.1

How Crack Any Codebase with AI covers it

How deep it goes
Defines the relationship and demonstrates it in SQL, then uses incoming and outgoing links for schema exploration.
Examples
Uses booking.event_type_id referencing event_type(id), plus Booking relationships to User, EventType, Payment, Attendee, and related tables.
What it assumes
Assumes basic tables, columns, and rows while treating their roles as transferable across relational database tools.
What you can do after
Evaluate/understand unfamiliar schemas by identifying relationship clusters and tracing actions across linked tables.
How it connects
Connects tables, columns, primary keys, indexes, schemas, and user-action traces.

Also explained in

Compare how 21 books explain foreign key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Crack Any Codebase with AI. The section links point to the parts of the book it draws on.