Database Locks Explained: Shared, Exclusive, FOR UPDATE
Shared vs exclusive locks, SELECT … FOR UPDATE against lost updates, row, page and table locks, lock escalation and range locks.
In this chapter
Locks: who waits for whom, and how much gets locked
Database locks: common questions
What does SELECT … FOR UPDATE do?
It locks the selected rows until the transaction ends, so other transactions that try to update or lock them wait.
More on Transactions: locks and production
Keep learning
Overview
SELECT (plain) none (reads the snapshot) light shared schema lock SELECT ... FOR SHARE S on each row read SELECT ... FOR UPDATE X on each row read UPDATE, DELETE X on rows changed (some engines: every row read) X on the new row foreign key check S-like lock on the parent row ALTER TABLE, DROP TABLE exclusive schema lock chapters · transactions, isolation and locks Locks: who waits for whom, and how much gets locked stock both sessions read each writes its own answer 1 lost update silently disappears → follows snapshot reads: what locking reads wait for, lock sizes, finding the queue head.
1. Shared and exclusive: many readers or one writer
S (shared) Others may read, not change. S + S is fine. X (exclusive) Everyone else is kept out. Which statement takes which lock (held until tx ends) Row locks Pick a statement per session. Does B wait?
2. The everyday fix: SELECT … FOR UPDATE stops a lost update
Plain SELECT takes no lock SELECT qty sees 10 T1's +10 lost FOR UPDATE: T2 waits, then sees 20 SELECT qty FOR UPDATE sees 10, X lock waits for T1 lock released Simple arithmetic: one atomic UPDATE, no locking read needed. Other fixes Version columns, serializable → write anomalies
3. Lock sizes, escalation, and the intention tags that connect them
A whole-table request checks only the table, not every row. Row lock Page lock Table lock Big UPDATE Lock escalation: memory saved, table stalled UPDATE 700,000 rows row locks pile up too many locks on table swap for 1 table lock UPDATE any other row Who escalates SQL Server ~5,000 locks on one object (default) Compact row locks per page Row locks stored in rows themselves Escalating engine? Update large tables in smaller batches. Intention locks (IS, IX) Clash only with whole-table S/X. 1,000 row updates never block. Pick held vs requested lock: can they coexist?
4. Row, range and predicate locks: stopping phantoms
A phantom is a newly inserted row that appears on re-run. You can't lock a row that isn't there yet. Three ways to protect a query's result Stops phantoms Engine detail Rows the statement found Every engine Interval of index keys, incl. empty gaps The WHERE condition itself Range lock follows the index used Its size depends on the access path. ↓
5. Why a missing index locks more rows
No index Scan every row. Locks left behind depend on engine + level. Scan cost always. One index Fixes speed and locking together. Policy for scanned rows that do not match Policy in the lab InnoDB, REPEATABLE READ Lock every row read, keep (plus ranges) InnoDB, READ COMMITTED Lock each row read, release non-matches PostgreSQL, any level Check first, lock only matches Read the plan before a big UPDATE → MySQL EXPLAIN · PostgreSQL EXPLAIN
6. Schema locks queue behind a long transaction
Step an ALTER TABLE in while an old transaction is open. Old tx New queries A waiting exclusive request blocks even compatible ones SELECT … (tx stays open) shared schema lock ALTER TABLE … wants exclusive: waits SELECT … queues behind ALTER queues too Before DDL Look for old open tx on that table. Short lock timeout Run DDL with it and retry. Online schema tools Still need brief exclusive lock at start and end.
7. Lock waits, timeouts and deadlocks
Deadlock: neither can continue UPDATE row A locks A UPDATE row B locks B waits for T2 cycle → victim → continues T2 rolled back When a wait does not end Engine does Application does Chain of waits Cycle (deadlock) Schema lock wait Often no practical default timeout Set a short one for DDL Every engine has a lock-wait view: one row per waiter + its blocker. → deadlock interview A lock-wait view, as most engines shape it (sample rows) blocked by blocker state orders row 81 idle in transaction, 9 min data_lock_waits, sys.innodb_lock_waits → diagnostics pg_locks + pg_blocking_pids() → diagnosis Timeout settings → MySQL config · PG locks
Remember
FOR UPDATE or atomic UPDATE, else lost update. Lock size Intention tags Clash only with whole-table locks. Need range or predicate locks. Missing index Can lock the whole table. Waiting DDL transaction mistakes
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.