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
);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;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;| id | product_id | old_price | new_price |
|---|---|---|---|
| 1 | 1 | 55.0 | 60.0 |
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 on | OLD | NEW |
|---|---|---|
INSERT | none (the row wasn't there) | the row added |
UPDATE | the row before | the row after |
DELETE | the row deleted | none (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;| id | product_id | old_price | new_price |
|---|---|---|---|
| 1 | 1 | 55.0 | 60.0 |
| 2 | 10 | 30.0 | 30.0 |
| 3 | 11 | 15.0 | 15.0 |
| 4 | 12 | 25.0 | 25.0 |
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:
UPDATE OF columnruns it only when theUPDATEsets that column.WHEN conditionruns it only for rows where the condition is true.
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;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;| id | product_id | old_price | new_price |
|---|---|---|---|
| 1 | 4 | 35.0 | 38.5 |
| 2 | 5 | 60.0 | 66.0 |
| 3 | 6 | 120.0 | 132.0 |
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;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);| id | name | stock |
|---|---|---|
| 6 | Cheesecake | 8 |
| 11 | Pen | 300 |
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);| id | name | stock |
|---|---|---|
| 6 | Cheesecake | 6 |
| 11 | Pen | 295 |
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;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);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;| id | name | stock |
|---|---|---|
| 6 | Cheesecake | 6 |
| 10 | Notebook | 75 |
| order_id | product_id | qty | price |
|---|---|---|---|
| 16 | 6 | 2 | 120.0 |
| 16 | 11 | 5 | 15.0 |
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;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);| id | name | city |
|---|---|---|
| 3 | Anan Wongsa | Phuket |
| id | name | city |
|---|---|---|
| 11 | Dao Rungroj | Trang |
| id | name | city | phone | joined |
|---|---|---|---|---|
| 3 | Anan Wongsa | Phuket | NULL | 2025-04-20 |
| 11 | Dao Rungroj | Trang | NULL | 2026-12-01 |
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;| name | tbl_name |
|---|---|
| customer_public_insert | customer_public |
| customer_public_update | customer_public |
| order_item_check_stock | order_item |
| order_item_take_stock | order_item |
| product_price_log | product |
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 |
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.
- Make a trigger
order_item_give_backthat puts stock back when an order line is deleted (useOLD). Delete the cheesecake line of order 16 and see Cheesecake's stock. - Make a
BEFORE UPDATE OF pricetrigger onproductthat refuses a price of 0 or less with the messagea 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;| id | name | stock |
|---|---|---|
| 6 | Cheesecake | 8 |
| id | name | price |
|---|---|---|
| 2 | Green Tea | 50.0 |
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