Home / Learn Secure SQL / Locking Basics
Locking Basics
How the database keeps two writers from colliding.
The short versionHow the database keeps two writers from colliding.
Theory in plain words
The basic idea
A lock temporarily restricts access to a row or table so that two transactions cannot make conflicting changes at the same time.
Why this comes up
Understanding locks explains why a transaction sometimes waits, or fails with a "deadlock" error, and what to do about it.
The mechanics
Keep transactions short, access tables in a consistent order across your codebase, and let the database manage locks rather than trying to fully hand-roll your own.
Where it is used
- Web application code review
- Backend development
- Database administration
-- SELECT ... FOR UPDATE locks the selected rows until the transaction ends
BEGIN;
SELECT * FROM accounts WHERE id = 1 FOR UPDATE;
-- ... do the balance check and UPDATE here ...
COMMIT;Quick check
1. Keeping transactions short mainly helps...
Shorter lock duration, less contention.