Triggers in PostgreSQL are database callback functions that automatically execute when a specified database event occurs, such as an `INSERT`, `UPDATE`, or `DELETE` operation. They are used to enforce business rules, validate input data, and maintain data integrity.
Usage
Triggers automate tasks and enforce rules at the database level, ensuring that specific operations occur in response to changes in the data. They consist of a trigger event, timing, and the associated function to be executed.
CREATETRIGGER trigger_name
{BEFORE|AFTER|INSTEADOF}{INSERT|UPDATE|DELETE}ON table_name
FOREACHROWEXECUTEFUNCTIONfunction_name();Mogelijk gemaakt door
In this syntax, `CREATE TRIGGER` defines a new trigger, specifying when it should fire (`BEFORE`, `AFTER`, or `INSTEAD OF` an event) and the function it should execute. `BEFORE` triggers are typically used to modify data before it is written to the database, `AFTER` triggers are used for actions that should occur once data is committed, and `INSTEAD OF` triggers are often used on views to perform the required modifications on underlying tables.
FOR EACH ROW indicates that the trigger function will execute once for each row affected by the triggering event. In contrast, FOR EACH STATEMENT could be used to execute the trigger function once per SQL statement, regardless of the number of rows affected.
NEW and OLD are special record variables within triggers: NEW contains the new row data for INSERT or UPDATE operations, and OLD contains the existing row data for UPDATE or DELETE operations.
Examples
1. Basic Insert Trigger
CREATEFUNCTIONlog_insert()RETURNSTRIGGERAS $$
BEGIN-- Log every insert operation into log_table
INSERTINTOlog_table(action, timestamp)VALUES('Insert',now());RETURNNEW;END;
$$ LANGUAGE plpgsql;CREATETRIGGER before_insert
BEFOREINSERTON main_table
FOREACHROWEXECUTEFUNCTIONlog_insert();Mogelijk gemaakt door
This example creates a trigger that logs every insert operation on the `main_table` into a `log_table`.
2. Update Trigger with Condition
CREATEFUNCTIONupdate_timestamp()RETURNSTRIGGERAS $$
BEGIN-- Update the updated_at timestamp field when a row is modified
NEW.updated_at :=now();RETURNNEW;END;
$$ LANGUAGE plpgsql;CREATETRIGGER update_time
BEFOREUPDATEON main_table
FOREACHROWWHEN(OLD.*ISDISTINCTFROMNEW.*)EXECUTEFUNCTIONupdate_timestamp();Mogelijk gemaakt door
This trigger updates the `updated_at` timestamp field in `main_table` whenever a row is modified.
3. Complex Trigger for Auditing
CREATEFUNCTIONaudit_changes()RETURNSTRIGGERAS $$
BEGINIF(TG_OP='DELETE')THEN-- Log DELETE operations into audit_log
INSERTINTOaudit_log(action, old_data, timestamp)VALUES('DELETE',OLD,now());ELSIF(TG_OP='UPDATE')THEN-- Log UPDATE operations with both old and newdataINSERTINTOaudit_log(action, old_data, new_data, timestamp)VALUES('UPDATE',OLD,NEW,now());ENDIF;RETURNNULL;END;
$$ LANGUAGE plpgsql;CREATETRIGGER audit_trigger
AFTERINSERTORUPDATEORDELETEON main_table
FOREACHROWEXECUTEFUNCTIONaudit_changes();Mogelijk gemaakt door
This trigger logs changes made to `main_table` into an `audit_log`, capturing both the old and new data for `UPDATE` operations.
Tips and Best Practices
Optimize for performance. Triggers can add overhead to database operations, so ensure they are efficient.
Use triggers sparingly. Avoid overusing triggers to prevent complexity and potential performance issues.
Ensure atomicity. Make sure that trigger functions are atomic and handle exceptions to maintain data integrity.
Test thoroughly. Rigorously test triggers in a development environment before deploying them in production to avoid unintended side effects.
Consider alternatives. Evaluate whether stored procedures or application logic might be better suited for certain operations to ensure clarity and maintainability.
Triggers in PostgreSQL are database callback functions that automatically execute when a specified database event occurs, such as an `INSERT`, `UPDATE`, or `DELETE` operation. They are used to enforce business rules, validate input data, and maintain data integrity.
Usage
Triggers automate tasks and enforce rules at the database level, ensuring that specific operations occur in response to changes in the data. They consist of a trigger event, timing, and the associated function to be executed.
In this syntax, `CREATE TRIGGER` defines a new trigger, specifying when it should fire (`BEFORE`, `AFTER`, or `INSTEAD OF` an event) and the function it should execute. `BEFORE` triggers are typically used to modify data before it is written to the database, `AFTER` triggers are used for actions that should occur once data is committed, and `INSTEAD OF` triggers are often used on views to perform the required modifications on underlying tables.
FOR EACH ROWindicates that the trigger function will execute once for each row affected by the triggering event. In contrast,FOR EACH STATEMENTcould be used to execute the trigger function once per SQL statement, regardless of the number of rows affected.NEWandOLDare special record variables within triggers:NEWcontains the new row data forINSERTorUPDATEoperations, andOLDcontains the existing row data forUPDATEorDELETEoperations.Examples
1. Basic Insert Trigger
This example creates a trigger that logs every insert operation on the `main_table` into a `log_table`.
2. Update Trigger with Condition
This trigger updates the `updated_at` timestamp field in `main_table` whenever a row is modified.
3. Complex Trigger for Auditing
This trigger logs changes made to `main_table` into an `audit_log`, capturing both the old and new data for `UPDATE` operations.
Tips and Best Practices