Interview Q&A / PostgreSQL

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What are advisory locks in PostgreSQL and when would you use one?

SHORT ANSWER

Advisory locks are application-defined locks on an arbitrary number, managed by PostgreSQL but not tied to any table or row. Use them to make sure only one process runs a task, like a nightly report job, at a time.

Explain it simply

A "Meeting in progress" sign on a door has no power to stop anyone physically; it works because everyone agrees to respect it. Advisory locks are such signs. PostgreSQL stores and queues them for you, but only code that asks for the same lock number is affected. Tables and rows are not touched.

Example

sql
-- Try to become the single runner of job 42
SELECT pg_try_advisory_lock(42);   -- true if you got it, false if another session has it

-- ... run the nightly report ...

SELECT pg_advisory_unlock(42);

-- Transaction-scoped version: released automatically at COMMIT/ROLLBACK
BEGIN;
SELECT pg_advisory_xact_lock(hashtext('nightly-report'));
-- work
COMMIT;

Session-level locks stay until you unlock or disconnect, so with a connection pooler in transaction mode they can be left behind or taken on the wrong connection. Prefer the xact variants there.

What to say in the interview

"Advisory locks let an application lock an abstract key, for example to ensure one cron instance runs at a time. I use the transaction-scoped versions, especially behind PgBouncer, so locks are never leaked."

Common mistakes

  • Using session-level advisory locks through a transaction-mode pooler.

#postgresql#locks#advisory-lock

Related questions

Practise more PostgreSQL questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open PostgreSQL quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.