When you design a table, four words keep coming up: primary key, foreign key, unique and index. They are often declared on the same columns and they sometimes create the same structures behind the scenes, so it is easy to mix them up. They answer four different questions:
Primary key : how do I identify one row?
Foreign key : which row in another table does this row point to?
Unique : which values must never appear twice?
Index : how do I find rows fast?
The first three are constraints : rules the database enforces on your data. The fourth is a performance structure : it changes speed, not what data is allowed (except for a unique index, which is both).
A small example
CREATE TABLE users ( id BIGINT PRIMARY KEY , email TEXT NOT NULL UNIQUE , name TEXT ) ;
CREATE TABLE orders ( id BIGINT PRIMARY KEY , user_id BIGINT NOT NULL REFERENCES users ( id ) , created_at TIMESTAMPTZ NOT NULL ) ;
CREATE INDEX orders_user_id_idx ON orders ( user_id ) ;
Enter fullscreen mode
Exit fullscreen mode
users.id and…