Procedures, Functions & Triggers in SQL
Move invariants to the database β carefully
Functions (RETURN values, usable in SQL) vs procedures (CALL side-effects, txn control). Triggers fire per-row/statement (audit history, denormalized sync, INSTEAD OF on complex views). Power with costs: hidden logic, test burden, write amplification. Keep business rules visible; push integrity (audit, guards) that must survive every writer.
Functions return values
Pure calculations callable from SELECT β testable, indexable where immutable.
Procedures run jobs
CALL side-effects with transaction control β backfills, maintenance.
Triggers enforce
AFTER for audit; INSTEAD OF maps complex-view writes. Survive every writer.
Version like code
Migrations + tests + rollback for all three. Hidden logic is tech debt.
1-- INSTEAD OF maps complex-view writes explicitly:2-- CREATE TRIGGER v_write INSTEAD OF INSERT ON v ...
| tool | job |
|---|---|
| functions | values in SQL |
| procedures | jobs with txn control |
| triggers | per-row enforcement |
Pure calculations live in functions callable from SELECT. Multi-step maintenance lives in procedures. Cross-writer invariants (audit) live in triggers β the only layer bugs cannot bypass.
Pure bonus function
Deterministic math in SQL.
1CREATE FUNCTION bonus_calc(s NUMERIC) RETURNS NUMERIC AS $$ SELECT s * 0.1 $$ LANGUAGE sql IMMUTABLE;
| call | result |
|---|---|
| bonus_calc(85000) | 8500 |
Complex-view write map
Explicit write routing where views cannot pass through.
1-- CREATE TRIGGER v_write INSTEAD OF INSERT ON v FOR EACH ROW EXECUTE FUNCTION route_v();
| trigger | job |
|---|---|
| instead-of | writes routed explicitly |
Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.