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 get a value from a PostgreSQL XML column?
- How can I use PostgreSQL XOR to compare two values?
- How can I troubleshoot zero damaged pages in PostgreSQL?
- How do I use PostgreSQL ZonedDateTime to store date and time information?
- How do I parse XML data using PostgreSQL?
- How do I set the PostgreSQL work_mem parameter?
- How can I set a PostgreSQL interval to zero?
- How can I use PostgreSQL's "zero if null" feature?
- How can I use PostgreSQL with YAML?
- How do I use PostgreSQL variables in my software development project?
See more codes...