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

A row locktransaction A locks arowtransaction B mustwaitA commits/rollbacks,lock released, B…
A row lock

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
Explicit row locking (PostgreSQL/MySQL)
-- 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...