One of the most valuable real-world uses of triggers is building an automatic audit log. An audit log records every change made to important data, including what changed, who changed it, and when — without requiring any modification to application code.
Design
Create an audit table with columns for the table name, the action (INSERT/UPDATE/DELETE), the affected record ID, a JSON snapshot of old and new values, and a timestamp. Then attach AFTER triggers to each important table.
Benefits
- Captures changes even when made directly via SQL (bypassing the application layer)
- Requires no application code changes
- Provides a reliable history for compliance and debugging
Storing old and new values as JSON (using JSON_OBJECT) provides a flexible schema that works for any table without requiring a separate audit table per table.