Locking — Complete Guide
Locking — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of MySQL Tutorial on Toolliyo Academy.
On this page
MySQL Tutorial · Lesson 46 of 100
Locking
Basics ✓ → Advanced
Advanced · 2 — Production · ~6 min · MySQL — Transactions & Concurrency
What is this?
Locks coordinate concurrent access: shared locks for reads, exclusive for writes. Row locks in InnoDB block conflicting UPDATE/DELETE on same rows; gap locks protect ranges in REPEATABLE READ.
Why should you care?
Seat booking or flash sale inventory must serialize conflicting updates — otherwise two users buy the last unit.
See it live — copy this example
Run in MySQL Workbench or the mysql CLI.
START TRANSACTION;
SELECT stock_qty FROM products WHERE product_id = 10 FOR UPDATE;
UPDATE products SET stock_qty = stock_qty - 1 WHERE product_id = 10;
COMMIT;
What happened?
- FOR UPDATE locks matching rows exclusively for this transaction.
- Other sessions block on same row until COMMIT.
- Prevents two checkouts reading “1 left” and both selling.
Practice next
- Tab A: START; SELECT ... FOR UPDATE on product 10.
- Tab B: try UPDATE same product — waits.
- Tab A COMMIT; Tab B proceeds.
- NOWAIT / SKIP LOCKED (MySQL 8+) for queue workers.
- SHOW PROCESSLIST when B is waiting — State shows lock wait.
Remember
FOR UPDATE = exclusive row lock intent. Locks release at transaction end. Design hot paths to hold locks briefly.
DataFlow flash sale SKU
Checkout uses FOR UPDATE on stock row before decrement.
Outcome: Only one buyer gets the last unit.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!