Audit History & Triggers in SQL
Append-only who-changed-what — compliance backbone
History tables (row versions with valid-from/to + actor) fed by triggers or disciplined app writes answer who changed what, when. Temporal/system-versioned tables automate where supported. Audit writes must be append-only (revoke UPDATE/DELETE on history) to stay trustworthy. Event sourcing replays full state at replay cost.
Version every mutation
History rows carry who/when/old/new — actor from session, diff as JSONB.
Trigger the capture
AFTER UPDATE/DELETE fans history for every writer — consoles included.
Append-only trust
REVOKE UPDATE/DELETE on history — tamper-evident by privilege.
Partition + temporal
Monthly partitions with retention; SYSTEM_TIME as-of where supported.
1-- trigger-maintained history:2-- CREATE TRIGGER audit AFTER UPDATE OR DELETE ON orders FOR EACH ROW EXECUTE FUNCTION log_change();
| layer | guarantee |
|---|---|
| history | append-only versions |
| trigger | cannot be skipped by app bugs |
Every mutation fans a history row with actor + timestamp + diff. App-path audits miss console fixes; trigger-path catches all writers uniformly.
Trigger fan-out (writer-proof)
No app path can skip it.
1CREATE TRIGGER audit AFTER UPDATE OR DELETE ON orders FOR EACH ROW EXECUTE FUNCTION log_change();
| writer | capture |
|---|---|
| app write | history row |
| console fix | history row |
As-of read (portable)
Half-open validity answers June-1st.
1SELECT * FROM prices WHERE product_id = 7 AND valid_from <= '2024-06-01' AND '2024-06-01' < valid_to;
| product_id | price |
|---|---|
| 7 | 99 |
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.