Locking — Complete Guide
Locking — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of PostgreSQL Tutorial on Toolliyo Academy.
On this page
PostgreSQL Tutorial · Lesson 38 of 100
Locking
SQL → Advanced
SQL · 1 — Queries · ~6 min · PostgreSQL — Transactions & MVCC
What is this?
PostgreSQL locks guard rows, pages, and relations — FOR UPDATE takes exclusive row lock, SHARE locks allow concurrent reads. Lock modes escalate when DDL runs.
Why should you care?
PostgresVerse inventory decrement uses SELECT ... FOR UPDATE so two checkout tabs cannot sell the last unit.
See it live — copy this example
Run in pgAdmin or psql.
BEGIN;
SELECT stock_qty FROM products
WHERE product_id = 42
FOR UPDATE;
UPDATE products SET stock_qty = stock_qty - 1
WHERE product_id = 42;
COMMIT;
What happened?
- FOR UPDATE locks product row 42 for this transaction.
- Second session blocking on same SELECT waits until COMMIT.
- Prevents lost update on stock.
Practice next
- Session A: BEGIN; SELECT ... FOR UPDATE on one product.
- Session B: same query — observe wait.
- Session A: COMMIT — B proceeds.
- Use FOR UPDATE SKIP LOCKED to grab next job from queue table.
- Try NOWAIT and catch lock_not_available error.
Remember
FOR UPDATE is pessimistic row lock. SKIP LOCKED skips locked rows for queue workers. DDL takes stronger locks — plan migrations carefully.
PostgresVerse flash sale
Last 10 phones use FOR UPDATE on stock row during payment window.
Outcome: Oversell incidents drop to zero during countdown sales.
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!