Menu

1 / 5

Primary Key vs Foreign Key vs Unique vs Index: A SQL Cheat Sheet

DEV Community: backend·Abdeldjalil Chougui·about 16 hours ago
#2iEEPE0t
#devtobackend#devto#dev#index#unique
Long article (987 words) — no AI summary yet.
Reading 0:00
15s threshold

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…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.