SQLite Triggers
What is a Trigger?
A trigger is a set of SQL statements that runs automatically when something happens in a table: an INSERT, an UPDATE or a DELETE.
CREATE TRIGGER trigger_name
BEFORE|AFTER INSERT|UPDATE|DELETE
ON table_name
BEGIN
statements;
END;
Inside the trigger, NEW is the new version of the row, and OLD is the old version.
Log Price Changes
This example creates a table for a log, and a trigger that writes to the log every time a price is changed. Then it changes a price, and shows the log:
Example
CREATE TABLE IF NOT EXISTS PriceLog (
ProductID INTEGER,
OldPrice NUMERIC,
NewPrice NUMERIC,
ChangedAt TEXT
);
CREATE TRIGGER IF NOT EXISTS LogPrice
AFTER UPDATE OF Price ON Products
BEGIN
INSERT INTO PriceLog VALUES (
OLD.ProductID, OLD.Price,
NEW.Price, datetime('now'));
END;
UPDATE Products SET Price = 20
WHERE ProductID = 1;
SELECT * FROM PriceLog;
Try it Yourself »
Stop a Change
A BEFORE trigger can stop a change with RAISE(). This trigger does not allow negative prices:
Example
CREATE TRIGGER IF NOT EXISTS CheckPrice
BEFORE UPDATE OF Price ON Products
WHEN NEW.Price < 0
BEGIN
SELECT RAISE(ABORT, 'Price cannot be negative');
END;
UPDATE Products SET Price = -5
WHERE ProductID = 1;
Try it Yourself »
Delete a Trigger
DROP TRIGGER trigger_name;