Database Triggers
What you will learn
- What a trigger is and when it fires
- The difference between BEFORE, AFTER and INSTEAD OF triggers
- How to read the OLD and NEW rows inside a trigger
- Two common uses: a change log and a safety check
- Why triggers must be used with care
1. What is a trigger?
A trigger is a rule stored inside the database that runs by itself when something happens to a table. You do not call it. The database calls it whenever a matching INSERT, UPDATE or DELETE happens, no matter which program made the change.
Think of a door sensor: nobody presses a button, but when the door opens the light turns on.
A trigger has four parts:
| Part | Example | Meaning |
|---|---|---|
| Timing | AFTER |
before or after the change |
| Event | UPDATE OF price |
which statement (and sometimes which column) |
| Table | ON products |
where to watch |
| Action | INSERT INTO price_log ... |
what to do |
Triggers connect to ideas you already know. Constraints (lesson 2.7) refuse bad data with a fixed rule. A trigger can do the same with any logic you like, and it can also react by changing other tables.
2. A change log with an AFTER trigger
This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It adds tables and triggers of its own to your browser's copy; run the examples from top to bottom, and Reset data starts again.
Our shop wants to remember every price change. Instead of trusting every program to write the log, we let the database do it.
Our bank wants to remember every status change of an account. Instead of trusting every program to write the log, we let the database do it.
Our school wants to remember every change of the credits of a course. Instead of trusting every program to write the log, we let the database do it.
CREATE TABLE change_trace (
id INTEGER PRIMARY KEY,
row_id INTEGER, old_value, new_value);
CREATE TRIGGER log_change
AFTER UPDATE OF price ON products
WHEN OLD.price <> NEW.price
BEGIN
INSERT INTO change_trace (row_id, old_value, new_value)
VALUES (OLD.product_id, OLD.price, NEW.price);
END;
(done)
CREATE TABLE change_trace (
id INTEGER PRIMARY KEY,
row_id INTEGER, old_value, new_value);
CREATE TRIGGER log_change
AFTER UPDATE OF status ON accounts
WHEN OLD.status <> NEW.status
BEGIN
INSERT INTO change_trace (row_id, old_value, new_value)
VALUES (OLD.account_id, OLD.status, NEW.status);
END;
(done)
CREATE TABLE change_trace (
id INTEGER PRIMARY KEY,
row_id INTEGER, old_value, new_value);
CREATE TRIGGER log_change
AFTER UPDATE OF credits ON courses
WHEN OLD.credits <> NEW.credits
BEGIN
INSERT INTO change_trace (row_id, old_value, new_value)
VALUES (OLD.course_id, OLD.credits, NEW.credits);
END;
(done)
Inside the trigger, two special names are available:
OLDis the row as it was before the change (exists forUPDATEandDELETE).NEWis the row as it will be after the change (exists forINSERTandUPDATE).
The WHEN line is a filter: the trigger only does its work if the watched value really changed. Now make three updates: one that changes it, one that writes the same value again, and one that changes another column:
UPDATE products SET price = 130 WHERE product_id = 1;
UPDATE products SET price = price WHERE product_id = 2;
UPDATE products SET name = 'Steel pan XL' WHERE product_id = 1;
SELECT * FROM change_trace;
id row_id old_value new_value
-- ------ --------- ---------
1 1 6.6 130.0
(1 row)
UPDATE accounts SET status = 'frozen' WHERE account_id = 1;
UPDATE accounts SET status = status WHERE account_id = 2;
UPDATE accounts SET account_type = 'savings' WHERE account_id = 1;
SELECT * FROM change_trace;
id row_id old_value new_value
-- ------ --------- ---------
1 1 open frozen
(1 row)
UPDATE courses SET credits = 5 WHERE course_id = 1;
UPDATE courses SET credits = credits WHERE course_id = 2;
UPDATE courses SET title = 'Algebra 1' WHERE course_id = 1;
SELECT * FROM change_trace;
id row_id old_value new_value
-- ------ --------- ---------
1 1 4 5
(1 row)
Only the first update was logged: the second did not change the value, and the third changed a column the trigger does not watch.
Quick check: what do OLD and NEW hold in the first update?
OLD is the value before the change and NEW the value after it. That is exactly the pair in the log row.
3. A safety check with a BEFORE trigger
A BEFORE trigger runs first and can stop the change. In SQLite you stop it with RAISE(ABORT, 'message').
CREATE TABLE soap_products (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price INTEGER NOT NULL);
CREATE TRIGGER no_negative_price
BEFORE INSERT ON soap_products
WHEN NEW.price < 0
BEGIN
SELECT RAISE(ABORT, 'price cannot be negative');
END;
INSERT INTO soap_products (name, price) VALUES ('Soap', 50);
(1 row changed)
INSERT INTO soap_products (name, price) VALUES ('Soap', -5);
IntegrityError: price cannot be negative
SELECT COUNT(*) AS products FROM soap_products;
products
--------
1
(1 row)
CREATE TABLE soap_products (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price INTEGER NOT NULL);
CREATE TRIGGER no_negative_price
BEFORE INSERT ON soap_products
WHEN NEW.price < 0
BEGIN
SELECT RAISE(ABORT, 'price cannot be negative');
END;
INSERT INTO soap_products (name, price) VALUES ('Soap', 50);
(1 row changed)
INSERT INTO soap_products (name, price) VALUES ('Soap', -5);
IntegrityError: price cannot be negative
SELECT COUNT(*) AS products FROM soap_products;
products
--------
1
(1 row)
CREATE TABLE soap_products (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price INTEGER NOT NULL);
CREATE TRIGGER no_negative_price
BEFORE INSERT ON soap_products
WHEN NEW.price < 0
BEGIN
SELECT RAISE(ABORT, 'price cannot be negative');
END;
INSERT INTO soap_products (name, price) VALUES ('Soap', 50);
(1 row changed)
INSERT INTO soap_products (name, price) VALUES ('Soap', -5);
IntegrityError: price cannot be negative
SELECT COUNT(*) AS products FROM soap_products;
products
--------
1
(1 row)
(A simple CHECK (price >= 0) would do this job with less machinery. Use a trigger only when a plain constraint cannot express the rule, for example a rule that must look at other tables.)
4. Timing: BEFORE, AFTER and INSTEAD OF
| Timing | Runs | Typical use |
|---|---|---|
BEFORE |
before the change is made | refuse or check data |
AFTER |
after the change is made | log, copy, update other tables |
INSTEAD OF |
in place of the change, on a view | make a view you can write to |
INSTEAD OF triggers work on views (lesson 4.7): the view cannot be written to directly, so you say what should happen to the real tables instead.
SQLite's own documentation warns that the effect of changing a table inside a BEFORE trigger can be unpredictable, so keep BEFORE triggers for checks and put the changes in AFTER triggers.
5. Looking at and removing triggers
Triggers live in the database's catalog. You can list and drop them:
SELECT name FROM sqlite_master WHERE type = 'trigger' ORDER BY name;
DROP TRIGGER no_negative_price;
SELECT name FROM sqlite_master WHERE type = 'trigger' ORDER BY name;
name
-----------------
log_change
no_negative_price
(2 rows)
name
----------
log_change
(1 row)
SELECT name FROM sqlite_master WHERE type = 'trigger' ORDER BY name;
DROP TRIGGER no_negative_price;
SELECT name FROM sqlite_master WHERE type = 'trigger' ORDER BY name;
name
-----------------
log_change
no_negative_price
(2 rows)
name
----------
log_change
(1 row)
SELECT name FROM sqlite_master WHERE type = 'trigger' ORDER BY name;
DROP TRIGGER no_negative_price;
SELECT name FROM sqlite_master WHERE type = 'trigger' ORDER BY name;
name
-----------------
log_change
no_negative_price
(2 rows)
name
----------
log_change
(1 row)
Other systems have their own catalog views, and their syntax differs. For example, PostgreSQL's CREATE TRIGGER does not hold the action itself: it says EXECUTE FUNCTION function_name(...), and the work lives in a separate function. Its documentation page for CREATE TRIGGER also lets a trigger run once per row or once per statement. We do not run PostgreSQL in this course, so treat that as a pointer to its documentation, not something shown here.
6. The dangers of triggers
Triggers are powerful and easy to forget. Here is what goes wrong:
CREATE TABLE demo_orders (id INTEGER PRIMARY KEY, total INTEGER);
CREATE TABLE audit_notes (note TEXT);
CREATE TRIGGER note_order AFTER INSERT ON demo_orders BEGIN INSERT INTO audit_notes VALUES ('order ' || NEW.id); END;
INSERT INTO demo_orders (total) VALUES (10), (20), (30);
SELECT * FROM audit_notes;
note
-------
order 1
order 2
order 3
(3 rows)
CREATE TABLE demo_orders (id INTEGER PRIMARY KEY, total INTEGER);
CREATE TABLE audit_notes (note TEXT);
CREATE TRIGGER note_order AFTER INSERT ON demo_orders BEGIN INSERT INTO audit_notes VALUES ('order ' || NEW.id); END;
INSERT INTO demo_orders (total) VALUES (10), (20), (30);
SELECT * FROM audit_notes;
note
-------
order 1
order 2
order 3
(3 rows)
CREATE TABLE demo_orders (id INTEGER PRIMARY KEY, total INTEGER);
CREATE TABLE audit_notes (note TEXT);
CREATE TRIGGER note_order AFTER INSERT ON demo_orders BEGIN INSERT INTO audit_notes VALUES ('order ' || NEW.id); END;
INSERT INTO demo_orders (total) VALUES (10), (20), (30);
SELECT * FROM audit_notes;
note
-------
order 1
order 2
order 3
(3 rows)
Someone who only reads the application code sees three inserts into demo_orders and may never learn that audit_notes is also being written. That is the main danger: hidden behaviour.
Worked example: choose the right tool
For each need, decide between a column rule (NOT NULL, CHECK, UNIQUE, DEFAULT), a trigger, or application code.
| Need | Best choice | Why |
|---|---|---|
| Price must be zero or more | CHECK (price >= 0) |
one column, simple rule |
| Keep a history of every price change, whoever makes it | trigger | must work for all programs, writes to another table |
| Send an email when an order is placed | application code | a database trigger should not talk to the outside world |
| An order's total must equal the sum of its lines | trigger or a careful design | involves two tables |
The products and prices are made up.
Common mistakes
- Using a trigger where a constraint would do. Constraints are simpler, faster to read and checked the same way every time.
- Hiding important business logic in triggers that nobody documents. Write down every trigger (name, table, what it does).
- Triggers that cause more triggers. One change can start a chain that is hard to follow and slow.
- Forgetting that bulk changes fire the trigger for every row. Loading a million rows runs a row-level trigger a million times.
- Putting slow or outside-world work in a trigger (sending email, calling a web service). The change waits until the trigger finishes.
Key takeaways
- A trigger runs automatically when a table is changed, for every program that changes it.
- Use
AFTERtriggers to log or copy changes andBEFOREtriggers to check or refuse data. OLDis the row before the change;NEWis the row after it.- Prefer a plain constraint when one is enough; keep triggers few, small and documented.
- Syntax differs between databases, so check your system's documentation.
Practice
1. What is the difference between a trigger and a CHECK constraint?
Show answer
A CHECK constraint only accepts or refuses a row using a rule about that row. A trigger can run any logic, look at other tables, and change other tables, but it is harder to see and maintain.
2. In an AFTER UPDATE trigger, which name holds the value before the change?
Show answer
OLD (for example OLD.price). NEW.price holds the value after the change.
3. In the price-log example, why was the update SET name = 'Green tea' not logged?
Show answer
The trigger was defined as AFTER UPDATE OF price, so it only fires when the price column is part of the update. That update changed only name.
4. Why is putting an email-sending step inside a trigger a bad idea?
Show answer
The change in the database must wait for the slow outside action, and if the trigger fails the whole change may be refused. It is also hidden from people reading the application. Better to save an event and let a separate program send the email (lesson 11.7).
5. A table receives 10,000 inserts at once and has a row-level AFTER INSERT trigger. How many times does the trigger run?
Show answer
10,000 times, once for each inserted row. (The three-row example above wrote three audit rows for three inserted orders.)
6. Name two things you should do to keep triggers manageable in a team project.
Show answer
For example: keep triggers few and small, and document each one (name, table, purpose). Test them, and use a constraint instead whenever a constraint is enough.