SQL · Queries that survive scale
What is the difference between a primary key and a foreign key?
Short answer
A primary key uniquely identifies each row and cannot be NULL. A foreign key references a key in another table and enforces that the referenced row exists.
The primary key defines row identity. The foreign key defines a relationship and protects referential integrity: you cannot insert a child row that points to a missing parent, and you cannot delete a parent that still has children unless the constraint says otherwise.
CREATE TABLE customers (
id BIGINT PRIMARY KEY,
email TEXT NOT NULL UNIQUE
);
CREATE TABLE orders (
id BIGINT PRIMARY KEY,
customer_id BIGINT NOT NULL REFERENCES customers(id),
total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);Behavior and trade-offs
- A primary key is unique, NOT NULL, and usually backed by a unique index
- A table can have only one primary key, but many foreign keys
- Foreign keys are not automatically indexed in every database, so index the referencing column
- ON DELETE CASCADE removes children, while RESTRICT or NO ACTION blocks the delete
- Foreign keys add write-time checks but prevent orphaned data
On large write-heavy systems, some teams drop foreign keys and enforce relationships in the application. That can reduce lock contention, but it trades away a strong database guarantee, so the decision needs monitoring and cleanup jobs.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Does a foreign key automatically create an index?
- 2What are the options for ON DELETE?
- 3Can a table have more than one primary key?
- 4Why might a team choose not to use foreign keys?
Say it in the interview
A primary key identifies each row uniquely and cannot be NULL. A foreign key references a key in another table and enforces referential integrity. I always index foreign key columns because the database may not do it automatically, especially for cascade checks. I use cascades deliberately and treat disabling foreign keys as a trade-off that needs application-level enforcement.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live SQL mock interview and get scored feedback on depth, clarity and confidence.