31. Triggers: statements that run by themselves

Tell the database to do something every time a row is added, changed or deleted: keep a log, keep stock right, refuse what breaks a rule.

What a trigger is

Some work has to happen every time something else happens. Every time a price changes, write down the old price and the new one. Every time an order line is added, take the goods out of stock. If every program that changes the data has to remember this, sooner or later one of them forgets.

A trigger is a set of statements kept in the database that runs by itself when a row of a table is added (INSERT), changed (UPDATE) or deleted (DELETE). Nobody has to remember to run it; the database does it, whoever made the change.

Let's keep a log of price changes. First, a table for the log. changed_at fills itself in with the time (CURRENT_TIMESTAMP, in UTC); the examples leave it out because it is different every time you run them:

CREATE TABLE price_log (
  id         INTEGER PRIMARY KEY,
  product_id INTEGER NOT NULL,
  old_price  REAL,
  new_price  REAL,
  changed_at TEXT DEFAULT CURRENT_TIMESTAMP
);
✓ Done

Now the trigger. It reads almost as a sentence: "create a trigger named product_price_log, which runs after each row of product is updated, and does this, from BEGIN to END":

CREATE TRIGGER product_price_log
AFTER UPDATE ON product
BEGIN
  INSERT INTO price_log (product_id, old_price, new_price)
  VALUES (OLD.id, OLD.price, NEW.price);
END;
✓ Done

Change Coffee's price and look in the log. We didn't write to price_log ourselves:

UPDATE product SET price = 60 WHERE id = 1;
SELECT id, product_id, old_price, new_price FROM price_log;
idproduct_idold_pricenew_price
1155.060.0
1 row

The trigger wrote it: product 1 went from 55 to 60.

NEW and OLD

Inside a trigger, NEW is the row as it is after the change, and OLD the row as it was before. NEW.price is the new price, OLD.price the old one. Which of the two there is depends on the kind of trigger:

Trigger onOLDNEW
INSERTnone (the row wasn't there)the row added
UPDATEthe row beforethe row after
DELETEthe row deletednone (the row is gone)

A trigger runs once for each row the statement touches. Watch what our log does with a statement that changes 3 rows, and not even their price:

UPDATE product SET stock = stock + 10 WHERE category_id = 4;
SELECT id, product_id, old_price, new_price FROM price_log;
idproduct_idold_pricenew_price
1155.060.0
21030.030.0
31115.015.0
41225.025.0
4 rows

3 new rows in the log, one for each stationery product, each with the same old and new price. The trigger runs on any update of product, even one that only changed stock. The log is filling up with noise.

UPDATE OF and WHEN: run only when it matters

Two things narrow a trigger down:

There is no way to change a trigger, so we drop it (DROP TRIGGER), empty the log, and make it again, better:

DROP TRIGGER product_price_log;
DELETE FROM price_log;

CREATE TRIGGER product_price_log
AFTER UPDATE OF price ON product
WHEN OLD.price <> NEW.price
BEGIN
  INSERT INTO price_log (product_id, old_price, new_price)
  VALUES (OLD.id, OLD.price, NEW.price);
END;
✓ Done

Now three updates: one of stock only, one that sets Coffee's price to what it already is (60), and a 10% rise for the bakery:

UPDATE product SET stock = stock - 10 WHERE category_id = 4;
UPDATE product SET price = 60 WHERE id = 1;
UPDATE product SET price = price * 1.1 WHERE category_id = 2;
SELECT id, product_id, old_price, new_price FROM price_log;
idproduct_idold_pricenew_price
1435.038.5
2560.066.0
36120.0132.0
3 rows

Only the 3 bakery products are logged: Croissant 35 to 38.5, Banana Bread 60 to 66, Cheesecake 120 to 132. The stock update didn't set price, so UPDATE OF price let it pass; Coffee's price didn't really change, so WHEN let it pass.

Keeping stock right: AFTER INSERT

When an order line goes into order_item, that many goods leave the shelf. A trigger can do this every time:

CREATE TRIGGER order_item_take_stock
AFTER INSERT ON order_item
BEGIN
  UPDATE product SET stock = stock - NEW.qty WHERE id = NEW.product_id;
END;
✓ Done

NEW.qty and NEW.product_id are from the order line just added. Cheesecake and Pen before:

SELECT id, name, stock FROM product WHERE id IN (6, 11);
idnamestock
6Cheesecake8
11Pen300
2 rows

Customer 10 orders 2 cheesecakes and 5 pens:

INSERT INTO orders (id, customer_id, ordered, status) VALUES (16, 10, '2026-12-01', 'paid');
INSERT INTO order_item (order_id, product_id, qty, price) VALUES (16, 6, 2, 120), (16, 11, 5, 15);
SELECT id, name, stock FROM product WHERE id IN (6, 11);
idnamestock
6Cheesecake6
11Pen295
2 rows

Cheesecake went from 8 to 6, Pen from 300 to 295. The trigger ran twice, once for each line.

Refusing what breaks a rule: RAISE(ABORT)

A BEFORE trigger runs before the row goes in, so it can stop it. RAISE(ABORT, 'message') stops the statement with that error message and undoes everything the statement had done so far. Here: an order line may not ask for more than is in stock:

CREATE TRIGGER order_item_check_stock
BEFORE INSERT ON order_item
WHEN (SELECT stock FROM product WHERE id = NEW.product_id) < NEW.qty
BEGIN
  SELECT RAISE(ABORT, 'not enough stock');
END;
✓ Done

RAISE is written inside a SELECT, that's simply how it is called. Now add two more lines to order 16: 1 notebook, which is fine, and 20 cheesecakes, of which there are only 6:

INSERT INTO order_item (order_id, product_id, qty, price) VALUES (16, 10, 1, 30), (16, 6, 20, 120);
Error: not enough stock

The error message is the one we wrote. And the notebook line, which had gone in fine, and the stock its trigger took? Look:

SELECT id, name, stock FROM product WHERE id IN (6, 10);
SELECT * FROM order_item WHERE order_id = 16;
idnamestock
6Cheesecake6
10Notebook75
2 rows
order_idproduct_idqtyprice
1662120.0
1611515.0
2 rows

Notebook's stock is still 75 and order 16 still has its 2 lines. ABORT undid the whole statement, the first row and what its trigger did included: either the whole statement happens, or none of it.

Before writing a trigger to enforce a rule, see whether a plain constraint can do it (chapter 21): CHECK (price > 0) is shorter, clearer and can't be forgotten. Triggers are for rules a constraint can't express, like this one, which has to look at another table.

INSTEAD OF: making a view writable

In chapter 30 we saw that a view can't be changed directly. An INSTEAD OF trigger tells the database what to do instead: when someone updates the view, run these statements on the real tables. Make customer_public again (the view without phone numbers) with a trigger for UPDATE and one for INSERT:

CREATE VIEW customer_public AS
SELECT id, name, city FROM customer;

CREATE TRIGGER customer_public_update
INSTEAD OF UPDATE ON customer_public
BEGIN
  UPDATE customer SET name = NEW.name, city = NEW.city WHERE id = OLD.id;
END;

CREATE TRIGGER customer_public_insert
INSTEAD OF INSERT ON customer_public
BEGIN
  INSERT INTO customer (id, name, city, joined) VALUES (NEW.id, NEW.name, NEW.city, '2026-12-01');
END;
✓ Done

Now the view takes UPDATE and INSERT. RETURNING (chapter 18) shows the rows that went through the view:

UPDATE customer_public SET city = 'Phuket' WHERE id = 3 RETURNING id, name, city;
INSERT INTO customer_public (id, name, city) VALUES (11, 'Dao Rungroj', 'Trang') RETURNING id, name, city;
SELECT * FROM customer WHERE id IN (3, 11);
idnamecity
3Anan WongsaPhuket
1 row
idnamecity
11Dao RungrojTrang
1 row
idnamecityphonejoined
3Anan WongsaPhuketNULL2025-04-20
11Dao RungrojTrangNULL2026-12-01
2 rows

The real customer table changed: Anan Wongsa now lives in Phuket, and Dao Rungroj is a new customer, with joined filled in by the trigger. Whoever uses the view never sees a phone number, and can still keep names and cities up to date.

Seeing, dropping, and when not to use triggers

Triggers are kept in sqlite_schema too, with type trigger; tbl_name is the table or view they belong to:

SELECT name, tbl_name FROM sqlite_schema WHERE type = 'trigger' ORDER BY name;
nametbl_name
customer_public_insertcustomer_public
customer_public_updatecustomer_public
order_item_check_stockorder_item
order_item_take_stockorder_item
product_price_logproduct
5 rows

DROP TRIGGER removes one (IF EXISTS doesn't complain when it isn't there). Dropping a table drops its triggers with it.

DROP TRIGGER customer_public_insert;
DROP TRIGGER IF EXISTS no_such_trigger;
SELECT name FROM sqlite_schema WHERE type = 'trigger' ORDER BY name;
name
customer_public_update
order_item_check_stock
order_item_take_stock
product_price_log
4 rows

Triggers work out of sight, and that is both their strength and their danger. Someone who runs INSERT INTO order_item and sees the stock change will wonder why, and a trigger that runs another trigger that runs a third is hard to follow and slows every write down. Use triggers for what must always happen, whoever writes: logs, keeping figures in step, rules a constraint can't express. Don't use them for business steps that belong in the program, like sending an email when an order is paid. And write down which triggers your database has.

  1. Make a trigger order_item_give_back that puts stock back when an order line is deleted (use OLD). Delete the cheesecake line of order 16 and see Cheesecake's stock.
  2. Make a BEFORE UPDATE OF price trigger on product that refuses a price of 0 or less with the message a price must be more than 0. Then set Green Tea's price (id 2) to 50, which should go through.
Show the answer
CREATE TRIGGER order_item_give_back
AFTER DELETE ON order_item
BEGIN
  UPDATE product SET stock = stock + OLD.qty WHERE id = OLD.product_id;
END;
DELETE FROM order_item WHERE order_id = 16 AND product_id = 6;
SELECT id, name, stock FROM product WHERE id = 6;

CREATE TRIGGER product_price_positive
BEFORE UPDATE OF price ON product
WHEN NEW.price <= 0
BEGIN
  SELECT RAISE(ABORT, 'a price must be more than 0');
END;
UPDATE product SET price = 50 WHERE id = 2;
SELECT id, name, price FROM product WHERE id = 2;
idnamestock
6Cheesecake8
1 row
idnameprice
2Green Tea50.0
1 row

Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made