Skip to content
KALANBLON
Show contents

Chapter 5 of 7 · 20 min

Triggers, constraints and savepoints

By the end of this chapter, you'll be able to

  • Automate a reaction to a change with a trigger
  • Refuse an invalid operation with RAISE
  • Make types and calculations reliable with STRICT and generated columns
  • Cancel part of a transaction with SAVEPOINT

Triggers

A trigger is a block of statements that the database runs automatically before or after an INSERT, an UPDATE or a DELETE. Inside the block, NEW refers to the row after the change, OLD to the row before.

The shop records every incoming or outgoing goods movement in movements. Two triggers keep the stock up to date and flag low stock:

CREATE TRIGGER apply_movement
AFTER INSERT ON movements
BEGIN
  UPDATE stock SET quantity = quantity + NEW.delta WHERE product = NEW.product;
END;

CREATE TRIGGER low_stock_alert
AFTER UPDATE OF quantity ON stock
WHEN NEW.quantity < NEW.threshold AND OLD.quantity >= OLD.threshold
BEGIN
  INSERT INTO log (message) VALUES ('low stock: ' || NEW.product || ' (' || NEW.quantity || ')');
END;

INSERT INTO movements (product, delta, reason) VALUES
  ('solar lamp', -4, 'sale'), ('water filter', -4, 'sale'), ('water bottle', 20, 'delivery'), ('solar lamp', -5, 'sale');
SELECT product, quantity FROM stock ORDER BY product;
SELECT message FROM log;
product | quantity
solar lamp | 3
water bottle | 60
water filter | 2
message
low stock: water filter (2)
low stock: solar lamp (3)
  • AFTER INSERT ON movements: the first trigger runs after each movement is inserted, and applies NEW.delta to the product's stock.
  • AFTER UPDATE OF quantity ON stock: the second reacts to quantity changes. Its WHEN clause runs it only if the stock drops below the threshold, so the alert isn't repeated on every sale.
  • Triggers chain: inserting a movement updates the stock, which can write to the log. It all happens in the same transaction as the original insertion.

The message is written to the log. The program that inserted the sale had nothing more to do.

Step 4 of 4
Text description of the animation
  1. The row is inserted into movements. The lamp stock is then 8.
  2. The AFTER INSERT trigger runs UPDATE stock: 8 + (-5) = 3.
  3. This UPDATE fires low_stock_alert: 3 < 5 and 8 ≥ 5, the WHEN condition is true.
  4. The message is written to the log. The program that inserted the sale had nothing more to do.

Refusing an operation

What happens if we sell more filters than are left? The CHECK (quantity >= 0) constraint of stock refuses the update, and the whole insertion is cancelled:

CREATE TRIGGER apply_movement
AFTER INSERT ON movements
BEGIN
  UPDATE stock SET quantity = quantity + NEW.delta WHERE product = NEW.product;
END;
INSERT INTO movements (product, delta, reason) VALUES ('water filter', -10, 'sale');
CHECK constraint failed: quantity >= 0

The message talks about quantity >= 0, while the user inserted a movement: not very helpful. A BEFORE INSERT trigger can check the rule beforehand and refuse with a clear message, thanks to RAISE(ABORT, 'message'):

CREATE TRIGGER refuse_impossible_sale
BEFORE INSERT ON movements
WHEN NEW.delta < 0 AND (SELECT quantity FROM stock WHERE product = NEW.product) + NEW.delta < 0
BEGIN
  SELECT RAISE(ABORT, 'insufficient stock');
END;
INSERT INTO movements (product, delta, reason) VALUES ('water filter', -10, 'sale');
insufficient stock

Reliable types and calculations

By default, SQLite has flexible typing: an INTEGER column also accepts text. A STRICT table refuses any value of the wrong type. A generated column is computed by the database from the other columns: it can't be wrong or forgotten.

CREATE TABLE orders (
  id INTEGER PRIMARY KEY,
  quantity INTEGER NOT NULL,
  unit_price REAL NOT NULL,
  discount_pct REAL NOT NULL DEFAULT 0 CHECK (discount_pct BETWEEN 0 AND 50),
  total REAL GENERATED ALWAYS AS (ROUND(quantity * unit_price * (1 - discount_pct / 100), 2)) STORED
) STRICT;
INSERT INTO orders (quantity, unit_price, discount_pct) VALUES (3, 25.0, 10), (1, 40.0, 0);
SELECT id, quantity, unit_price, discount_pct, total FROM orders;
id | quantity | unit_price | discount_pct | total
1 | 3 | 25 | 10 | 67.5
2 | 1 | 40 | 0 | 40

GENERATED ALWAYS AS (…) STORED computes and stores total on every insert or update. Nobody can write it directly.

SAVEPOINT: cancelling part of a transaction

Inside a transaction, a SAVEPOINT sets a marker. ROLLBACK TO marker cancels what was done since that marker, without abandoning the whole transaction:

BEGIN;
INSERT INTO log (message) VALUES ('stocktake started');
SAVEPOINT recount;
UPDATE stock SET quantity = 0 WHERE product = 'water bottle';
ROLLBACK TO recount;
UPDATE stock SET quantity = 38 WHERE product = 'water bottle';
COMMIT;
SELECT product, quantity FROM stock WHERE product = 'water bottle';
SELECT message FROM log;
product | quantity
water bottle | 38
message
stocktake started

The mistaken recount (stock at 0) was cancelled, but the log message, written before the marker, is kept. It's useful in a long process: on an error with one item, you cancel just that item, and carry on.

Your turn

Mini-lab: refusing an impossible saleSQLite

Result

Click “Run”: the SQL engine (about 1 MB) will load in your browser the first time.

A fresh SQLite database is created on every run, in your browser · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Worked exercise

Solved exercise: the threshold history

Each product's alert threshold is changed from time to time. Write a trigger that records in log every real threshold change, in the form solar lamp: threshold 5 → 8. An update that sets the same value again must log nothing. Test with three updates, one of which changes nothing.

Hint 1
AFTER UPDATE OF threshold ON stock only reacts to updates that touch the threshold column.
Hint 2
The WHEN NEW.threshold <> OLD.threshold clause filters out updates that change nothing.
Show the solution and common mistakes
CREATE TRIGGER track_threshold
AFTER UPDATE OF threshold ON stock
WHEN NEW.threshold <> OLD.threshold
BEGIN
  INSERT INTO log (message) VALUES (NEW.product || ': threshold ' || OLD.threshold || ' → ' || NEW.threshold);
END;
UPDATE stock SET threshold = 8 WHERE product = 'solar lamp';
UPDATE stock SET threshold = 8 WHERE product = 'solar lamp';
UPDATE stock SET threshold = 15 WHERE product = 'water bottle';
SELECT id, message FROM log;
id | message
1 | solar lamp: threshold 5 → 8
2 | water bottle: threshold 10 → 15

The second update sets 8 again while the threshold is already 8: the WHEN clause is false, nothing is logged.

Common mistakes:

  • Forgetting the WHEN clause: every update, even with no effect, adds a row to the log.
  • Writing an AFTER UPDATE ON stock trigger without OF threshold: it also runs on every sale, which changes the quantity. With the WHEN clause the result stays right, but the database works for nothing.

Summary

  1. 1A trigger runs statements before or after a change; NEW and OLD refer to the row after and before.
  2. 2RAISE(ABORT, 'message') in a BEFORE trigger refuses an operation with a clear message.
  3. 3A STRICT table refuses values of the wrong type; a generated column is always right.
  4. 4SAVEPOINT and ROLLBACK TO cancel only part of a transaction.
  5. 5Rules handed to the database apply to every program that uses it.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.