Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 146/ 160
08. Transactions, Security & Production SQL Administration

Table-Level Locks & Advisory Locks

Use table locks and advisory locks for migrations and application coordination.

AdvancedTable Locks · Advisory Locks3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Some changes need the whole table to themselves, and advisory locks are agreed-upon "I'm doing this" flags for your own jobs.

Think of it like…

A meeting room: normal use (reading and writing on the whiteboard) can happen together, but repainting the room needs everyone out, and anyone arriving while the painter waits must also wait. Advisory locks are a sign-up sheet on the door that only works because everyone agrees to check it.

Where you’ve seen it

Three app servers run the same nightly billing cron. Each starts with SELECT pg_try_advisory_lock(hashtext('nightly_billing')); the first gets true and runs the job, the others get false and exit immediately. The job ends with pg_advisory_unlock, and if the server crashes, the lock is released automatically when its session ends, so tomorrow's run isn't blocked.

Words you’ll hear

ACCESS SHARE / ROW EXCLUSIVE
Table locks taken by SELECT / by INSERT, UPDATE, DELETE; they don't conflict with each other.
ACCESS EXCLUSIVE
Taken by most ALTER TABLE, DROP, TRUNCATE, VACUUM FULL; conflicts with everything, even SELECT.
Lock queue
Waiting lock requests in order; a waiting ACCESS EXCLUSIVE blocks everyone who arrives after it.
Advisory lock
An application-defined lock on a 64-bit key, held per session or per transaction.

Visual diagram

Loading interactive diagram

Theory & example queries

Table lock modes and the lock queue

PostgreSQL has eight table lock modes. The everyday ones don't conflict: many sessions can read (ACCESS SHARE) and write rows (ROW EXCLUSIVE) at once, with row locks resolving conflicts on individual rows. CREATE INDEX takes SHARE, which blocks writes but not reads, and CREATE INDEX CONCURRENTLY takes a weaker lock that blocks neither. Most ALTER TABLE forms, DROP, TRUNCATE and VACUUM FULL need ACCESS EXCLUSIVE.

Locks are granted in queue order, so a waiting ACCESS EXCLUSIVE request blocks every later request on that table, even plain SELECTs that are compatible with the current holder. A two-millisecond ALTER can cause a multi-minute outage if it queues behind a long-running query. Always run DDL with SET lock_timeout = '3s' (and retry), and find blockers with SELECT pid, pg_blocking_pids(pid), query FROM pg_stat_activity WHERE wait_event_type = 'Lock';.

Safe DDLQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SET2  lock_timeout = '3s';34ALTER TABLE orders5ADD COLUMN gift_message text;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/5
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative lock-timeout result
SET ERROR: canceling statement due to lock timeout

Note: Assumes another transaction holds a conflicting lock. If the lock is available within 3 seconds, ALTER TABLE reports success instead.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

If the lock isn't granted within 3 seconds, the statement fails instead of blocking traffic, and the migration tool retries later.

Key takeaway: ACCESS EXCLUSIVE blocks all; a queued one blocks everyone behind it, so use lock_timeout.

Advisory locks for coordination

Advisory locks lock a number you choose (one bigint or two integers), often derived from a name with hashtext. pg_advisory_lock(k) waits for the lock and holds it until pg_advisory_unlock or the session ends; pg_try_advisory_lock(k) returns true or false immediately; pg_advisory_xact_lock(k) is released automatically at COMMIT or ROLLBACK. Uses include single-instance cron jobs, serialising work per customer (pg_advisory_xact_lock(customer_id)), and migration tools such as Flyway and Rails migrations, which use one to stop two deploys migrating at once.

Watch for connection pooling: session-level advisory locks belong to a database connection, and with PgBouncer in transaction mode, the next transaction on that connection may be someone else's, so the lock leaks or is released by the wrong code. Prefer transaction-level locks there. Locks are visible in pg_locks with locktype = 'advisory'. MySQL offers similar named locks with GET_LOCK('name', timeout) and RELEASE_LOCK('name').

Serialise processing per customerQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1BEGIN;23SELECT4  pg_advisory_xact_lock(4821);56UPDATE wallets7SET8  balance = balance - 2509WHERE10  customer_id = 4821;1112INSERT INTO13  ledger (customer_id, amount)14VALUES15  (4821, -250);1617COMMIT;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Start transaction

Open a transaction so changes can be checked and committed or rolled back together.

1/17
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative serialized transaction
BEGIN UPDATE 1 INSERT 0 1 COMMIT

Note: Assumes wallet 4821 exists with enough balance; competing transactions using the same advisory key wait, while other keys can proceed.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Other transactions for customer 4821 wait; other customers proceed in parallel.

Key takeaway: try-lock for single-run jobs, xact locks with poolers, keys from hashtext or ids.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Lock modes

Know what each statement locks

Reads and row writes coexist; most ALTER, DROP and TRUNCATE need ACCESS EXCLUSIVE.

SQL at this stepReadable preview
1SELECT: ACCESS SHARE · ALTER: ACCESS EXCLUSIVE
What to watch at this step
Modes
8 in PostgreSQL
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

Besides row locks, databases take table-level locks automatically: in PostgreSQL every SELECT holds ACCESS SHARE, every INSERT, UPDATE or DELETE holds ROW EXCLUSIVE, and ALTER TABLE, DROP and TRUNCATE need ACCESS EXCLUSIVE, which conflicts with everything. Advisory locks are different: the database doesn't take them for you; your application asks for a lock on a number, such as pg_advisory_xact_lock(42), to coordinate work like "only one server runs the billing job".

Why it matters: Two production problems come from table locks: a migration's ALTER TABLE waiting behind a long query and blocking all traffic queued behind it, and jobs running twice because several servers started them. Understanding lock modes and the lock queue prevents the first; advisory locks solve the second without extra infrastructure. Both come up in backend and DevOps interviews.

When to reach for it

  • Making sure a cron job runs on only one server
  • Serialising balance changes per customer
  • Safe schema migrations with lock_timeout

When to avoid or be careful

  • DDL without lock_timeout on busy tables
  • Session-level advisory locks behind PgBouncer transaction pooling
  • LOCK TABLE in application code paths

Ways to coordinate concurrent work

Row locks (SELECT … FOR UPDATE)
Best for: Protecting specific rows during read-modify-write

Strengths: Fine-grained; automatic with the data.

Watch out: Only covers rows that already exist.

Advisory locks
Best for: Single-run jobs and per-key serialisation not tied to one row

Strengths: No extra infrastructure; released on disconnect.

Watch out: Purely cooperative; session locks misbehave with transaction pooling.

Explicit LOCK TABLE
Best for: Rare maintenance needing a whole table quiet

Strengths: Simple and absolute.

Watch out: Blocks other work; easy to cause outages.

Interview signals & numbers to know

When this topic comes up

  • “A migration took the site down for a few minutes”
  • “The job ran twice on two servers”
  • “How do you prevent concurrent runs?”
  • Lock queues
  • pg_advisory_lock

Benchmarks & rules of thumb

8 -
table lock modes in PostgreSQL
3 s -
a typical lock_timeout for migrations
64-bit -
advisory lock key size

Common mistakes & follow-ups

Common interview mistakes

  • Running ALTER TABLE during a long analytics query, so the ALTER queues and every request behind it times out.
  • Taking pg_advisory_lock through PgBouncer in transaction mode and never releasing it on the right connection.
  • Using pg_advisory_lock (waiting) for a cron guard, so the other servers queue up and run the job afterwards.

Likely interviewer follow-ups

  • Why can a fast ALTER TABLE block all queries on a table?
  • How would you ensure a scheduled job runs only once across several servers?
  • What's the difference between session and transaction advisory locks?
Interview tip: Explain the lock queue with the three-step story: long SELECT, waiting ALTER, everyone else blocked. Then give lock_timeout as the fix. That story shows real production experience.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Table-Level Locks & Advisory Locks with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Row-Level Locking (SELECT ... FOR UPDATE, FOR SHARE, SKIP LOCKED)
Next topic
Understanding, Detecting & Preventing Deadlocks