Adjust Salaries Atomically
Engineering has an unallocated salary pool of 5000.00. Four
changes have been approved and they take effect together:
- Carol is leaving — remove her row and return her salary to the pool
- Alice gets
+4000.00, funded from the pool - Bob gets
+3000.00, funded from the pool
Apply all of it inside a single transaction, then return the final state:
SELECT e.name, e.salary, p.unallocated
FROM employee e JOIN pool p ON p.department_id = e.department_id
ORDER BY e.name;
The pool may never go negative — a CHECK
enforces it. The raises cost 7000.00 and the pool holds
5000.00, so the sequence has to be arranged for the constraint to
hold after every statement, not just at COMMIT.
Expected output
name | salary | unallocated
------+----------+------------
Alice | 94000.00 | 4000.00
Bob | 83000.00 | 4000.00
Dan | 70000.00 | 4000.00
Editorial
The arithmetic is not the problem. 5000 + 6000 - 7000 = 4000
whichever order you do it in. The constraint is the problem, because it
is checked after every statement rather than at COMMIT.
BEGIN;
UPDATE pool
SET unallocated = unallocated + (SELECT salary FROM employee WHERE name = 'Carol')
WHERE department_id = 1;
DELETE FROM employee WHERE name = 'Carol';
UPDATE employee SET salary = salary + 4000.00 WHERE name = 'Alice';
UPDATE employee SET salary = salary + 3000.00 WHERE name = 'Bob';
UPDATE pool SET unallocated = unallocated - 7000.00 WHERE department_id = 1;
COMMIT;
The refund goes first: the pool runs 5000 → 11000 → 4000 and is in range the
whole way. Spend first and it goes to -2000 at the second statement, the
CHECK rejects it, and the transaction is left in an aborted state
where every later statement fails with "current transaction is aborted" until
you ROLLBACK.
Note the order of the first two statements as well. The refund reads Carol's
salary, so it has to run before the DELETE removes the row it
reads. Swap them and the subquery returns NULL,
unallocated + NULL is NULL, and the NOT NULL
constraint rejects it — a different error from the same cause, which is
statements that depend on each other being written in the wrong order.
Why one transaction and not five statements
Without BEGIN, each statement is its own transaction and commits
on its own. If the process dies after the delete and before the raises, Carol is
gone, the pool is 11000, and nobody got a raise — a state no business rule
allows and nothing will ever correct, because there is no record of what was
meant to happen. 💡 Atomicity = the group of statements either all take
effect or none do. It is the property that lets you reason about the database in
terms of valid states instead of every point partway through your code.
DEFERRABLE, when the order cannot be arranged
Sometimes no ordering works — swapping two uniquely-numbered rows is the
standard example, where either assignment collides with the other's current
value. For that, PostgreSQL can hold the check until COMMIT:
ALTER TABLE pool ADD CONSTRAINT pool_nonneg
CHECK (unallocated >= 0) DEFERRABLE INITIALLY DEFERRED;
With that in place the spend-first order commits, because the only moment
that matters is the end. Two things to know before reaching for it.
CHECK constraints cannot actually be deferred in
PostgreSQL — only UNIQUE, PRIMARY KEY,
FOREIGN KEY and EXCLUDE can, so the statement above is
rejected and the real swap case needs a unique constraint. And deferring trades
an early, precise error for a late, vague one: a failure at
COMMIT tells you the transaction is invalid without telling you
which statement made it so.
Doing it in one statement instead
WITH refund AS (
DELETE FROM employee WHERE name = 'Carol' RETURNING salary
), raises AS (
UPDATE employee SET salary = salary + CASE name WHEN 'Alice' THEN 4000.00 ELSE 3000.00 END
WHERE name IN ('Alice','Bob') RETURNING salary
)
UPDATE pool SET unallocated = unallocated + (SELECT salary FROM refund) - 7000.00
WHERE department_id = 1;
💡 A data-modifying CTE — DELETE ... RETURNING inside
WITH — lets several writes share one statement, and therefore one
snapshot. It commits, and it is worth knowing for the reason it works:
every sub-statement sees the same snapshot and the constraint is evaluated once
at the end of the statement, so the intermediate -2000 never exists. It is also
harder to read and the ordering between the CTEs is not guaranteed, which is
why the explicit transaction is the better answer to give out loud.
What an interviewer is checking
That you say BEGIN without being asked, and that you know a
constraint is checked per statement by default. The follow-up worth preparing is
"what if two of these ran at once" — which is where row locks and
SELECT ... FOR UPDATE come in, and which a single connection cannot
show you.
department
1 row
| idinteger | nametext |
|---|---|
| 1 | Engineering |
employee
4 rows
| idinteger | nametext | department_idinteger | salarynumeric(10,2) |
|---|---|---|---|
| 1 | Alice | 1 | 90000 |
| 2 | Bob | 1 | 80000 |
| 3 | Carol | 1 | 6000 |
| 4 | Dan | 1 | 70000 |
pool
1 row
| department_idinteger | unallocatednumeric(10,2) |
|---|---|
| 1 | 5000 |