What are a primary key and a foreign key?
A primary key uniquely identifies a row: its values are unique and cannot be NULL. A foreign key is a column whose values must exist in the primary or unique key of another table, or be NULL if allowed. The database checks this both when a child row is inserted and when a parent row is deleted, and ON DELETE sets the deletion behaviour. Keys do not check business meaning.
SQL · Basics
A test deletes a user and the API answers 500. What exactly did the database reject?
An automated test cleans data: it deletes a user who already has an account. The API answers 500 and the log contains a line about a constraint violation. This is not a failure but the foreign key doing its job: the database refuses to leave an account without an owner. This lesson is about how primary and foreign keys guarantee integrity, what exactly they check and which test cases follow from them.
How it works and why. A primary key (PRIMARY KEY) uniquely identifies a row: values are unique and cannot be NULL. A table has only one, but it can consist of several columns (a composite key). It can be a "surrogate" key (a counter number, a UUID) that means nothing, or a "natural" one (for example an email). Natural keys are risky: an email changes and every reference would have to be fixed, so relations usually use a surrogate.
A foreign key (FOREIGN KEY) is a column whose values must exist in the primary (or unique) key of another table, or be NULL if the column allows it. The database checks this on every change: when a child row is inserted or updated (the reference must lead to an existing record) and when a parent row is deleted or changed (nothing may reference it). So an "orphan" record simply cannot appear in such a schema.
The schema from the example, PostgreSQL:
CREATE TABLE users (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE
);
CREATE TABLE accounts (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id integer NOT NULL REFERENCES users (id),
currency char(3) NOT NULL,
balance numeric(14,2) NOT NULL DEFAULT 0
);
What the foreign key accepts
| user_id | result |
|---|---|
| 1 | ok |
| 2 | ok |
| 999 | error rejected |
| id | |
|---|---|
| 1 | anna@test.com |
| 2 | ivan@test.com |
users, so the database rejects the whole row instead of storing it with a "broken" reference.Example: what the test sees. Creating an account for a user that does not exist:
INSERT INTO accounts (user_id, currency) VALUES (1, 'UAH');
INSERT INTO accounts (user_id, currency) VALUES (999, 'UAH');
-- ERROR: insert or update on table "accounts" violates
-- foreign key constraint "accounts_user_id_fkey"
-- DETAIL: Key (user_id)=(999) is not present in table "users".
The error texts are shortened, and their form depends on the DBMS and version (MySQL, SQL Server and Oracle word them differently, but the point is the same). The reverse side: deleting a parent row that is still referenced:
DELETE FROM users WHERE id = 1;
-- ERROR: update or delete on table "users" violates
-- foreign key constraint "accounts_user_id_fkey" on table "accounts"
-- DETAIL: Key (id)=(1) is still referenced from table "accounts".
It helps to tell apart: a database error is correct behaviour, but how the user learns about it depends on the application. An API that returns 500 with the query text has a defect (a leak of details), while 409 with an explanatory message is proper handling. What happens to child records on delete is decided by the ON DELETE rule (rejection by default, there are CASCADE and SET NULL); there is a separate lesson on that.
What to test here.
- Creating a child record with a non-existent reference: it must be rejected, not silently stored.
- Deleting a parent that has children: rejection, cascade or nulling, depending on requirements.
- A duplicate primary key or unique field (the same email twice).
- NULL in the foreign key column: whether an "optional" relation is allowed by business logic.
Limits and special cases. Not every schema has foreign keys: they are sometimes deliberately turned off (legacy databases, distributed services whose tables live in different databases). Then orphan records really appear, and they are found with a separate integrity query. In PostgreSQL a foreign key does not create an index on the referencing column automatically, so deleting parents and JOINs may be slow without one. A foreign key protects only the existence of the reference, not its business meaning: a UAH account can reference any existing user.
Common mistakes.
- Taking an email or phone as a primary key: the value changes and relations break.
- Assuming a foreign key is always there: the schema may lack it, and the data may already hold orphan rows.
- Checking only the UI: the form does not let you pick someone else's user, while the API or SQL does.
- Cleaning test data in the wrong order: child rows must be deleted first, then parents.
- Accepting a 500 from the API as the norm for a key violation: the client should get a clear error.
Check yourself
The orders table has a user_id column with a foreign key to users. Can an order be inserted with user_id = NULL?
Answer
Yes, if the column is not declared NOT NULL: NULL means "no reference" and the foreign key does not check it. Whether that is acceptable for an order is decided by business logic, so it is a separate test case.
Why does the users table use a surrogate primary key while the email is just a unique field?
Answer
An email can change, and the primary key is used in references from other tables. A surrogate key is stable, and the uniqueness of the email is guaranteed by a separate UNIQUE constraint.