# Triggers

Source: https://cubibase.com/docs/database/triggers

Also available: [Markdown version](https://cubibase.com/docs/database/triggers.md) · [llms.txt](https://cubibase.com/llms.txt) · [full site content](https://cubibase.com/llms-full.txt)

Execute a function automatically when rows change. Triggers fire on INSERT, UPDATE, DELETE, or TRUNCATE, before or after the event, per row or per statement.

## The shape of a trigger

| Choice | Values | Notes |
| --- | --- | --- |
| Timing | `BEFORE`, `AFTER` | BEFORE can modify the row being written; AFTER sees the final state |
| Events | `INSERT`, `UPDATE`, `DELETE`, `TRUNCATE` | Combine several events in one trigger |
| Level | `ROW`, `STATEMENT` | ROW fires per affected row; STATEMENT once per query |
| Update of | column list | Fire only when specific columns are updated |
| WHEN | boolean expression | A row-level condition, e.g. `NEW.plan <> OLD.plan` |
| Function | a public trigger function | Must return `trigger` |

- TRUNCATE triggers must be FOR EACH STATEMENT — there are no rows to iterate.
- WHEN conditions require FOR EACH ROW.
- INSTEAD OF triggers apply to views and are not offered on tables.

## The trigger function

A trigger calls a function that returns `trigger`. Create it on the Functions screen (there is a trigger template), then pick it here. Inside the body, `NEW` is the row being written and `OLD` the row being replaced or removed.

**Example · stamp updated_at on every update**

```sql
CREATE FUNCTION public.set_updated_at()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
  NEW.updated_at := now();
  RETURN NEW;
END;
$$;
```

**SQL · what the Console creates**

```sql
CREATE TRIGGER customers_set_updated_at
BEFORE UPDATE ON public.customers
FOR EACH ROW
EXECUTE FUNCTION public.set_updated_at();
```

> **tip**: A BEFORE INSERT trigger can fill server-side fields — return NEW with the fields set and every writer gets them, including the Data API.

## Enabling, disabling, dropping

- The Triggers screen groups triggers by table and shows timing, events, level, function, and enabled state.
- Disabling a trigger keeps its definition but stops it firing — useful while backfilling data.
- Dropping the trigger does not drop the function; other triggers may still use it.
- Triggers run inside the writing transaction: if the function raises, the whole write is rolled back.

> **warning**: Trigger functions run with the privileges of the writing role and are not stopped by RLS on other tables they touch. Keep trigger bodies small and reviewed.

## Additional resources

- [Functions](https://cubibase.com/docs/database/functions) Where trigger functions are written and replaced.
- [Tables and columns](https://cubibase.com/docs/database/tables) The tables triggers attach to.
- [Writing rows](https://cubibase.com/docs/data-api/writing) The writes that fire your triggers.
