PostgreSQL triggers are database callback functions that automatically execute or "trigger" when a specified database event occurs, like an `INSERT`, `UPDATE`, `DELETE`, or `TRUNCATE`. These are used to maintain data integrity, enforce business rules, or perform logging and auditing.
Usage
Triggers are used when you need to automate tasks in response to changes in a table's data. They are particularly useful for maintaining consistency and implementing complex business logic at the database level.
sql
CREATETRIGGER trigger_name
{BEFORE|AFTER|INSTEADOF}{INSERT|UPDATE|DELETE|TRUNCATE}ON table_name
[FOREACHROW|FOREACHSTATEMENT]EXECUTEPROCEDUREfunction_name();Offerto da
In this syntax, `CREATE TRIGGER` defines a new trigger named `trigger_name`, specifying when it should fire (`BEFORE`, `AFTER`, or `INSTEAD OF`), which event should trigger it (`INSERT`, `UPDATE`, `DELETE`, or `TRUNCATE`), and the table it applies to (`ON table_name`). `EXECUTE PROCEDURE` calls the function that contains trigger logic.
Examples
1. Basic Trigger on Insert
sql
CREATEORREPLACEFUNCTIONlog_insert()RETURNSTRIGGERAS $$
BEGININSERTINTOlog_table(action, timestamp)VALUES('INSERT',NOW());RETURNNEW;END;
$$ LANGUAGE plpgsql;CREATETRIGGER insert_trigger
AFTERINSERTON main_table
FOREACHROWEXECUTEPROCEDURElog_insert();Offerto da
This example creates a trigger that logs an entry into `log_table` every time a new row is inserted into `main_table`.
2. Trigger to Enforce Business Rule
sql
CREATEORREPLACEFUNCTIONcheck_salary()RETURNSTRIGGERAS $$
BEGINIFNEW.salary <1000THENRAISEEXCEPTION'Salary cannot be less than 1000';ENDIF;RETURNNEW;END;
$$ LANGUAGE plpgsql;CREATETRIGGER salary_check
BEFOREINSERTORUPDATEON employees
FOREACHROWEXECUTEPROCEDUREcheck_salary();Offerto da
Here, a trigger ensures that the salary of any employee is not set below 1000, either on insertion or update.
3. Trigger for Audit Logging
sql
CREATEORREPLACEFUNCTIONaudit_changes()RETURNSTRIGGERAS $$
BEGINIFTG_OP='UPDATE'THENINSERTINTOaudit_log(table_name, operation, old_data, new_data, changed_at)VALUES(TG_TABLE_NAME,TG_OP,ROW(OLD.*),ROW(NEW.*),NOW());ENDIF;RETURNNEW;END;
$$ LANGUAGE plpgsql;CREATETRIGGER audit_trigger
AFTERUPDATEON any_table
FOREACHROWEXECUTEPROCEDUREaudit_changes();Offerto da
This example captures changes in `any_table` by logging both the old and new row data to an `audit_log` table after each update.
Managing Triggers
To disable a trigger:
sql
ALTERTABLE table_name DISABLETRIGGER trigger_name;Offerto da
To enable a trigger:
sql
ALTERTABLE table_name ENABLETRIGGER trigger_name;Offerto da
To delete a trigger:
sql
DROPTRIGGER trigger_name ON table_name;Offerto da
Tips and Best Practices
Keep triggers simple and efficient. Complex logic can slow down database operations. Be cautious of performance implications, especially in highly transactional environments.
Use triggers for critical constraints. Ensure that critical business rules are enforced at the database level.
Limit side effects. Triggers should avoid altering the database state in unexpected ways.
Document triggers. Maintain clear documentation for each trigger to help future developers understand its purpose.
Test thoroughly. Ensure triggers work as expected by testing with various scenarios and edge cases.
Be mindful of execution order. Understand the execution order when multiple triggers are defined for the same event on a table.
Handle recursive calls. Be aware of potential recursive trigger calls and implement safeguards where necessary.
PostgreSQL triggers are database callback functions that automatically execute or "trigger" when a specified database event occurs, like an `INSERT`, `UPDATE`, `DELETE`, or `TRUNCATE`. These are used to maintain data integrity, enforce business rules, or perform logging and auditing.
Usage
Triggers are used when you need to automate tasks in response to changes in a table's data. They are particularly useful for maintaining consistency and implementing complex business logic at the database level.
In this syntax, `CREATE TRIGGER` defines a new trigger named `trigger_name`, specifying when it should fire (`BEFORE`, `AFTER`, or `INSTEAD OF`), which event should trigger it (`INSERT`, `UPDATE`, `DELETE`, or `TRUNCATE`), and the table it applies to (`ON table_name`). `EXECUTE PROCEDURE` calls the function that contains trigger logic.
Examples
1. Basic Trigger on Insert
This example creates a trigger that logs an entry into `log_table` every time a new row is inserted into `main_table`.
2. Trigger to Enforce Business Rule
Here, a trigger ensures that the salary of any employee is not set below 1000, either on insertion or update.
3. Trigger for Audit Logging
This example captures changes in `any_table` by logging both the old and new row data to an `audit_log` table after each update.
Managing Triggers
To disable a trigger:
To enable a trigger:
To delete a trigger:
Tips and Best Practices