liveBook · Manning

Primary key

As explained in Just Use Postgres!

A primary key is a column or set of columns that uniquely identifies each row in a table and cannot contain null values.

A primary key uniquely identifies every row in a table. It combines uniqueness with a not-null requirement, preventing missing or duplicate row identifiers. section 2.3.1

Use primary keys to model identity in PostgreSQL tables:

  • Define one column as the key, such as products.catalog.id or products.reviews.id. section 2.3.1
  • Use UUID values when identifiers should not depend on numeric sequences; gen_random_uuid() can supply a default. section 2.4.2
  • Use a compound primary key when uniqueness depends on several columns together. section 2.4.2

One product per order line

The sales.order_items table uses PRIMARY KEY (order_id, product_id). This lets one order contain different products while allowing each product to appear only once in that order. section 2.4.2

Listing 2.14 Creating orders and order_items tables
CREATE TABLE sales.orders (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),  
    customer_id INT REFERENCES customers.accounts(id),
    order_date TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
    total_amount DECIMAL(10, 2)
);

CREATE TABLE sales.order_items (
    order_id UUID REFERENCES sales.orders(id),
    product_id INT REFERENCES products.catalog(id),
    quantity INT CHECK (quantity > 0),
    price DECIMAL (10, 2), 
    PRIMARY KEY (order_id, product_id)  
);

Inspect executable table definitions showing a UUID primary key on sales.orders and a compound primary key on sales.order_items. section 2.4.2

How Just Use Postgres! covers it

How deep it goes
Defines single-column, UUID, and compound keys with executable PostgreSQL table definitions, but defers broader key-design theory.
Examples
Uses catalog and review schemas, UUID-based orders, and order_items keyed by order_id and product_id.
What you can do after
Apply it via PostgreSQL CREATE TABLE definitions using numeric, UUID, or compound primary keys.
How it connects
Connects primary keys with not-null constraints, unique constraints, foreign keys, UUIDs, sequences, and explicit transactions.

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 Just Use Postgres!. The section links point to the parts of the book it draws on.