How to Use LISTEN in PostgreSQL for Notifications
In PostgreSQL, use the
LISTEN command to wait for notifications on a specified channel. When another session sends a notification with NOTIFY, the listening session receives it asynchronously, enabling event-driven communication.Syntax
The LISTEN command subscribes the current session to a notification channel. The syntax is simple:
LISTEN channel_name;— subscribes to notifications onchannel_name.- Use
UNLISTEN channel_name;to stop listening on that channel. - Use
UNLISTEN *;to stop listening on all channels.
Notifications are sent using NOTIFY channel_name, 'payload'; where payload is optional text data.
sql
LISTEN channel_name; -- Waits for notifications on 'channel_name' UNLISTEN channel_name; -- Stops listening on 'channel_name' UNLISTEN *; -- Stops listening on all channels
Example
This example shows two sessions: one listens on a channel, and the other sends a notification. The listening session will receive the notification asynchronously.
sql
-- Session 1: Listen for notifications LISTEN my_channel; -- Session 2: Send a notification NOTIFY my_channel, 'Hello listeners!';
Output
Asynchronous notification "my_channel" with payload "Hello listeners!" received.
Common Pitfalls
Common mistakes when using LISTEN include:
- Not committing the transaction after
LISTEN, which can delay receiving notifications. - Expecting notifications to be received immediately without checking for them in the client application.
- Using
LISTENin a session that closes immediately, so it never waits for notifications.
Remember, LISTEN only registers the session to receive notifications; your client must actively check or wait for them.
sql
/* Wrong: LISTEN inside a transaction that is never committed */ BEGIN; LISTEN my_channel; -- No COMMIT here, notifications won't be received until commit /* Right: Commit after LISTEN */ BEGIN; LISTEN my_channel; COMMIT;
Quick Reference
| Command | Description |
|---|---|
| LISTEN channel_name; | Subscribe to notifications on a channel |
| NOTIFY channel_name, 'payload'; | Send a notification with optional payload |
| UNLISTEN channel_name; | Stop listening on a specific channel |
| UNLISTEN *; | Stop listening on all channels |
Key Takeaways
Use LISTEN to subscribe your session to notifications on a channel.
Send notifications with NOTIFY to alert listening sessions asynchronously.
Always commit the transaction after LISTEN to start receiving notifications.
Your client must actively check or wait for notifications to process them.
Use UNLISTEN to stop listening when notifications are no longer needed.