Triggers in PostgreSQL are special procedures that are automatically executed or triggered when certain events occur in a database table. They are used to maintain the integrity of the data, enforce business rules, and automate complex checks or transformations.
Usage
Triggers are employed to automatically respond to events such as `INSERT`, `UPDATE`, or `DELETE` operations on a table. They can be set to execute `BEFORE`, `AFTER`, or `INSTEAD OF` the event and can optionally be conditioned on whether the event succeeds. Triggers can be defined at the row level, executing for each affected row, or at the statement level, executing once per SQL statement.
CREATETRIGGER trigger_name
{BEFORE|AFTER|INSTEADOF}{INSERT|UPDATE|DELETE}ON table_name
FOREACH{ROW|STATEMENT}EXECUTEFUNCTIONfunction_name();Offerto da
In this syntax, `CREATE TRIGGER` defines a new trigger named `trigger_name` that calls a specified function `function_name` either before, after, or instead of a data-modifying event on `table_name`.
Triggers interact with transaction control commands like `COMMIT` and `ROLLBACK`. If a trigger causes an error, the entire transaction will typically be rolled back unless explicitly handled.
Examples
1. Basic Trigger for Auditing
CREATETABLEaudit_log(
id SERIALPRIMARYKEY,
operation VARCHAR(10),
operation_time TIMESTAMPDEFAULTCURRENT_TIMESTAMP);CREATEORREPLACEFUNCTIONlog_insert()RETURNSTRIGGERAS $$
BEGININSERTINTOaudit_log(operation)VALUES('INSERT');RETURNNEW;END;
$$ LANGUAGE plpgsql;CREATETRIGGER insert_audit
AFTERINSERTON target_table
FOREACHROWEXECUTEFUNCTIONlog_insert();Offerto da
This basic example logs every `INSERT` operation on `target_table` into the `audit_log` table.
2. Trigger with Conditional Logic
CREATEORREPLACEFUNCTIONcheck_salary()RETURNSTRIGGERAS $$
BEGINIFNEW.salary <OLD.salary THENRAISEEXCEPTION'Salary cannot be decreased!';ENDIF;RETURNNEW;END;
$$ LANGUAGE plpgsql;CREATETRIGGER salary_check
BEFOREUPDATEON employees
FOREACHROWEXECUTEFUNCTIONcheck_salary();Offerto da
This trigger ensures that an employee's salary cannot be decreased during an update operation.
3. Cascade Trigger
CREATEORREPLACEFUNCTIONdelete_cascade()RETURNSTRIGGERAS $$
BEGINDELETEFROM orders WHERE customer_id =OLD.id;RETURNOLD;END;
$$ LANGUAGE plpgsql;CREATETRIGGER cascade_delete
AFTERDELETEON customers
FOREACHROWEXECUTEFUNCTIONdelete_cascade();Offerto da
This example automatically deletes all orders associated with a customer when the customer is removed.
Managing Triggers
To disable or drop a trigger when it's no longer needed, you can use the following commands:
ALTERTABLE table_name DISABLETRIGGER trigger_name;DROPTRIGGER trigger_name ON table_name;Offerto da
To view existing triggers in a database, you can query the `pg_trigger` system catalog.
Tips and Best Practices
Keep triggers simple. Complex logic can lead to performance bottlenecks and maintenance challenges.
Test thoroughly. Ensure your triggers work as expected by testing them under various scenarios.
Document triggers. Clearly document the purpose and operation of each trigger to aid future developers.
Consider permissions. Ensure that users triggering the events have appropriate permissions to execute the associated functions.
Monitor performance impact. Be aware that extensive use of triggers may affect performance, especially on high-transaction tables.
Avoid recursive triggers. Recursive triggers can lead to infinite loops and should be handled with caution.
Triggers in PostgreSQL are special procedures that are automatically executed or triggered when certain events occur in a database table. They are used to maintain the integrity of the data, enforce business rules, and automate complex checks or transformations.
Usage
Triggers are employed to automatically respond to events such as `INSERT`, `UPDATE`, or `DELETE` operations on a table. They can be set to execute `BEFORE`, `AFTER`, or `INSTEAD OF` the event and can optionally be conditioned on whether the event succeeds. Triggers can be defined at the row level, executing for each affected row, or at the statement level, executing once per SQL statement.
In this syntax, `CREATE TRIGGER` defines a new trigger named `trigger_name` that calls a specified function `function_name` either before, after, or instead of a data-modifying event on `table_name`.
Triggers interact with transaction control commands like `COMMIT` and `ROLLBACK`. If a trigger causes an error, the entire transaction will typically be rolled back unless explicitly handled.
Examples
1. Basic Trigger for Auditing
This basic example logs every `INSERT` operation on `target_table` into the `audit_log` table.
2. Trigger with Conditional Logic
This trigger ensures that an employee's salary cannot be decreased during an update operation.
3. Cascade Trigger
This example automatically deletes all orders associated with a customer when the customer is removed.
Managing Triggers
To disable or drop a trigger when it's no longer needed, you can use the following commands:
To view existing triggers in a database, you can query the `pg_trigger` system catalog.
Tips and Best Practices