Databases · Middle · Question 18 of 75
What is a 'lost update', and how can you prevent it?
-- Two requests at the same time:
SELECT balance FROM accounts WHERE id = 1; -- both read 100
UPDATE accounts SET balance = 150 WHERE id = 1; -- +50
UPDATE accounts SET balance = 130 WHERE id = 1; -- +30- 1Add an index on
balance - ✓Correct answer: One change overwrites the other; use an atomic update (
SET balance = balance + 50),SELECT ... FOR UPDATEor optimistic locking - 3It can't happen in PostgreSQL
Explanation
Read-modify-write in application code is the classic source. Let the database do the arithmetic, or lock or version the row.