What constraints are there and how do you test them?
Constraints are rules the database checks itself on every data change. They are PRIMARY KEY, FOREIGN KEY, NOT NULL, UNIQUE and CHECK (DEFAULT only supplies a value) and apply to every write path. For QA they are ready negative cases: the application must turn a refusal into a clear answer, for example 409, not 500. CHECK and UNIQUE let NULL through.
SQL · Constraints and indexes
Registering an existing email returns 500 with the database text. Whose bug is it?
A test registers a second user with the same email. The application answers "500 Internal Server Error" and the body shows the table and constraint name. The database did its job: it refused the duplicate. The bug is that the application did not turn the refusal into a clear answer. Constraints give QA a ready list of negative cases, and this lesson is about how to read and check them.
How it works and why. A constraint is a rule the database checks itself on every INSERT and UPDATE. Validation in a form or an API can miss a separate write path: an import, a script, another service. A constraint in the database applies to all paths at once, so it is the last line of defence. There is one more reason: a race. The application first runs SELECT "is there such an email", then INSERT. Two parallel requests both see "none" and both insert. Only a UNIQUE constraint in the database guarantees uniqueness, because the database serialises such conflicts.
The set: PRIMARY KEY (unique and not NULL, creates an index), FOREIGN KEY (a reference to an existing row), NOT NULL, UNIQUE, CHECK (any condition), DEFAULT (a value when the field is not passed; not a constraint, but it affects tests). Each violation has its own SQLSTATE code, from which the application must choose its answer.
| Constraint | SQLSTATE | What to check |
|---|---|---|
| NOT NULL | 23502 | a request without the field, with null and with an empty string |
| UNIQUE, PRIMARY KEY | 23505 | a duplicate, a duplicate in another case, parallel requests |
| FOREIGN KEY | 23503 | INSERT/UPDATE of a child with a missing parent, DELETE/UPDATE of the parent |
| CHECK | 23514 | boundaries: -0.01, 0, the largest value |
Example: tables and two refusals.
CREATE TABLE users (
id integer PRIMARY KEY,
email text NOT NULL,
CONSTRAINT users_email_unique UNIQUE (email)
);
CREATE TABLE accounts (
id integer PRIMARY KEY,
user_id integer NOT NULL REFERENCES users (id),
balance numeric(12,2),
CONSTRAINT balance_non_negative CHECK (balance >= 0)
);
The database rejects a duplicate email, and this is the code (23505) the application must catch:
INSERT INTO users VALUES (1, 'ana@test.com');
INSERT INTO users VALUES (2, 'ana@test.com');
-- ERROR: duplicate key value violates unique constraint
-- "users_email_unique"
-- DETAIL: Key (email)=(ana@test.com) already exists.
-- (message shortened)
The correct API behaviour: 409 Conflict (or 422 naming the email field) and a text like "this email is already registered". The wrong one: 500 and the raw database text, which also reveals table and constraint names.
Now the trap. CHECK rejects a row only when the condition is false. If the condition gives UNKNOWN because of NULL, the row passes:
INSERT INTO accounts VALUES (1, 1, -5.00);
-- ERROR: new row for relation "accounts" violates check
-- constraint "balance_non_negative"
INSERT INTO accounts VALUES (2, 1, NULL);
-- INSERT 0 1: accepted, although the balance is unknown
So CHECK (balance >= 0) without NOT NULL does not guarantee a non-negative balance: it can be unknown. Likewise UNIQUE treats two NULLs as different, so in a nullable column several rows with email = NULL pass (an empty string is an ordinary value, and a second one is a duplicate) (in PostgreSQL 15+ NULLS NOT DISTINCT changes this). And UNIQUE compares values literally: "Ana@test.com" and "ana@test.com" differ until uniqueness is built on lower(email).
Where the uniqueness rule lives
SELECT, then INSERT
Two parallel requests both see "none". The database holds two equal emails.
UNIQUE + handling 23505
The database rejects the second request. The application turns the refusal into 409.
Limits and alternatives. A new constraint on a table with data may fail to apply: ALTER TABLE … ADD CONSTRAINT checks all existing rows. For CHECK and foreign keys the NOT VALID option applies only to new writes and checks old rows later with VALIDATE CONSTRAINT. Not everything fits a constraint: the rule "balance not less than the sum of reserves" across tables needs a trigger or a check in code. Constraints also slow bulk loading, so an import sometimes defers them, and then the data must be checked with a query after the load.
Common mistakes.
- Checking only form validation and never bypassing it with a direct API request: the rule may exist only in the front end.
- Assuming CHECK or UNIQUE catches NULL: both let it through.
- Testing a duplicate sequentially and never trying two parallel requests.
- Accepting 500 with database text as "error handling": it is a defect and a leak of schema details.
- Forgetting the empty string:
NOT NULLlets it through, a separate CHECK is needed.
Check yourself
The accounts table has CHECK (balance >= 0). A test inserts an account with balance = NULL and the insert succeeds. Is it a database bug?
Answer
No, this is how SQL works: CHECK rejects a row only when the condition is false, and NULL >= 0 gives UNKNOWN. If the balance must be set, NOT NULL is needed too (or DEFAULT 0). A finding for QA: the requirement "balance is non-negative" is incomplete without "balance is mandatory".
users.email has UNIQUE. A test registers ana@test.com, then Ana@test.com, and both succeed. What now?
Answer
UNIQUE compares strings literally, so these are different values to the database. If the requirement says email is case-insensitive, it is a defect: a unique index on lower(email) (or the citext type) and email normalisation in the application are needed. The decision depends on the requirement, so clarify it first.