Bird
Raised Fist0
PostgreSQLquery~10 mins

Advisory locks in PostgreSQL - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Advisory locks
Start Transaction
Request Advisory Lock
Check Lock Availability
Lock Acquired
Perform Work
Release Lock
End Transaction
The flow shows starting a transaction, requesting an advisory lock, waiting if needed, doing work, then releasing the lock and ending the transaction.
Execution Sample
PostgreSQL
BEGIN;
SELECT pg_advisory_lock(12345);
-- critical section
SELECT pg_advisory_unlock(12345);
COMMIT;
This code acquires an advisory lock with key 12345, does some work, then releases the lock.
Execution Table
StepActionFunction CallResultLock State
1Start transactionBEGIN;Transaction startedNo lock held
2Request lockSELECT pg_advisory_lock(12345);Lock acquiredLock 12345 held by session
3Perform work-- critical sectionWork doneLock 12345 held by session
4Release lockSELECT pg_advisory_unlock(12345);Lock releasedNo lock held
5End transactionCOMMIT;Transaction committedNo lock held
💡 Transaction ends and lock is released if not already unlocked.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
Lock 12345Not heldHeldHeldReleasedReleased
TransactionNot startedStartedStartedStartedCommitted
Key Moments - 3 Insights
Why does the session wait at pg_advisory_lock if another session holds the lock?
Because pg_advisory_lock blocks until the lock is free, as shown in step 2 where the lock is acquired only when available.
What happens if you forget to call pg_advisory_unlock?
The lock stays held until the transaction ends, so it is automatically released at COMMIT or ROLLBACK, as shown in step 5.
Can advisory locks be used outside transactions?
Yes, advisory locks are session-level and can be used outside explicit transactions; however, locks acquired outside transactions are held until the session ends or the lock is explicitly released.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the lock state after step 3?
ANo lock held
BLock 12345 released
CLock 12345 held by session
DLock 12345 waiting
💡 Hint
Check the 'Lock State' column in row for step 3 in the execution table.
At which step is the lock released according to the execution table?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the 'Action' and 'Result' columns for when the lock is released.
If pg_advisory_lock is called while the lock is held by another session, what happens?
AThe call blocks until the lock is free
BThe call returns immediately with success
CThe call fails with an error
DThe lock is forcibly taken
💡 Hint
Refer to the concept flow where 'Check Lock Availability' leads to waiting if lock is not free.
Concept Snapshot
Advisory locks in PostgreSQL allow sessions to lock resources by key.
Use pg_advisory_lock(key) to acquire a lock; it blocks if taken.
Use pg_advisory_unlock(key) to release the lock.
Locks are session-based and released automatically at transaction end.
Useful for application-level synchronization without locking tables.
Full Transcript
This visual execution shows how advisory locks work in PostgreSQL. First, a transaction starts. Then the session requests an advisory lock with a key. If the lock is free, it is acquired; otherwise, the session waits. While holding the lock, the session performs work. After finishing, it releases the lock explicitly or it is released automatically when the transaction commits or rolls back. The lock state changes from not held to held and back to released. Advisory locks help coordinate access to resources without blocking database rows or tables directly.

Practice

(1/5)
1. What is the main purpose of advisory locks in PostgreSQL?
easy
A. To control access to resources using user-defined keys
B. To automatically manage table-level locks during transactions
C. To speed up query execution by caching results
D. To backup the database safely without downtime

Solution

  1. Step 1: Understand advisory locks concept

    Advisory locks allow applications to coordinate access to resources by using custom keys, not automatic locks on tables or rows.
  2. Step 2: Compare options

    The other options describe other database features unrelated to advisory locks.
  3. Final Answer:

    To control access to resources using user-defined keys -> Option A
  4. Quick Check:

    Advisory locks = user-defined resource control [OK]
Hint: Advisory locks use keys to manage resource access [OK]
Common Mistakes:
  • Confusing advisory locks with automatic table locks
  • Thinking advisory locks speed up queries
  • Assuming advisory locks handle backups
2. Which of the following is the correct syntax to acquire a session-level advisory lock with key 12345?
easy
A. SELECT pg_advisory_lock(12345);
B. LOCK TABLE pg_advisory_lock(12345);
C. SELECT acquire_lock(12345);
D. BEGIN LOCK 12345;

Solution

  1. Step 1: Recall advisory lock syntax

    PostgreSQL uses the function pg_advisory_lock(key) to acquire a session-level advisory lock.
  2. Step 2: Evaluate options

    SELECT pg_advisory_lock(12345); is the correct function call. The other options use invalid syntax or non-existent functions.
  3. Final Answer:

    SELECT pg_advisory_lock(12345); -> Option A
  4. Quick Check:

    pg_advisory_lock(key) = correct syntax [OK]
Hint: Use SELECT pg_advisory_lock(key) to lock [OK]
Common Mistakes:
  • Using LOCK TABLE instead of function call
  • Calling non-existent functions like acquire_lock
  • Trying to lock with BEGIN LOCK syntax
3. What will be the result of this query if the advisory lock with key 999 is already held by another session?
SELECT pg_try_advisory_lock(999);
medium
A. true
B. false
C. null
D. error

Solution

  1. Step 1: Understand pg_try_advisory_lock behavior

    This function tries to acquire the lock immediately and returns true if successful, false if the lock is held by someone else.
  2. Step 2: Analyze the scenario

    Since the lock with key 999 is already held, the function returns false without waiting.
  3. Final Answer:

    false -> Option B
  4. Quick Check:

    pg_try_advisory_lock returns false if lock busy [OK]
Hint: pg_try_advisory_lock returns false if lock busy [OK]
Common Mistakes:
  • Expecting true even if lock is held
  • Thinking it returns null or error
  • Confusing pg_try_advisory_lock with pg_advisory_lock
4. You wrote this code:
SELECT pg_advisory_unlock(123);

But the lock was never acquired before. What will happen?
medium
A. The function returns true and releases the lock
B. The function blocks until the lock is acquired
C. The function throws an error
D. The function returns false because no lock was held

Solution

  1. Step 1: Understand pg_advisory_unlock behavior

    This function releases a lock if held and returns true; if no lock was held, it returns false.
  2. Step 2: Analyze the scenario

    Since the lock was never acquired, the function returns false without error or blocking.
  3. Final Answer:

    The function returns false because no lock was held -> Option D
  4. Quick Check:

    Unlock returns false if lock not held [OK]
Hint: Unlock returns false if no lock held [OK]
Common Mistakes:
  • Expecting an error when unlocking unheld lock
  • Thinking unlock blocks or waits
  • Assuming unlock always returns true
5. You want to ensure two different sessions do not run a critical section simultaneously using advisory locks. Which approach is best?
-- Session 1 and 2 run this code:
SELECT pg_try_advisory_lock(42);
-- If true, run critical section, then
SELECT pg_advisory_unlock(42);
hard
A. Use pg_advisory_unlock before acquiring lock to clear old locks
B. Use pg_try_advisory_lock to attempt lock and skip if busy
C. Use pg_advisory_lock to wait until lock is available before running
D. Use random keys each time to avoid conflicts

Solution

  1. Step 1: Understand locking strategies

    pg_try_advisory_lock returns immediately and may skip critical section if lock busy; pg_advisory_lock waits until lock is free.
  2. Step 2: Choose best approach for critical section

    To ensure only one session runs critical section at a time, waiting for the lock is safer than skipping it.
  3. Step 3: Evaluate other options

    Unlocking before acquiring is unsafe and random keys defeat locking purpose.
  4. Final Answer:

    Use pg_advisory_lock to wait until lock is available before running -> Option C
  5. Quick Check:

    Waiting lock ensures exclusive access [OK]
Hint: Use pg_advisory_lock to wait for exclusive access [OK]
Common Mistakes:
  • Using try lock and skipping critical section silently
  • Unlocking before locking without owning lock
  • Using random keys causing no real locking