SQLAdvanced#transactions#concurrency

What are optimistic and pessimistic locking?

Pessimistic locking takes a lock up front (SELECT ... FOR UPDATE) so nobody else can change the row. Optimistic locking takes no lock and detects conflicts at write time using a version column.

Example
-- pessimistic
SELECT * FROM seats WHERE id = 9 FOR UPDATE;
-- optimistic
UPDATE seats SET taken = 1, version = version + 1 WHERE id = 9 AND version = 3;

Related Questions

1
SQLIntermediate#procedures

What is a stored procedure and how does it differ from a function?

Open
2
SQLIntermediate#triggers

What is a trigger?

Open
3
SQLBeginner#aggregates#nulls

What are aggregate functions and how do NULLs affect them?

Open