Interview Databases & Caching

What is the difference between a primary key, a unique key, and a foreign key?

Databases & Caching · Intermediate level

Answer

A primary key uniquely identifies each row and cannot be null. A unique key enforces uniqueness for a column or column set. A foreign key enforces that values in one table refer to valid rows in another table.

Technical explanation

Primary keys identify rows and are often referenced by foreign keys.

Unique constraints enforce business uniqueness such as email or tenant plus name.

Foreign keys protect referential integrity but need indexing and migration planning on large tables.

Hands-on example

Example schema:

CREATE TABLE customers (id uuid PRIMARY KEY, email text UNIQUE NOT NULL);

CREATE TABLE orders (id uuid PRIMARY KEY, customer_id uuid NOT NULL REFERENCES customers(id));

Add an index on orders(customer_id) for join and delete/update performance.

Preparing for an interview?

Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.

More Databases & Caching interview questions

← All Databases & Caching questions