0
0
PostgresqlHow-ToBeginner · 3 min read

How to Use pg_notify in PostgreSQL for Notifications

Use pg_notify(channel, payload) in PostgreSQL to send a notification on a specified channel with an optional payload string. Other sessions can listen to this channel using LISTEN channel and receive notifications asynchronously.
📐

Syntax

The pg_notify function sends a notification to all sessions listening on a specified channel.

  • channel: The name of the notification channel (a string).
  • payload: An optional string message sent with the notification (max 8000 bytes).

Example syntax:

sql
SELECT pg_notify('channel_name', 'your message here');
💻

Example

This example shows how to send a notification and listen for it in two separate sessions.

Session 1 listens on the channel my_channel:

sql
-- Session 1: Listen for notifications
LISTEN my_channel;

-- Session 2: Send a notification
SELECT pg_notify('my_channel', 'Hello listeners!');
Output
Asynchronous notification "my_channel" with payload "Hello listeners!" received.
⚠️

Common Pitfalls

Common mistakes when using pg_notify include:

  • Not running LISTEN before expecting notifications.
  • Expecting immediate synchronous results; notifications are asynchronous.
  • Using channel names or payloads longer than allowed limits.
  • Not handling notifications in client applications properly.

Example of a wrong approach and the correct way:

sql
-- Wrong: Sending notification without any session listening
SELECT pg_notify('test_channel', 'No listeners yet');

-- Right: First listen, then send
LISTEN test_channel;
SELECT pg_notify('test_channel', 'Now listeners will get this');
📊

Quick Reference

CommandDescription
LISTEN channel_name;Start listening for notifications on the channel.
UNLISTEN channel_name;Stop listening on the channel.
SELECT pg_notify(channel, payload);Send a notification with optional payload.
NOTIFY channel, 'payload';SQL command equivalent to pg_notify.

Key Takeaways

Use pg_notify(channel, payload) to send asynchronous notifications in PostgreSQL.
Always run LISTEN channel in a session to receive notifications on that channel.
Notifications are asynchronous; your application must handle them properly.
Channel names and payloads must be strings and have size limits.
Use UNLISTEN to stop receiving notifications when no longer needed.