Active Rules
A conventional (passive) database acts only when a user or program asks it to. An active database has rules that react automatically to events. The rules follow the event-condition-action (ECA) model: ON an event (insert, delete or update of a table), IF a condition is true, THEN execute an action (SQL statements or procedures). In relational systems the rules are called triggers.
Syntax of Triggers
A trigger has a name, a timing (BEFORE, AFTER or INSTEAD OF), an event (INSERT, UPDATE [OF column], DELETE), a table, a granularity, an optional condition and an action.
- Oracle: CREATE [OR REPLACE] TRIGGER name BEFORE|AFTER INSERT OR UPDATE OR DELETE ON table [FOR EACH ROW] [WHEN (condition)] BEGIN ... END; the old and new row values are :OLD and :NEW.
- IBM DB2: CREATE TRIGGER name AFTER|NO CASCADE BEFORE event ON table REFERENCING OLD AS o NEW AS n FOR EACH ROW|STATEMENT WHEN (condition) BEGIN ATOMIC ... END.
- MySQL and SQLite use OLD and NEW directly; MySQL has FOR EACH ROW only.
Semantics
- Granularity: a row-level trigger runs once for each affected row; a statement-level trigger runs once for the whole statement.
- BEFORE triggers can check or change the new values and can stop the operation; AFTER triggers are used for logging and propagating changes; INSTEAD OF triggers apply to views.
- Execution: actions may cascade (a trigger fires other triggers). Rule sets should be terminating (no infinite chain) and confluent (the final state does not depend on the order of rules). When several triggers match, a defined order (creation time or priority) is used. Conditions may be evaluated immediately or deferred until commit.
Applications and Design Principles
Applications: integrity constraints (business rules), audit logs, derived data (updating totals and stock), alerts and notifications, replication and security monitoring. Design principles: keep triggers short and simple, avoid cascades and recursion, test termination, do not use a trigger where a constraint will do, document every trigger and remember that triggers hide logic from application programmers.
Definition: Trigger. A stored rule of the form event-condition-action that the database system executes automatically when a specified event occurs on a table.
Table 4.1: Trigger timing
| Timing | Typical use | Can change new values |
|---|---|---|
| BEFORE | Validate or correct data | Yes |
| AFTER | Audit log, derived data | No |
| INSTEAD OF | Make a view updatable | Replaces the action |
Example 4.1: A stock reorder rule
Problem: A table product(pid, name, qty) holds a pen with quantity 15. A trigger inserts a row into reorder when an update leaves qty below 10. Two sales then reduce the quantity by 4 and by 3. What does the reorder table contain?
Solution:
- The first sale makes qty = 15 - 4 = 11; the condition 11 < 10 is false, so the trigger does nothing.
- The second sale makes qty = 11 - 3 = 8; the condition 8 < 10 is true.
- The action inserts the row (pid 1, qty_left 8) into reorder.
Result: The reorder table contains exactly one row, (1, 8).
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE product(pid INTEGER PRIMARY KEY, name TEXT, qty INTEGER);
CREATE TABLE reorder(pid INTEGER, qty_left INTEGER);
INSERT INTO product VALUES (1, 'Pen', 15);
CREATE TRIGGER low_stock AFTER UPDATE OF qty ON product
WHEN NEW.qty < 10
BEGIN
INSERT INTO reorder VALUES (NEW.pid, NEW.qty);
END;
""")
for sold in (4, 3):
upd = "UPDATE product SET qty = qty - ? WHERE pid = 1"
db.execute(upd, (sold,))
q = db.execute("SELECT qty FROM product").fetchone()[0]
print("After selling", sold, "-> qty", q, "reorder rows:",
db.execute("SELECT * FROM reorder").fetchall())
Output
After selling 4 -> qty 11 reorder rows: []
After selling 3 -> qty 8 reorder rows: [(1, 8)]
Common mistakes
- Writing triggers that fire each other in an endless chain.
- Using an AFTER trigger when a BEFORE trigger is needed to reject bad data.
- Doing heavy processing inside a trigger, which slows every update.
- Forgetting that a row-level trigger runs once per row, not once per statement.
Key takeaways
- Active rules follow event-condition-action.
- Timing: BEFORE, AFTER or INSTEAD OF; granularity: row or statement.
- Oracle uses :OLD and :NEW; DB2 uses REFERENCING OLD and NEW.
- Good rule sets terminate and are confluent.
Practice questions
- What does ECA stand for?
- What is the difference between row-level and statement-level triggers?
- Give two applications of triggers.
Answers to the practice questions
- Event, Condition, Action.
- Row-level runs once for each affected row; statement-level runs once per statement.
- Audit logging and maintaining derived data such as stock.
Sources
- Official BCA syllabus Advanced Database Systems, course code 25BCA406DS04, Unit IV
