Triggers: CREATE, ALTER, DROP and RENAME TRIGGER
A trigger is a database object that performs an action automatically when a given event happens: a row of a table is inserted, updated or deleted, or a transaction commits or rolls back. Triggers can enforce rules, reject invalid changes and keep audit logs.
Triggers can be defined on ordinary tables. Vertex and edge tables of a graph do not support triggers (Graph class error. TRIGGER is not allowed with graph class.); in the e-commerce sample database the examples therefore use the relational tables orders and order_items.
CREATE TRIGGER
Section titled “CREATE TRIGGER”CREATE TRIGGER trigger_name[ STATUS { ACTIVE | INACTIVE } ][ PRIORITY key ]event_time event_type [ event_target ][ IF condition ]EXECUTE [ AFTER | DEFERRED ] action[ COMMENT 'comment' ];
event_time ::= BEFORE | AFTER | DEFERREDevent_type ::= INSERT | UPDATE | DELETE | STATEMENT INSERT | STATEMENT UPDATE | STATEMENT DELETE | COMMIT | ROLLBACKevent_target ::= ON table_name [ ( column_name ) ]action ::= REJECT | INVALIDATE TRANSACTION | PRINT 'message' | INSERT statement | UPDATE statement | DELETE statement| Part | Meaning |
|---|---|
| STATUS | ACTIVE (default) or INACTIVE; an inactive trigger does not run. |
| PRIORITY | A non-negative number, default 0; when several triggers fire for the same event, those with higher priority run first. Give triggers on the same event distinct priorities so that their order is defined. |
| event_time | When the condition and action run; see Event time. |
| event_type, event_target | Which event fires the trigger; see Trigger event type. |
| IF condition | The action runs only if the condition is true; see Trigger condition. |
| EXECUTE … action | What to do; see Trigger action. |
| COMMENT | A description of the trigger. |
The following trigger rejects order lines with a quantity of zero or less:
CREATE TRIGGER trg_qty_checkBEFORE UPDATE ON order_itemsIF new.quantity <= 0EXECUTE REJECT;
UPDATE order_items SET quantity = 0 WHERE order_id = 2;ERROR: The operation has been rejected by trigger "trg_qty_check".Guidelines for trigger definition
Section titled “Guidelines for trigger definition”Triggers are powerful but run implicitly, so design them carefully:
- Side effects. Conditions and actions should do only what is expected; avoid calling methods with side effects in conditions.
- Changing the target table. An action that changes the table the trigger is defined on can fire the same trigger again and loop. Make sure the recursion ends, and limit it with SET TRIGGER MAXIMUM DEPTH.
- Recursion between triggers. If trigger A fires trigger B, which fires A again, the transaction can loop until the depth limit stops it.
- Overhead. If the logic can be expressed more efficiently in the application or in a constraint, do so.
- Uniqueness. Do not define two triggers for the same event that contradict each other, and set PRIORITY where the order matters.
Event time
Section titled “Event time”| Event time | Condition and action run |
|---|---|
| BEFORE | Before the event is processed |
| AFTER | After the event is processed |
| DEFERRED | At the end of the transaction (cannot be used with COMMIT or ROLLBACK events) |
The action can also be delayed separately: EXECUTE AFTER action or EXECUTE DEFERRED action evaluates the condition at the event time but runs the action later.
Trigger type
Section titled “Trigger type”- A table trigger has a table as its event target and fires on instance or statement events. It is visible to all users who have SELECT permission on the table.
- A user trigger has no target and fires on COMMIT or ROLLBACK. It belongs to the user who created it and fires only for that user's transactions.
Trigger event type
Section titled “Trigger event type”- Instance events fire once for every row affected: INSERT, UPDATE, DELETE.
- Statement events fire once per statement, however many rows it affects: STATEMENT INSERT, STATEMENT UPDATE, STATEMENT DELETE.
- COMMIT and ROLLBACK fire when the transaction ends; they have no target.
Instance and statement events need an event target; COMMIT and ROLLBACK cannot have one.
Trigger event target
Section titled “Trigger event target”The target is a table, optionally with one column. With a column, an UPDATE trigger fires only when that column is updated.
The following trigger keeps a log of quantity changes, one row for each changed order line:
CREATE TABLE qty_log (order_id INT, product_id INT, old_qty SHORT, new_qty SHORT, changed_at DATETIME);
CREATE TRIGGER trg_order_items_qty_logAFTER UPDATE ON order_items(quantity)EXECUTE INSERT INTO qty_log VALUES (obj.order_id, obj.product_id, old.quantity, obj.quantity, SYS_DATETIME)COMMENT 'audit quantity changes';
UPDATE order_items SET quantity = quantity + 1 WHERE order_id = 1;SELECT order_id, product_id, old_qty, new_qty FROM qty_log;| order_id | product_id | old_qty | new_qty |
|---|---|---|---|
| 1 | 1137 | 2 | 3 |
A statement trigger fires once, before the first row is changed:
CREATE TRIGGER trg_orders_stmtBEFORE STATEMENT UPDATE ON orders(shipped_date)EXECUTE PRINT 'orders are being shipped';Combination of event type and target
Section titled “Combination of event type and target”| Event type | Target | Fires when |
|---|---|---|
| INSERT, STATEMENT INSERT | Table | Rows are inserted into the table |
| UPDATE, STATEMENT UPDATE | Table or column | Rows (or the column) of the table are updated |
| DELETE, STATEMENT DELETE | Table | Rows are deleted from the table |
| COMMIT | none | The transaction commits |
| ROLLBACK | none | The transaction rolls back |
Trigger condition
Section titled “Trigger condition”The condition is an expression that is true or false, using the operators allowed in a WHERE clause. It can refer to the affected row through correlation names and can contain subqueries. Without a condition, the action always runs.
-- reject unusually large order linesCREATE TRIGGER trg_big_orderBEFORE INSERT ON order_itemsIF new.quantity > 50EXECUTE REJECT;
-- check a rule across the whole table when the transaction commitsCREATE TRIGGER trg_commit_checkBEFORE COMMITIF 0 < (SELECT COUNT(*) FROM orders WHERE shipped_date < order_date)EXECUTE REJECT;Correlation name
Section titled “Correlation name”In instance triggers on INSERT, UPDATE and DELETE, the condition and action can refer to the affected row through correlation names:
| Name | Refers to |
|---|---|
| obj | The row as it is now: before an update or delete, or after an insert or update |
| new | The values proposed by an insert or update, before they are applied |
| old | The values before an update, while the trigger runs |
Which names are available depends on the event and the event time:
| Event | BEFORE | AFTER or DEFERRED |
|---|---|---|
| INSERT | new | obj |
| UPDATE | obj, new | obj, and old (AFTER only) |
| DELETE | obj | — |
Using a name that is not available is an error, for example old in a DEFERRED UPDATE trigger:
CREATE TRIGGER foo_trigger DEFERRED UPDATE ON order_items IF old.quantity = 100 EXECUTE PRINT 'foo_trigger';ERROR: Error compiling condition for "foo_trigger": Attribute "old" was not found.Trigger action
Section titled “Trigger action”| Action | Effect |
|---|---|
| REJECT | Cancels the operation that fired the trigger. Only with BEFORE, because afterwards the change has been made. |
| INVALIDATE TRANSACTION | Lets the operation complete but prevents the transaction from committing; it must be rolled back. Used with DEFERRED triggers to check a transaction as a whole. |
| PRINT 'message' | Prints a message to the client console (for development and testing); the operation is not affected. |
| INSERT, UPDATE, DELETE | Runs the statement, which can use the correlation names. |
-- the transaction cannot commit if it set an implausible shipping costCREATE TRIGGER trg_shipping_checkDEFERRED UPDATE ON ordersIF obj.shipping_cost > 1000EXECUTE INVALIDATE TRANSACTION;Trigger's COMMENT
Section titled “Trigger's COMMENT”A comment is given with COMMENT in CREATE TRIGGER or ALTER TRIGGER. Comments are shown in the catalog views db_trigger and db_trig:
SELECT trigger_name, target_class_name, target_attr_name, target_attr_type, commentFROM db_trig WHERE trigger_name LIKE 'trg_order%';| trigger_name | target_class_name | target_attr_name | target_attr_type | comment |
|---|---|---|---|---|
| trg_order_items_qty_log | order_items | quantity | INSTANCE | Audit quantity changes |
In corasql, ;schema order_items also lists the triggers of the table.
ALTER TRIGGER
Section titled “ALTER TRIGGER”ALTER TRIGGER changes the status, priority or comment of a trigger. To change its event, condition or action, drop and re-create it.
ALTER TRIGGER trigger_name { STATUS { ACTIVE | INACTIVE } | PRIORITY key } [ COMMENT 'comment' ];ALTER TRIGGER trigger_name COMMENT 'comment';ALTER TRIGGER trg_qty_check STATUS INACTIVE;ALTER TRIGGER trg_qty_check PRIORITY 0.7;ALTER TRIGGER trg_order_items_qty_log COMMENT 'audit order line quantity changes';- Only one of STATUS and PRIORITY can be changed per statement.
- A table trigger can be changed by its owner or by a user with ALTER permission on the table; a user trigger only by its owner.
DROP TRIGGER
Section titled “DROP TRIGGER”DROP TRIGGER trigger_name;One trigger is dropped per statement. A table trigger can be dropped by a user with ALTER permission on the table; a user trigger (COMMIT or ROLLBACK) is visible to and can be dropped by its owner only.
RENAME TRIGGER
Section titled “RENAME TRIGGER”RENAME TRIGGER old_name AS new_name;RENAME TRIGGER trg_qty_check AS trg_order_items_qty_check;Trigger names must be unique among triggers; a trigger can have the same name as a table. The rules for renaming are the same as for ALTER TRIGGER.
Deferred condition and action
Section titled “Deferred condition and action”A trigger with DEFERRED as event time, or with EXECUTE DEFERRED, runs at the end of the transaction. Pending deferred triggers can be run earlier or cancelled:
EXECUTE DEFERRED TRIGGER { trigger_name | ALL TRIGGERS }; -- run nowDROP DEFERRED TRIGGER { trigger_name | ALL TRIGGERS }; -- cancelGranting trigger authorization
Section titled “Granting trigger authorization”Permissions on triggers are not granted directly. A table trigger is available to every user who has permission on its table. Defining a table trigger requires ALTER permission on the table; a user trigger can be defined by any user.
Trigger on REPLACE and INSERT ... ON DUPLICATE KEY UPDATE
Section titled “Trigger on REPLACE and INSERT ... ON DUPLICATE KEY UPDATE”REPLACE and INSERT … ON DUPLICATE KEY UPDATE perform inserts, updates and deletes internally, and fire the corresponding triggers:
| Statement and situation | Triggers fired, in order |
|---|---|
| INSERT … ON DUPLICATE KEY UPDATE, key exists | BEFORE UPDATE, AFTER UPDATE |
| REPLACE, key exists (row is deleted and inserted again) | BEFORE DELETE, AFTER DELETE, BEFORE INSERT, AFTER INSERT |
| Either statement, key does not exist | BEFORE INSERT, AFTER INSERT |
With a trigger for each of these six events on a table coupon (code VARCHAR(16) UNIQUE, uses INT) that contains 'SPRING', each trigger writing its name to a log table:
INSERT INTO coupon VALUES ('SPRING', 0) ON DUPLICATE KEY UPDATE uses = uses + 1; -- before update, after updateREPLACE INTO coupon VALUES ('SPRING', 5); -- before delete, after delete, before insert, after insertREPLACE INTO coupon VALUES ('SUMMER', 0); -- before insert, after insertTrigger debugging
Section titled “Trigger debugging”Check that a new trigger works as intended. A trigger that makes statements much slower may be doing too much work or looping. The following trigger is deliberately recursive: it counts n down by updating its own row:
CREATE TABLE countdown (id INT PRIMARY KEY, n INT);INSERT INTO countdown VALUES (1, 0);
CREATE TRIGGER loop_tgrBEFORE UPDATE ON countdown(n)IF new.n > 0EXECUTE UPDATE countdown SET n = new.n - 1 WHERE id = obj.id;Viewing trigger execution log
Section titled “Viewing trigger execution log”SET TRIGGER TRACE prints a line on the client console each time a trigger condition is evaluated or an action runs, until it is turned off or the session ends:
SET TRIGGER TRACE { ON | OFF };Limiting nested trigger
Section titled “Limiting nested trigger”SET TRIGGER MAXIMUM DEPTH limits how deeply triggers can fire other triggers (or themselves). When the limit is reached, the statement fails and the transaction must be rolled back.
SET TRIGGER [ MAXIMUM ] DEPTH count;The default and highest allowed depth is 32 (SET TRIGGER DEPTH 33 fails with Maximum trigger depth cannot exceed 32.). Both settings apply to the current session.
GET TRIGGER reads the current settings, optionally into a session variable:
GET TRIGGER TRACE [ INTO :variable ]; -- 1 if trace is on, 0 if offGET TRIGGER [ MAXIMUM ] DEPTH [ INTO :variable ]; -- current depth limitSetting n to 15 would fire loop_tgr 16 times, more than a depth of 10 allows:
SET TRIGGER MAXIMUM DEPTH 10;UPDATE countdown SET n = 15 WHERE id = 1;ERROR: Error evaluating action for "loop_tgr", Maximum trigger depth 10 exceeded at trigger "loop_tgr".