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
WHEN
clause.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
ENABLE
andDISABLE
commands, respectively.ENABLE TRIGGER my_trigger ON my_table;
For more information, please see the PostgreSQL documentation.
More of Postgresql
- How can I use PostgreSQL XOR to compare two values?
- How can I use PostgreSQL and ZFS snapshots together?
- How do I use PostgreSQL ZonedDateTime to store date and time information?
- How can Zalando use PostgreSQL to improve its software development?
- How can I troubleshoot zero damaged pages in PostgreSQL?
- How can I integrate PostgreSQL with Yii2?
- How can I use PostgreSQL with YAML?
- How do I install and configure PostgreSQL on a Windows machine?
- How do I use PostgreSQL's XMIN and XMAX features?
- How can I set a PostgreSQL interval to zero?
See more codes...