Using pg_notify in PostgreSQL trigger function Using pg_notify in PostgreSQL trigger function database database

Using pg_notify in PostgreSQL trigger function


This might be to late to help but perhaps someone else will be able to use it. Using SELECT pg_notify('', ''); in the trigger causes the DB to respond with

ERROR: query has no destination for result dataSQL state: 42601Hint: If you want to discard the results of a SELECT, use PERFORM instead.

Changing the SELECT to PERFORM as the error say helps to resolve this issue and the notification gets delivered as expected. Perhaps this could have been the problem.

I have the same setup, and had the same problem.


It might be useful to someone out there. Sometimes you want to pass whole row to "observer" and then it might be a nice idea to serialise whole row into JSON. You can achieve this with help of row_to_json

-- Notify when record was inserted into 'prices' tableCREATE OR REPLACE FUNCTION notify_pricesinserted()  RETURNS trigger AS $$DECLAREBEGIN  PERFORM pg_notify(    CAST('pricesinserted' AS text),    row_to_json(NEW)::text);  RETURN NEW;END;$$ LANGUAGE plpgsql;CREATE TRIGGER notify_pricesinserted  AFTER INSERT ON prices  FOR EACH ROW  EXECUTE PROCEDURE notify_pricesinserted();


CREATE OR REPLACE FUNCTION notifyshipment() RETURNS trigger AS $$DECLAREBEGIN  PERFORM pg_notify(CAST('snc' AS text),CAST(NEW.id AS text)|| ' ' || CAST(NEW.tracking_number AS text));  RETURN NEW;END;$$ LANGUAGE plpgsql;CREATE TRIGGER shipmentnotify AFTER UPDATE ON shipments FOR EACH ROW EXECUTE PROCEDURE notifyshipment();