Video in progress

What is the difference between a PRIMARY KEY and a UNIQUE constraint?

Both reject duplicate values. But a table has only one PRIMARY KEY and it can't be NULL, while a table can have several UNIQUE constraints, and PostgreSQL doesn't treat NULLs as duplicates.

📖 Answer

A PRIMARY KEY is the row's "passport". Other tables point at it with a FOREIGN KEY. It is automatically NOT NULL and UNIQUE.

UNIQUE is for business rules: "no two accounts with the same email".

CREATE TABLE users (
    id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email text UNIQUE,
    phone text UNIQUE
);

INSERT INTO users(email) VALUES (NULL);
INSERT INTO users(email) VALUES (NULL); -- no error!

The second INSERT goes through because in the SQL standard NULL means "unknown", and two unknowns are not equal. Since PostgreSQL 15 you can change this with UNIQUE NULLS NOT DISTINCT.

Both create a B-tree index under the hood, so a lookup by email is fast even without a separate index.