liveBook · Manning

Universally unique identifier

As explained in Just Use Postgres!

A UUID is a standardized 128-bit identifier designed to be globally unique without relying on a database sequence.

A UUID is a standardized 128-bit identifier used for primary keys without depending on a database sequence. In a coffee-ordering system, Postgres can generate a random UUIDv4 when the application does not provide one. UUID-based keys avoid sequence dependencies and can scale better for distributed identifier generation. 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)  
);

Use the table definition to see a UUID primary key generated by gen_random_uuid(), alongside order items that reference it. section 2.4.2

Recording an order

A transaction inserts an order with the UUID 19a0cffc-8757-453c-a4d2-b554fdc08954, inserts two related order items, decreases both stock quantities, and commits the changes atomically. section 2.4.2

Listing 2.15 Customer buying two products
BEGIN;

INSERT INTO sales.orders (id, customer_id, total_amount)  
VALUES ('19a0cffc-8757-453c-a4d2-b554fdc08954', 1, 26.53);

INSERT INTO sales.order_items (order_id, product_id, quantity, price)
VALUES ('19a0cffc-8757-453c-a4d2-b554fdc08954', 1, 1, 16.54),
 ('19a0cffc-8757-453c-a4d2-b554fdc08954', 4, 1, 9.99);

UPDATE products.catalog  
SET stock_quantity = stock_quantity - 1
WHERE id IN (1, 4);

COMMIT;

Run the complete order transaction to observe an application-supplied UUID used across the order and order_items records. section 2.4.2

How Just Use Postgres! covers it

How deep it goes
Defines UUID primary keys and generation functions, but defers broader identifier design and administration.
Examples
Demonstrates UUIDs in sales.orders and order_items, including a generated default and an application-supplied order identifier.
What it assumes
Assumes basic SQL table and primary-key knowledge while contrasting UUIDs with sequence-generated numeric identifiers.
What you can do after
Operate/configure Postgres tables with UUID primary keys and generate values through defaults or application input.
How it connects
Connects UUIDs with primary keys, sequences, foreign keys, explicit transactions, UUIDv4, and UUIDv7.

Also explained in

Compare how 10 books explain universally unique identifier →

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.