0
0
PostgreSQLquery~5 mins

LISTEN and NOTIFY for pub-sub in PostgreSQL

Choose your learning style9 modes available
Introduction

LISTEN and NOTIFY let different parts of a database talk to each other instantly. This helps programs react quickly when something changes.

You want to update a user interface right after data changes in the database.
You need to alert other parts of your app when a new order is placed.
You want to trigger background tasks after a database event happens.
You want to avoid constant checking for changes by using real-time notifications.
Syntax
PostgreSQL
LISTEN channel_name;

NOTIFY channel_name, 'optional_message';

LISTEN waits for notifications on a named channel.

NOTIFY sends a message to all listeners on that channel.

Examples
This command makes your session wait for notifications on the 'new_order' channel.
PostgreSQL
LISTEN new_order;
This sends a message 'Order #123 placed' to all sessions listening on 'new_order'.
PostgreSQL
NOTIFY new_order, 'Order #123 placed';
You can send a notification without a message. Listeners just know something happened.
PostgreSQL
NOTIFY new_order;
Sample Program

In one session, you run LISTEN to wait for messages on 'new_order'. In another session, you run NOTIFY to send a message. The first session immediately gets the message.

PostgreSQL
-- Open two database sessions.
-- Session 1: Listen for notifications
LISTEN new_order;

-- Session 2: Send a notification
NOTIFY new_order, 'Order #123 placed';

-- Back to Session 1, you will see a notification received message.
OutputSuccess
Important Notes

LISTEN and NOTIFY are asynchronous; your session must be actively waiting to receive notifications.

Notifications are lightweight and fast but not guaranteed to be delivered if the listener disconnects.

Use LISTEN and NOTIFY to reduce polling and improve real-time responsiveness in your apps.

Summary

LISTEN waits for messages on a channel.

NOTIFY sends messages to all listeners on that channel.

This helps different parts of your app communicate instantly through the database.