How to Use NOTIFY in PostgreSQL for Event Notifications
In PostgreSQL, use the
NOTIFY command to send a notification event with a channel name and optional payload. Other sessions can listen for these events using LISTEN, enabling asynchronous communication between database clients.Syntax
The NOTIFY command sends a notification to all clients listening on a specified channel. It has this form:
NOTIFY channel;— sends a notification without a payload.NOTIFY channel, 'payload';— sends a notification with a text payload.
The channel is a name identifying the notification topic, and the optional payload is a string message.
sql
NOTIFY channel_name;
NOTIFY channel_name, 'your message here';Example
This example shows how one session sends a notification and another session listens for it.
First, start listening on a channel:
sql
-- Session 1: Listen for notifications LISTEN my_channel; -- Session 2: Send a notification NOTIFY my_channel, 'Hello listeners!';
Output
LISTEN
NOTIFY
Common Pitfalls
- For
NOTIFYto work, the listening session must have executedLISTENon the same channel beforehand. - Notifications are asynchronous; the sender does not wait for receivers to process the message.
- Payloads are limited to 8000 bytes; larger messages will be truncated.
- Notifications are not persistent; if no session is listening, the notification is lost.
sql
/* Wrong: Sending notification without listener active */ NOTIFY my_channel, 'Test message'; /* Right: First listen, then notify */ -- In one session: LISTEN my_channel; -- In another session: NOTIFY my_channel, 'Test message';
Quick Reference
| Command | Description |
|---|---|
| LISTEN channel_name; | Start listening for notifications on a channel |
| NOTIFY channel_name; | Send a notification without payload |
| NOTIFY channel_name, 'payload'; | Send a notification with a text payload |
| UNLISTEN channel_name; | Stop listening on a specific channel |
| UNLISTEN *; | Stop listening on all channels |
Key Takeaways
Use LISTEN to subscribe to a notification channel before sending NOTIFY.
NOTIFY sends asynchronous messages that listeners can react to in real time.
Payloads in NOTIFY are optional and limited in size to 8000 bytes.
Notifications are lost if no session is listening on the channel.
Use UNLISTEN to stop receiving notifications when no longer needed.