Question 9 of 20 Fundamentals Concept
What do primary keys and foreign keys protect in a sample database?
Short answer
A primary key guarantees each row has a unique, non-null identifier, so a sample cannot be recorded twice under the same ID. A foreign key guarantees every reference points to a row that exists, so a result cannot belong to a sample that was never registered.
Why
The PostgreSQL documentation defines a primary key as a column or set of columns that must be both unique and not null. A foreign key requires that values in one table match a row in another, which the documentation calls referential integrity. In a lab database, samples has sample_id as its primary key, and results has sample_id as a foreign key referencing samples.
The database then refuses a result for sample S-999 if S-999 was never registered, and refuses to delete a sample that still has results unless the key says what should happen, for example ON DELETE RESTRICT. These rules hold for every program and every person writing to the tables, which is stronger than a check in one script. They also make joins trustworthy, because a many-to-one join on a primary key cannot multiply rows.
Limits matter too. A primary key on an auto-incrementing number does not stop the same physical sample being entered twice with two numbers, so a unique constraint on the real-world identifier is still needed. PostgreSQL does not index the referencing column automatically, so add one if you join or delete often.
And a plain unique constraint allows several rows with NULL unless declared NULLS NOT DISTINCT, available since PostgreSQL 15.
A strong answer covers
- Primary key means unique and not null
- Foreign key enforces referential integrity
- Constraints apply to every writer, not one script
- Surrogate keys still need a unique natural identifier
- Index foreign key columns yourself
Common mistakes
- Assuming an auto-increment primary key prevents duplicate entry of the same physical sample
- Enforcing relationships only in application code, so a manual import can create orphan results
- Expecting a foreign key to create an index on the referencing column automatically
The interviewer might ask next
What ON DELETE behavior would you choose for results when a sample record is withdrawn, and why?