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
- What is a deadlock, and how do databases detect and resolve them?
- What is a transaction, and what do the ACID properties mean?
- What is WAL (write-ahead logging), and how does it support durability and replication?
- What is AWS DMS, and when would you use it?
- What is schema migration, and how do you run migrations safely in production?
- What is a composite index, and does column order matter?
- How do you decide which columns to index?
- What is connection exhaustion, and how do you prevent it?