Skip to content
Home » Cloudflare D1 SQL Docs » D1 Triggers

D1 Triggers

Triggers, are SQL actions fired automatically when a data change occurs. Cloudflare D1 offers a good support for triggers that fire on INSERT, DELETE and UPDATE events. In this page, we will discuss how to use triggers with D1.

Basis of D1 triggers
INSERT triggers
UPDATE triggers
DELETE triggers
Triggers that fire on column change
Triggers that fire on specific event only
Rising errors

Basis of D1 triggers

The base syntax of a Cloudflare D1 trigger is:

CREATE TRIGGER [IF NOT EXISTS] <trigger name> <BEFORE | AFTER | INSTEAD OF> <INSERT | UPDATE | DELETE> ON <table name> 
BEGIN
 .. your SQL action code here
END;

Example (a trigger that increments with one the column customers_count of table marketing_stats upon insertion of a new customer record):

CREATE TRIGGER tr_customers BEFORE INSERT ON customers
BEGIN
  UPDATE marketing_stats SET customers_count = customers_count + 1;
END;

INSERT triggers