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 do I use the PostgreSQL hash function?
- How can I use PostgreSQL with YAML?
- How do I use PostgreSQL's XMIN and XMAX features?
- How can I set a PostgreSQL interval to zero?
- How can Zalando use PostgreSQL to improve its software development?
- How can I troubleshoot zero damaged pages in PostgreSQL?
- How do I use PostgreSQL ZonedDateTime to store date and time information?
- How can I extract the year from a PostgreSQL timestamp?
- How can I extract the year from a date in PostgreSQL?
- How can I retrieve data from PostgreSQL for yesterday's date?
See more codes...