---
title: "Triggers: CREATE, ALTER, DROP and RENAME TRIGGER"
description: "Define CoraDB triggers that run when rows are inserted, updated or deleted: timing, conditions, new and old rows, deferred triggers."
url: "https://www.coradb.ai/manual/sql/trigger.html"
markdown_url: "https://www.coradb.ai/manual/markdown/sql/trigger.md"
product: "CoraDB"
version: "1.0"
keywords: "coradb trigger, create trigger, alter trigger, drop trigger, rename trigger, before update, after insert, deferred trigger, correlation name, reject, trigger trace, trigger depth"
---

# 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

```sql
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 | DEFERRED
event_type   ::= INSERT | UPDATE | DELETE
               | STATEMENT INSERT | STATEMENT UPDATE | STATEMENT DELETE
               | COMMIT | ROLLBACK
event_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](https://www.coradb.ai/manual/sql/trigger.html#event-time). |
| *event_type*, *event_target* | Which event fires the trigger; see [Trigger event type](https://www.coradb.ai/manual/sql/trigger.html#trigger-event-type). |
| **IF** *condition* | The action runs only if the condition is true; see [Trigger condition](https://www.coradb.ai/manual/sql/trigger.html#trigger-condition). |
| **EXECUTE** … *action* | What to do; see [Trigger action](https://www.coradb.ai/manual/sql/trigger.html#trigger-action). |
| **COMMENT** | A description of the trigger. |

The following trigger rejects order lines with a quantity of zero or less:

```sql
CREATE TRIGGER trg_qty_check
BEFORE UPDATE ON order_items
IF new.quantity <= 0
EXECUTE REJECT;

UPDATE order_items SET quantity = 0 WHERE order_id = 2;
```

```text
ERROR: The operation has been rejected by trigger "trg_qty_check".
```


### 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](https://www.coradb.ai/manual/sql/trigger.html#limiting-nested-trigger).
- **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

| 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

- 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

- **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

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:

```sql
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_log
AFTER 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:

```sql
CREATE TRIGGER trg_orders_stmt
BEFORE STATEMENT UPDATE ON orders(shipped_date)
EXECUTE PRINT 'orders are being shipped';
```


### 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

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](https://www.coradb.ai/manual/sql/trigger.html#correlation-name) and can contain subqueries. Without a condition, the action always runs.

```sql
-- reject unusually large order lines
CREATE TRIGGER trg_big_order
BEFORE INSERT ON order_items
IF new.quantity > 50
EXECUTE REJECT;

-- check a rule across the whole table when the transaction commits
CREATE TRIGGER trg_commit_check
BEFORE COMMIT
IF 0 < (SELECT COUNT(*) FROM orders WHERE shipped_date < order_date)
EXECUTE REJECT;
```


### 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:

```sql
CREATE TRIGGER foo_trigger DEFERRED UPDATE ON order_items IF old.quantity = 100 EXECUTE PRINT 'foo_trigger';
```

```text
ERROR: Error compiling condition for "foo_trigger": Attribute "old" was not found.
```


### 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. |

```sql
-- the transaction cannot commit if it set an implausible shipping cost
CREATE TRIGGER trg_shipping_check
DEFERRED UPDATE ON orders
IF obj.shipping_cost > 1000
EXECUTE INVALIDATE TRANSACTION;
```

> **Warning:**
> - An **INSERT** action in a trigger on an **INSERT** event of the same table fires the trigger again and can loop.
> - **UPDATE** triggers on partitioned tables must not change the partitioning key in a way that breaks the partitioning; CoraDB raises an error for such updates.



### Trigger's COMMENT

A comment is given with **COMMENT** in **CREATE TRIGGER** or **ALTER TRIGGER**. Comments are shown in the catalog views [db_trigger](https://www.coradb.ai/manual/sql/catalog_classes.html#db_trigger) and [db_trig](https://www.coradb.ai/manual/sql/catalog_views.html#db_trig):

```sql
SELECT trigger_name, target_class_name, target_attr_name, target_attr_type, comment
FROM 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

**ALTER TRIGGER** changes the status, priority or comment of a trigger. To change its event, condition or action, drop and re-create it.

```sql
ALTER TRIGGER trigger_name { STATUS { ACTIVE | INACTIVE } | PRIORITY key } [ COMMENT 'comment' ];
ALTER TRIGGER trigger_name COMMENT 'comment';
```

```sql
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

```sql
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

```sql
RENAME TRIGGER old_name AS new_name;
```

```sql
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

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:

```sql
EXECUTE DEFERRED TRIGGER { trigger_name | ALL TRIGGERS };   -- run now
DROP DEFERRED TRIGGER { trigger_name | ALL TRIGGERS };      -- cancel
```


### 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

**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:

```sql
INSERT INTO coupon VALUES ('SPRING', 0) ON DUPLICATE KEY UPDATE uses = uses + 1;   -- before update, after update
REPLACE INTO coupon VALUES ('SPRING', 5);    -- before delete, after delete, before insert, after insert
REPLACE INTO coupon VALUES ('SUMMER', 0);    -- before insert, after insert
```


## 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:

```sql
CREATE TABLE countdown (id INT PRIMARY KEY, n INT);
INSERT INTO countdown VALUES (1, 0);

CREATE TRIGGER loop_tgr
BEFORE UPDATE ON countdown(n)
IF new.n > 0
EXECUTE UPDATE countdown SET n = new.n - 1 WHERE id = obj.id;
```


### 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:

```sql
SET TRIGGER TRACE { ON | OFF };
```


### 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.

```sql
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:

```sql
GET TRIGGER TRACE [ INTO :variable ];               -- 1 if trace is on, 0 if off
GET TRIGGER [ MAXIMUM ] DEPTH [ INTO :variable ];   -- current depth limit
```

Setting `n` to 15 would fire `loop_tgr` 16 times, more than a depth of 10 allows:

```sql
SET TRIGGER MAXIMUM DEPTH 10;
UPDATE countdown SET n = 15 WHERE id = 1;
```

```text
ERROR: Error evaluating action for "loop_tgr", Maximum trigger depth 10 exceeded at trigger "loop_tgr".
```
