liveBook · Manning

Foreign key

As explained in Build Python Web Apps with Streamlit

A foreign key constraint requires values in one table's column to correspond to existing values in a referenced table's key column.

A foreign key connects related tables by requiring a column’s value to match an existing value in another table’s key column. In a haiku app, each haiku can record its author using the username of an existing user. section 8.2.2 section 8.2.4

The referenced column is typically a primary key. Here, users.username uniquely identifies a user, while haikus.author points to it. This models the one-to-many relationship in which one user can be associated with multiple haikus. section 8.2.2

Connecting users and haikus

The schema declares the relationship with FOREIGN KEY (author) REFERENCES users(username). After inserting alice into users, rows in haikus can use alice as their author. The database also supplies haiku_id and created_at through their declared types and defaults. section 8.2.4

Figure 8.4 Database schema with a foreign key relationship between the users and haikus tables

Use the schema diagram to see users.username connected to haikus.author and to distinguish each table’s primary key. section 8.2.2

How Build Python Web Apps with Streamlit covers it

How deep it goes
Defines the relationship and shows its PostgreSQL declaration, but does not develop broader constraint-management or deletion behavior.
Examples
Uses users.username, haikus.author, the alice user, and inserted haiku rows to demonstrate the relationship.
What it assumes
Assumes tables, columns, and primary keys, while introducing how entities and one-to-many relationships become relational schema elements.
What you can do after
Apply it via PostgreSQL by declaring a FOREIGN KEY that references a primary-key column in another table.
How it connects
Connects primary keys, relational database schemas, ER diagrams, SQL, and one-to-many relationships.

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 Build Python Web Apps with Streamlit. The section links point to the parts of the book it draws on.