postgresqlHow do I create a PostgreSQL trigger?
Creating a trigger in PostgreSQL requires a few steps:
-
Create a function to execute when the trigger is fired. This function should accept the same parameters as the trigger.
CREATE FUNCTION my_trigger_function() RETURNS trigger AS $$ BEGIN -- Your code goes here END; $$ LANGUAGE plpgsql; -
Create the trigger itself, specifying the table and event it should fire on, as well as the function to execute.
CREATE TRIGGER my_trigger AFTER INSERT ON my_table FOR EACH ROW EXECUTE PROCEDURE my_trigger_function(); -
Optionally, you can specify the timing of the trigger (BEFORE or AFTER) and the type of event (INSERT, UPDATE, or DELETE).
-
Optionally, you can also specify the conditions under which the trigger should fire using a
WHENclause.CREATE TRIGGER my_trigger AFTER INSERT ON my_table FOR EACH ROW WHEN (NEW.status = 'active') EXECUTE PROCEDURE my_trigger_function(); -
Finally, you can enable and disable the trigger using the
ENABLEandDISABLEcommands, respectively.ENABLE TRIGGER my_trigger ON my_table;
For more information, please see the PostgreSQL documentation.
More of Postgresql
- How can I troubleshoot zero damaged pages in PostgreSQL?
- How do I use PostgreSQL's XMIN and XMAX features?
- How can I monitor PostgreSQL performance using Zabbix?
- How can I integrate PostgreSQL with Yii2?
- How can I use PostgreSQL with YAML?
- How do I use PostgreSQL's XMLTABLE to parse XML data?
- How do I use PostgreSQL UNION to combine the results of two queries?
- How do I decide whether to use PostgreSQL VARCHAR or TEXT data types?
- How do I use PostgreSQL with Qt?
- How can I retrieve data from PostgreSQL for yesterday's date?
See more codes...