Sub topic 4
Consistency: constraints and valid states
This chapter assumes you know basic SQL (SELECT, INSERT, UPDATE, DELETE), what tables, primary keys and constraints are, and the BEGIN, COMMIT and ROLLBACK commands from the previous chapters. Examples use PostgreSQL syntax.
What "consistency" means in ACID
In ACID, consistency means that a transaction takes the database from one valid state to another valid state. A valid state is one where every rule you have declared holds. Those rules are constraints, and they include rules the application enforces through triggers or code.
Consistency is different from the other three properties. The database engine provides atomicity, isolation and durability on its own. Consistency is shared work. The engine enforces the rules you declare, and you must declare the right rules and write transactions that move data correctly. If you never declare a rule, the database cannot protect it.
The word also has other meanings. In the CAP theorem and in replication, "consistency" describes whether replicas agree with each other. In ACID it only means that the declared rules hold at commit time.
Constraints are the rules
A constraint is a rule the database checks for you. The common kinds are:
| Constraint | What it guarantees | Example |
|---|---|---|
| NOT NULL | A column always has a value | `balance numeric NOT NULL` |
| PRIMARY KEY | Each row has a unique, non-null identity | `id integer PRIMARY KEY` |
| UNIQUE | No two rows share the same value | `email text UNIQUE` |
| CHECK | A condition on the row is true | `CHECK (balance >= 0)` |
| FOREIGN KEY | A row refers to a row that exists | `account_id REFERENCES accounts(id)` |
| EXCLUDE | No two rows conflict under a chosen operator (PostgreSQL) | no overlapping room bookings |
Here is the table used throughout this tutorial.
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance numeric(12,2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts (id, balance) VALUES (1, 100.00), (2, 50.00);The CHECK constraint states a business rule: no account may go negative. Every INSERT and UPDATE is tested against it. A statement that would break the rule fails, and the row is not changed.
A violation stops the invalid state
Suppose a transfer tries to take 500 from an account that holds 100.
BEGIN;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
-- Fails: new balance would be negative, so the CHECK constraint rejects it.
-- In PostgreSQL the transaction is now aborted and must be rolled back.
ROLLBACK;
SELECT balance FROM accounts WHERE id = 1;
-- Still the value from before the failed transaction.PostgreSQL reports an error such as new row for relation "accounts" violates check constraint "accounts_balance_check". After that error the transaction is in an aborted state. Every further statement is refused with "current transaction is aborted, commands ignored until end of transaction block" until you issue ROLLBACK. A COMMIT on an aborted transaction acts as a ROLLBACK.
Other databases differ. MySQL with InnoDB, for example, rolls back only the failing statement and leaves the transaction open. Check your database's documentation before you write code that depends on this behavior.
This is where consistency and atomicity meet. Atomicity discards the partial work, and the constraint decides whether the work was valid in the first place.
A multi-step transfer stays valid
Consider the transfer from earlier chapters.
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
COMMIT;The rule "money is neither created nor destroyed" is not a declared constraint. Between the two UPDATE statements the total is 30 short. That is fine, because consistency is only required at the boundaries: before BEGIN and after COMMIT. Other sessions never see the middle state, because of isolation. The correctness of the sum comes from the transaction's logic, which you wrote.
Immediate and deferred checks
Most constraints are checked at the end of each statement. This is called immediate checking. It can be inconvenient when several rows must change together and the intermediate state would break a rule.
PostgreSQL lets you declare UNIQUE, PRIMARY KEY, EXCLUDE and FOREIGN KEY constraints as DEFERRABLE. A deferrable constraint can be checked at COMMIT instead. NOT NULL and CHECK constraints cannot be deferred.
CREATE TABLE slots (
position integer UNIQUE DEFERRABLE INITIALLY IMMEDIATE
);
INSERT INTO slots (position) VALUES (1), (2), (3);
BEGIN;
SET CONSTRAINTS ALL DEFERRED;
UPDATE slots SET position = position + 1;
COMMIT;Without deferral, the UPDATE can fail with a unique violation. Row 1 becomes 2 while row 2 still holds 2, and a unique index checks as it goes. With the check deferred to COMMIT, only the final state is tested, and that state is valid.
Note that DEFERRABLE on a UNIQUE constraint also changes how PostgreSQL performs the check, and it can be slower. Use it only where you need it.
Where constraints cannot help
Constraints protect a single row, or a pair of rows linked by a key. Rules that span many rows are harder. For example, "at least one doctor is on call" cannot be written as a CHECK on one row, because the rule depends on other rows.
Concurrent transactions can break such rules even though each transaction looks correct alone. This is the write skew anomaly, covered in the chapters on concurrency anomalies and isolation levels. In the doctors example, two sessions each see two doctors on call, and each takes a different doctor off call. Under REPEATABLE READ in PostgreSQL both commit and nobody is left on call. Under SERIALIZABLE one transaction fails with SQLSTATE 40001 and must be retried.
So consistency depends on isolation. The database promises that each transaction preserves the rules if the transaction would preserve them when run alone and the isolation level makes concurrent runs behave like some serial order. Without a strong enough isolation level, declared rules still hold but undeclared, multi-row rules can break.
Common mistakes
- Checking in the application only. A check such as "if balance >= amount then update" in app code can race with another session. Put the rule in a constraint so the database enforces it every time.
- Allowing NULL by accident. Columns are nullable by default. A CHECK like
balance >= 0passes whenbalanceis NULL, because the result is unknown, not false. Add NOT NULL where a value is required. - Ignoring the aborted state. After an error in PostgreSQL, keep sending statements and they all fail. Always handle the error by rolling back, or by rolling back to a savepoint.
- Assuming consistency covers business rules you did not declare. The database only knows what you told it.
- Swallowing constraint errors. Treat violations as expected outcomes. Catch them, report them, and do not retry them. A retry cannot fix a rule violation, unlike a deadlock.
Summary of the mechanism
When a statement changes a row, the database checks the row-level and key constraints, either right away or at COMMIT for deferred ones. If any check fails, the statement raises an error, and the transaction must roll back or recover to a savepoint. Nothing invalid can be committed. Rules you did not declare, and rules that depend on concurrent activity, remain your responsibility.
Exercise
A table has qty integer CHECK (qty >= 0). A transaction runs INSERT INTO items (qty) VALUES (NULL); and it succeeds. Why, and what one change prevents it?
Show answer
A CHECK constraint passes when its condition evaluates to unknown, and NULL >= 0 is unknown, not false. Declaring the column qty integer NOT NULL CHECK (qty >= 0) makes the insert fail.
Exercise
In PostgreSQL, a transaction runs an UPDATE that violates a CHECK constraint, and the application then sends a second, valid UPDATE in the same transaction followed by COMMIT. What happens to the second UPDATE and to the COMMIT?
Show answer
The transaction is aborted after the first error, so the second UPDATE is refused with "current transaction is aborted, commands ignored until end of transaction block". The COMMIT acts as a ROLLBACK, so no changes are saved. To keep the valid work, the application would have to use a savepoint before the failing statement and roll back to it.
Exercise
Why can the rule "at least one doctor must be on call" not be protected by a CHECK constraint, and which isolation level in PostgreSQL protects it when two transactions run at once?
Show answer
A CHECK constraint sees only one row, but the rule depends on the state of several rows. Two concurrent transactions can each pass their own check and still break the rule together (write skew). SERIALIZABLE detects this and aborts one transaction with SQLSTATE 40001, which the application should retry.