Part 12 / Topic 9 of 9
Advisory locks
Sometimes the thing to serialise isn't a row — it's an idea: "only one nightly report at a time", "one import per supplier". Advisory locks are application-defined locks on a number you choose; Postgres manages the queueing, you define the meaning:
SELECT pg_try_advisory_lock(42) AS got_it;
SELECT pg_try_advisory_lock(42) AS got_it_again;
SELECT pg_advisory_unlock(42) AS first_release,
pg_advisory_unlock(42) AS second_release,
pg_advisory_unlock(42) AS one_too_many;
got_it
--------
t
(1 row)
got_it_again
--------------
t
(1 row)
WARNING: you don't own a lock of type ExclusiveLock
first_release | second_release | one_too_many
---------------+----------------+--------------
t | t | f
(1 row)
pg_try_advisory_lock returns instead of blocking — t means you hold it. The second call still says t because the same session may re-take its own lock — they stack, which is why both releases return t and only the third, with nothing left to release, returns f (plus a warning). From another session, that second lock attempt would return f — which is the whole point: one job runs, the rest bow out. Session advisory locks survive COMMIT and die with the connection; pg_advisory_xact_lock variants release at transaction end — the safer default in pooled environments.
🧪 Quick quiz — answer from memory, then check.
- What does an advisory lock actually lock?
- When do session advisory locks release?
Show the answers
- Nothing but a number — the meaning ("the nightly report") is the application's convention.
- On explicit unlock or when the session disconnects (xact variants: at transaction end).
Done here? The practice set for Part 12 — 6 exercises with solutions — is on the part page.