A trigger is a stored program the DBMS runs automatically when a specified event — INSERT, UPDATE or DELETE on a table — occurs, optionally only when a condition holds. Triggers implement audit trails, derived values and business rules that declarative constraints cannot express.
Medium 40 minSyllabus: “Triggers”
Mark as
The idea in one minute
A trigger works like a motion-sensor light: you never switch it on yourself — an event (someone walks in) fires it, a condition (only when it is dark) decides whether it acts, and the action (light on) follows. In a database the event is a row change, the condition is a WHEN test, and the action is some SQL — for example writing an entry in an audit log whenever a salary changes.
Key points — the night-before list
ECA model: Event (INSERT, UPDATE [OF columns], DELETE; also DDL or logon in Oracle), Condition (WHEN), Action (SQL or procedural block).
Timing: BEFORE (validate or adjust incoming values), AFTER (audit, cascade changes), INSTEAD OF (replace the operation — used on views).
Row-level (FOR EACH ROW) fires once per affected row; statement-level fires once per statement — even when zero rows are affected.
OLD exists for UPDATE and DELETE, NEW for INSERT and UPDATE; Oracle writes :OLD/:NEW in the body but OLD/NEW in WHEN.
SQLite: BEFORE/AFTER/INSTEAD OF, row-level only, WHEN clause, SELECT RAISE(ABORT, 'msg') to reject; MySQL rejects with SIGNAL SQLSTATE '45000'.
Uses: auditing, maintaining derived or summary data, complex integrity rules (comparing OLD with NEW, cross-table), logging, making views updatable.
Prefer declarative constraints when they suffice — cheaper, visible, always enforced. Triggers are invoked implicitly; procedures are called explicitly.
Pitfalls: Oracle mutating-table error ORA-04091, cascading and recursive triggers, hidden side effects, per-row cost on bulk statements.
01What a trigger is: the event–condition–action model
A trigger is a named block of code stored in the database and attached to a table (or view, or schema). The DBMS executes it implicitly whenever its triggering event happens — nobody calls it. Databases that react to events this way are called active databases; triggers were standardised in SQL:1999, though Oracle, DB2 and others had them earlier.
The ECA rule
Event
What wakes the trigger: INSERT, DELETE, or UPDATE (optionally UPDATE OF specific columns) on a particular table. Oracle adds DDL events (CREATE, DROP) and database events (LOGON, STARTUP).
Condition
An optional test, the WHEN clause, evaluated for each triggering row; if it is not TRUE, the action is skipped.
Action
The SQL statements (or PL/SQL / procedural block) to run: insert an audit row, update a summary, or raise an error that cancels the triggering statement.
PSC favourite
'A program that is automatically executed in response to some event such as a modification of the database' — trigger (not cursor, procedure or method). 'Invoke a stored program automatically before a new record is inserted' — a row-level BEFORE INSERT trigger.
02Timing, granularity and the OLD/NEW values
Timing
Runs
Typical use
BEFORE
Before the row is changed (and before constraints are checked)
Validate data, reject bad changes, fill in or adjust values (in Oracle/MySQL by assigning NEW)
AFTER
After the row is changed
Audit trails, maintaining summary tables, propagating changes to other tables
INSTEAD OF
In place of the triggering statement
Make a join or aggregate view updatable by translating the change into base-table changes
Row-level trigger (FOR EACH ROW)
Fires once for every row the statement affects
Can read OLD and NEW values of that row
An UPDATE of 3 rows → 3 executions; of 0 rows → none
The only kind in SQLite and MySQL
Statement-level trigger
Fires once per triggering statement
No OLD/NEW row values (standard SQL offers transition tables instead)
An UPDATE of 3 rows → 1 execution; of 0 rows → still 1
Default in Oracle when FOR EACH ROW is omitted; SQL Server triggers are statement-level
Event
OLD (row before)
NEW (row after)
INSERT
not available
the row being inserted
UPDATE
values before the update
values after the update
DELETE
the row being deleted
not available
Which pseudo-records exist for each event
Spelling differs by product. SQLite and MySQL write OLD.salary and NEW.salary; Oracle writes :OLD.salary and :NEW.salary inside the trigger body but plain OLD/NEW in its WHEN clause; SQL Server exposes the pseudo-tables deleted and inserted. A BEFORE row trigger may modify the incoming row in Oracle (:NEW.ename := UPPER(:NEW.ename);) and MySQL (SET NEW.ename = UPPER(NEW.ename);) — SQLite cannot assign to NEW, so the same effect needs an AFTER trigger that runs an UPDATE.
SQLAudit every salary change (SQLite — runs in the SQL playground)
CREATE TABLE salary_audit (
audit_id INTEGER PRIMARY KEY,
emp_id INTEGER,
old_salary DECIMAL(10,2),
new_salary DECIMAL(10,2),
changed_on TEXT
);
CREATE TRIGGER trg_salary_audit
AFTER UPDATE OF salary ON emp -- event: only when salary is assigned
FOR EACH ROW
WHEN NEW.salary <> OLD.salary -- condition: skip no-op updates
BEGIN
INSERT INTO salary_audit (emp_id, old_salary, new_salary, changed_on)
VALUES (OLD.emp_id, OLD.salary, NEW.salary, datetime('now'));
END;
UPDATE emp SET salary = salary + 5000 WHERE dept_id = 30;
SELECT audit_id, emp_id, old_salary, new_salary FROM salary_audit;
-- 1 | 103 | 55000 | 60000-- 2 | 106 | 30000 | 35000-- 3 | 107 | 28000 | 33000
SQLBusiness rules with RAISE(ABORT, …) (SQLite)
-- rule 1: a budget can never become negative
CREATE TRIGGER trg_budget_nonneg
BEFORE UPDATE OF budget ON project
FOR EACH ROW
WHEN NEW.budget < 0
BEGIN
SELECT RAISE(ABORT, 'budget cannot be negative');
END;
-- rule 2: a budget may not be cut by more than half in one go (needs OLD and NEW —-- impossible with a CHECK constraint, which sees only the new row)
CREATE TRIGGER trg_budget_cut
BEFORE UPDATE OF budget ON project
FOR EACH ROW
WHEN NEW.budget < OLD.budget * 0.5
BEGIN
SELECT RAISE(ABORT, 'budget cannot be cut by more than half at once');
END;
UPDATE project SET budget = budget - 600000 WHERE proj_id = 3; -- error: budget cannot be negative
UPDATE project SET budget = 100000 WHERE proj_id = 2; -- error: cut by more than half
UPDATE project SET budget = 500000 WHERE proj_id = 2; -- OK: 900000 → 500000 is a 44% cut
RAISE(ABORT, msg) cancels the whole triggering statement, not just the current row: UPDATE project SET budget = budget * 0.4 fails on the first project and leaves all four budgets unchanged, because a statement is atomic. SQLite also offers RAISE(IGNORE) (silently skip this row's operation), RAISE(FAIL, msg) (stop but keep earlier rows' changes) and RAISE(ROLLBACK, msg) (roll back the entire transaction).
SQLINSTEAD OF trigger: making a join view insertable (SQLite)
CREATE VIEW emp_dept AS
SELECT e.emp_id, e.ename, d.dname FROM emp e JOIN dept d ON d.dept_id = e.dept_id;
INSERT INTO emp_dept VALUES (111, 'Kiran', 'Sales');
-- error: cannot modify emp_dept because it is a view
CREATE TRIGGER trg_emp_dept_ins
INSTEAD OF INSERT ON emp_dept
FOR EACH ROW
BEGIN
INSERT INTO emp (emp_id, ename, dept_id)
VALUES (NEW.emp_id, NEW.ename, (SELECT dept_id FROM dept WHERE dname = NEW.dname));
END;
INSERT INTO emp_dept VALUES (111, 'Kiran', 'Sales'); -- now succeeds
SELECT * FROM emp WHERE emp_id = 111; -- 111 | Kiran | NULL | NULL | NULL | 30 | NULL
04Oracle PL/SQL, MySQL and SQL Server syntax
SQLOracle: row-level and statement-level triggers
-- row-level: salaries may never be reduced
CREATE OR REPLACE TRIGGER trg_no_salary_cut
BEFORE UPDATE OF salary ON emp
FOR EACH ROW
WHEN (NEW.salary < OLD.salary) -- no colons in WHEN
BEGIN
RAISE_APPLICATION_ERROR(-20001, 'Salary of ' || :OLD.ename || ' cannot be reduced');
END;
/
-- statement-level (no FOR EACH ROW): changes only during office hours
CREATE OR REPLACE TRIGGER trg_office_hours
BEFORE INSERT OR UPDATE OR DELETE ON emp
BEGIN
IF TO_CHAR(SYSDATE, 'HH24') NOT BETWEEN '09' AND '17' THEN
RAISE_APPLICATION_ERROR(-20002, 'Changes allowed only in office hours');
END IF;
END;
/
SQLMySQL: BEFORE INSERT trigger that validates and adjusts NEW
DELIMITER $$
CREATE TRIGGER trg_emp_bi
BEFORE INSERT ON emp
FOR EACH ROW
BEGIN
IF NEW.salary <= 0 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Salary must be positive';
END IF;
SET NEW.ename = UPPER(NEW.ename);
END$$
DELIMITER ;
Feature
SQLite
Oracle
MySQL
SQL Server
Timing
BEFORE, AFTER, INSTEAD OF (views)
BEFORE, AFTER, INSTEAD OF, COMPOUND
BEFORE, AFTER
AFTER (FOR), INSTEAD OF
Granularity
Row only
Row and statement
Row only
Statement only
Old / new values
OLD.col, NEW.col
:OLD.col, :NEW.col
OLD.col, NEW.col
deleted / inserted tables
Change incoming row
No
:NEW.col := … (BEFORE)
SET NEW.col = … (BEFORE)
Via INSTEAD OF
Reject the change
RAISE(ABORT, 'msg')
RAISE_APPLICATION_ERROR(-20000…-20999, 'msg')
SIGNAL SQLSTATE '45000'
THROW / RAISERROR + ROLLBACK
Condition
WHEN expr
WHEN (cond)
IF inside body
IF inside body
Trigger dialects compared
05What triggers are used for
Auditing — record who changed what and when (salary_audit above); a classic legal and security requirement.
Derived and summary data — keep a department's head-count or a project's total hours up to date in a summary table, or maintain a denormalised copy.
Complex integrity rules — rules involving OLD and NEW (no salary cuts, budget cuts ≤ 50%), several rows (total hours per employee ≤ 60) or several tables, which CHECK constraints cannot express.
Event logging and notification — insert into a queue table that another process reads; replicate changes to another database.
Generating values — before identity columns existed, Oracle triggers filled primary keys from a sequence (:NEW.emp_id := emp_seq.NEXTVAL;).
Security and policy — block changes outside office hours or by certain users; log failed operations.
Updatable views — INSTEAD OF triggers translate changes on a join view into changes on its base tables.
Tip
Rule of thumb: if a rule can be written as NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY or CHECK, declare it — the DBMS enforces it more cheaply and visibly. Reach for a trigger only when the rule needs old values, other rows or other tables.
06Triggers vs constraints vs stored procedures
Aspect
Constraint
Trigger
Stored procedure
How it runs
Checked automatically by the DBMS
Fired automatically by an event
Called explicitly (CALL / EXEC)
Written as
Declarative condition
Procedural or SQL action
Procedural program
Parameters / return value
None
None (uses OLD/NEW)
IN, OUT, INOUT parameters
Can see old values
No — only the new row
Yes (OLD)
Only what it queries
Transaction control
—
Normally no COMMIT/ROLLBACK inside
May COMMIT (depending on product)
Typical use
Keys, ranges, references
Audit, derived data, complex rules
Business operations, batch jobs
Choosing the right tool
A trigger runs inside the transaction of the statement that fired it, so if the trigger fails, the statement fails, and if the transaction later rolls back, the trigger's changes roll back too. That is why triggers generally may not COMMIT or ROLLBACK themselves (Oracle's autonomous transactions are the deliberate exception, used for logging that must survive a rollback).
07Pitfalls: mutating tables, cascades and hidden logic
Mutating-table error (Oracle ORA-04091). A row-level trigger may not query or modify the table that is being changed by the triggering statement, because the table is in an intermediate state ('mutating'). A row trigger on emp that checks SELECT AVG(salary) FROM emp during an UPDATE of emp fails. Fixes: a statement-level AFTER trigger, an Oracle 11g compound trigger (collect rows in the row section, check in the after-statement section), or a declarative constraint.
Cascading and recursive triggers. A trigger's action can fire other triggers, which can fire more — a chain that is hard to follow and can loop. Products limit the depth (Oracle caps trigger cascading; SQL Server allows 32 nested levels). SQLite disables recursive firing of a trigger by its own action unless PRAGMA recursive_triggers = ON, and MySQL forbids a trigger from modifying the table that fired it.
Hidden logic — a simple-looking UPDATE silently does extra work; document triggers and keep them short.
Performance — a row-level trigger runs once per row, so a bulk update of a million rows runs it a million times.
Order — several triggers on the same event may run in an unspecified order unless the product lets you specify it (Oracle and MySQL: FOLLOWS / PRECEDES).
Bypass — TRUNCATE does not fire DELETE triggers, and bulk-load utilities may skip triggers.
Worked examples
Try the problem first, then reveal the working one step at a time.
EX 1Tracing an audit trigger
With trg_salary_audit (AFTER UPDATE OF salary, FOR EACH ROW, WHEN NEW.salary <> OLD.salary) installed, predict the audit rows written by: (1) UPDATE emp SET salary = salary + 5000 WHERE dept_id = 30; (2) UPDATE emp SET salary = salary WHERE dept_id = 10; (3) UPDATE emp SET salary = salary + 1 WHERE dept_id = 40.
EX 2A rule that needs OLD and NEW
With the two budget triggers installed (no negative budget; no cut of more than half), predict: (1) UPDATE project SET budget = budget − 600000 WHERE proj_id = 3; (2) UPDATE project SET budget = 100000 WHERE proj_id = 2; (3) UPDATE project SET budget = 500000 WHERE proj_id = 2; (4) UPDATE project SET budget = budget * 0.4 (all projects).
EX 3Row-level versus statement-level firing counts
An Oracle table has a row-level AFTER UPDATE trigger R and a statement-level AFTER UPDATE trigger S. How many times does each fire for an UPDATE that changes 3 rows, and for one whose WHERE matches no rows?
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
For each trigger, say whether OLD, NEW or both are available: (a) BEFORE INSERT; (b) AFTER UPDATE; (c) AFTER DELETE; (d) INSTEAD OF INSERT on a view.
Q2
Write a SQLite trigger that fills in today's date when an employee is inserted without a hire_date. (Remember SQLite cannot assign to NEW.)
Q3
An AFTER DELETE row trigger on works_on inserts (OLD.emp_id, OLD.proj_id, date('now')) into wo_log. What does wo_log contain after DELETE FROM works_on WHERE proj_id = 3; on the sample data?
Q4
Choose a CHECK constraint or a trigger for each rule and justify: (a) salary > 0; (b) salary may never decrease; (c) an employee may work at most 60 hours in total across projects; (d) job must be one of Clerk, Analyst, Manager, Salesman, President.
Q5
An Oracle row-level BEFORE UPDATE trigger on emp rejects any new salary above twice the company average as it was before the update, computed with SELECT AVG(salary) INTO v_avg FROM emp. The first UPDATE fails with ORA-04091. Explain and suggest two fixes.
Exam traps
OLD is undefined in INSERT triggers and NEW in DELETE triggers.
Statement-level triggers fire once even when no rows are affected; row-level triggers fire once per affected row (0 rows → 0 times).
INSTEAD OF triggers are for views (Oracle, SQLite, SQL Server), not for ordinary tables; MySQL has none.
In Oracle the body uses :NEW/:OLD with colons, but the WHEN clause uses NEW/OLD without them.
Triggers run inside the triggering statement's transaction and normally cannot COMMIT or ROLLBACK; an error in a trigger cancels the whole statement.
SQLite and MySQL triggers are row-level only; SQLite cannot assign to NEW, and TRUNCATE never fires DELETE triggers.
Quiz — KPSC style
10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Triggers · Question 1 of 10✓ 0 · ✗ 0
A program that the DBMS executes automatically in response to an event such as an INSERT on a table is called a:
Past-paper questions on this topic
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.
Past papers · Question 1 of 3✓ 0 · ✗ 0
Modelled on QP 147/2023 · Junior Instructor (Computer Operator and Programming Assistant) (11 Aug 2023), Q.36 (reworded)original paper (PDF)
What is the name for a stored program that runs automatically when an event such as an insert, update or delete happens on a table?