LISTEN is a PostgreSQL session-level command that registers the current connection as a subscriber to one or more notification channels. Once registered, the backend delivers any NOTIFY messages sent on those channels to the client as asynchronous events. A LISTEN takes effect immediately and lasts until the session ends or an UNLISTEN command cancels it. LISTEN is transaction-scoped during execution (it is rolled back if the surrounding transaction aborts) but the subscription itself persists across subsequent transactions in that session. LISTEN has no performance cost when idle, because the server only wakes the client when a relevant NOTIFY is committed. Each notification carries an optional payload string and the process ID of the backend that sent it. LISTEN is useful for building pub-sub systems, cache invalidation hooks, real-time user interfaces, and any workflow that benefits from triggerless eventing. Caveats: LISTEN works only inside a single PostgreSQL cluster, is not forwarded by logical replication, and requires the client driver to poll or wait on the socket for notifications.
channel_name
(identifier) - The name of the channel to subscribe to.*
(asterisk) - Special wildcard that subscribes to every channel (PostgreSQL 16+).NOTIFY, UNLISTEN, triggers, asynchronous events, LISTEN/NOTIFY pattern
PostgreSQL 6.4
LISTEN subscribes a session to a channel, while NOTIFY publishes a message to that channel. Both together form PostgreSQL's built-in pub-sub mechanism.
No. The command itself returns immediately. After that, the backend delivers notifications asynchronously while the session is idle or between statements.
Most PostgreSQL client libraries expose an event loop, callback, or polling function (e.g., `pg_connection.notifies` in libpq) that returns pending notifications along with the channel name, payload, and sender PID.
Yes, but only in AUTONOMOUS transactions or when the function is called directly. A long-running function cannot process incoming notifications while executing.