Triggers in PostgreSQL are database callback functions automatically invoked or executed in response to certain events on a particular table or view. They are used to enforce business rules, validate input data, and maintain data integrity.
Usage
Triggers are employed when you need to automatically execute a function in response to events such as `INSERT`, `UPDATE`, or `DELETE` operations on a table. They are defined to act before or after these events.
sql
CREATETRIGGER trigger_name
{BEFORE|AFTER|INSTEADOF}{ event [OR...]}ON table_name
[FOR[EACH]{ROW|STATEMENT}]EXECUTEPROCEDUREfunction_name(arguments);Didukung oleh
In this syntax, `CREATE TRIGGER` sets up a trigger called `trigger_name` that executes `function_name` when specified events occur on `table_name`.
Examples
1. Basic Insert Trigger
sql
CREATEORREPLACEFUNCTIONlog_insert()RETURNSTRIGGERAS $$
BEGININSERTINTOaudit_table(action, time)VALUES('INSERT',NOW());RETURNNEW;END;
$$ LANGUAGE plpgsql;CREATETRIGGER insert_audit
AFTERINSERTON my_table
FOREACHROWEXECUTEPROCEDURElog_insert();Didukung oleh
This trigger logs every insert operation on `my_table` by adding a record to `audit_table`.
2. Update Trigger with Conditional Logic
sql
CREATEORREPLACEFUNCTIONcheck_update()RETURNSTRIGGERAS $$
BEGINIFNEW.amount <0THENRAISEEXCEPTION'Amount cannot be negative';ENDIF;RETURNNEW;END;
$$ LANGUAGE plpgsql;CREATETRIGGER check_update_trigger
BEFOREUPDATEON transactions
FOREACHROWEXECUTEPROCEDUREcheck_update();Didukung oleh
This trigger verifies that the `amount` column in the `transactions` table is not negative before update operations.
3. Trigger for Cascading Deletes
sql
CREATEORREPLACEFUNCTIONcascade_delete()RETURNSTRIGGERAS $$
BEGINDELETEFROM child_table WHERE parent_id =OLD.id;RETURNOLD;END;
$$ LANGUAGE plpgsql;CREATETRIGGER cascading_delete_trigger
AFTERDELETEON parent_table
FOREACHROWEXECUTEPROCEDUREcascade_delete();Didukung oleh
This trigger ensures that when a row is deleted from `parent_table`, related rows in `child_table` are also removed.
Tips and Best Practices
Limit trigger logic. Keep trigger functions simple to minimize performance overhead and avoid complex business logic.
Use row-level triggers selectively. Opt for statement-level triggers when possible to reduce the number of executions. Row-level triggers are useful when operations need to be performed on each affected row, whereas statement-level triggers can reduce overhead by executing once per operation.
Be cautious with recursive triggers. Ensure that triggers do not unintentionally call themselves, leading to infinite loops.
Test thoroughly. Extensively test triggers in a development environment to assess their impact on performance.
Document triggers. Clearly document the purpose and logic of each trigger for future reference and maintenance.
Consider transaction boundaries. Be mindful of transaction boundaries to ensure triggers behave as expected in multi-statement transactions.
Monitor performance. Keep an eye on the performance impact of triggers in a live system and diagnose any issues using PostgreSQL's logging and monitoring tools.
Managing Triggers
To disable a trigger temporarily, use the `ALTER TABLE ... DISABLE TRIGGER` command.
To permanently remove a trigger, use the `DROP TRIGGER` command.
Triggers in PostgreSQL are database callback functions automatically invoked or executed in response to certain events on a particular table or view. They are used to enforce business rules, validate input data, and maintain data integrity.
Usage
Triggers are employed when you need to automatically execute a function in response to events such as `INSERT`, `UPDATE`, or `DELETE` operations on a table. They are defined to act before or after these events.
In this syntax, `CREATE TRIGGER` sets up a trigger called `trigger_name` that executes `function_name` when specified events occur on `table_name`.
Examples
1. Basic Insert Trigger
This trigger logs every insert operation on `my_table` by adding a record to `audit_table`.
2. Update Trigger with Conditional Logic
This trigger verifies that the `amount` column in the `transactions` table is not negative before update operations.
3. Trigger for Cascading Deletes
This trigger ensures that when a row is deleted from `parent_table`, related rows in `child_table` are also removed.
Tips and Best Practices
Managing Triggers