FresherTechnicalSQL
What are primary and foreign keys?
Try answering first
Model answer
A primary key uniquely identifies each row in a table. It must be unique and cannot be NULL, and a table has only one. It can be a natural value or a surrogate key such as an auto-increment integer or a UUID. The database builds an index on it automatically in most systems.
A foreign key is a column (or set of columns) that references the primary key of another table. It enforces referential integrity: you cannot insert an order for a customer that does not exist, and you cannot delete a customer that still has orders, unless a rule says what to do. Actions such as ON DELETE CASCADE, SET NULL or RESTRICT define the behavior.
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)
);
Foreign keys are what make joins between tables meaningful.
Key points
- Primary key: unique, non-null identifier of a row, one per table
- Foreign key: references another table's key to enforce referential integrity
- ON DELETE actions decide what happens to child rows
- Surrogate keys such as IDs are common; natural keys can change
Likely follow-ups
- Should you index a foreign key column?
- What is a composite primary key and when would you use one?
Common mistakes
- Confusing a primary key with a UNIQUE constraint (a table has many unique constraints)
- Skipping foreign keys and leaving orphan rows in the data