liveBook · Manning

Primary key

As explained in Build Python Web Apps with Streamlit

A primary key is a column or set of columns whose combined values uniquely identify each row in a data table.

When an app stores users and their writing, it needs a reliable way to tell one row from another. A primary key is a column—or a set of columns—whose values uniquely identify each row in a table. section 8.2.2 section 6.1.2

For a users table, username can serve as the primary key: every user must have one, and no two users can share it. For a haikus table, haiku_id identifies each haiku instead. Its SERIAL data type makes PostgreSQL assign successive integer values as rows are added. section 8.2.2 section 8.2.4

CREATE TABLE haikus (
  haiku_id SERIAL PRIMARY KEY,
  created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
  author VARCHAR(100),
  text TEXT,
  FOREIGN KEY (author) REFERENCES users(username)
);

In the haikus table definition, haiku_id is the primary key. The author column has a different job: it is a foreign key that refers to an existing username in the users table. section 8.2.4 section 8.2.2

Find the row you mean

If two haikus have different haiku_id values, an update can target one with WHERE haiku_id = 1, while a delete can target the other with WHERE haiku_id = 2. The key gives each operation a specific row to identify. section 8.2.4

A key need not be a single column. In a sales CSV, a row is identified by the combination of date, product name, segment, category, gender, age group, and state. Those columns together form its primary key; the sales figures describe the identified row. section 6.1.2

How Build Python Web Apps with Streamlit covers it

How deep it goes
Defines single-column and composite keys, then shows PostgreSQL PRIMARY KEY declarations; stops short of declaring a composite key in SQL.
Examples
Uses a multi-column sales CSV key, usernames and haiku IDs, and SQL statements targeting haikus by ID.
What it assumes
Builds on entities, attributes, and relational tables while introducing SQL column specifications before PRIMARY KEY declarations.
What you can do after
Apply it via PostgreSQL CREATE TABLE declarations to identify rows and support foreign-key references.
How it connects
Connects primary keys to relational tables, foreign keys, database schemas, and SQL updates and deletes.

Also explained in

Compare how 21 books explain primary 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.