A database trigger is procedural code that the database server runs automatically in response to events on a table. As PostgreSQL’s documentation puts it, “CREATE TRIGGER creates a new trigger. The trigger will be associated with the specified table, view, or foreign table and will execute the specified function when certain operations are performed on that table.” The events that can fire a trigger are “one of INSERT, UPDATE, DELETE, or TRUNCATE.”
Triggers can be configured to run at different points relative to the operation. A trigger may “fire before the operation is attempted on a row (before constraints are checked and the INSERT, UPDATE, or DELETE is attempted); or after the operation has completed; or instead of the operation (in the case of inserts, updates or deletes on a view).” They can also run once per affected row, marked FOR EACH ROW, or once per statement regardless of how many rows change, marked FOR EACH STATEMENT.
Triggers are typically used to enforce rules that should hold no matter who writes the data, or to maintain derived values such as audit logs, denormalized totals, or last-modified timestamps. The cost is that this behavior is hidden: a simple INSERT or UPDATE may set off side effects that are not visible in the application code issuing it, which can make a system harder to reason about and debug.