Trigger for audit logging
📖 Scenario: You manage a database for a small company. You want to keep track of any changes made to the employees table. This helps you see who changed what and when.
🎯 Goal: Create a trigger that records every update made to the employees table into an audit_log table. This log will store the employee's ID, old salary, new salary, and the time of change.
📋 What You'll Learn
Create an
employees table with columns id (integer), name (text), and salary (integer).Create an
audit_log table with columns employee_id (integer), old_salary (integer), new_salary (integer), and changed_at (timestamp).Create a trigger function called
log_salary_change that inserts a record into audit_log whenever an employee's salary is updated.Create a trigger called
salary_update_trigger that calls log_salary_change after an update on the employees table.Test the trigger by updating an employee's salary and verify the audit log entry.
💡 Why This Matters
🌍 Real World
Audit logging is important in many companies to track changes in sensitive data like employee salaries. It helps with security and compliance.
💼 Career
Database administrators and DevOps engineers often create triggers for audit logging to ensure data integrity and traceability.
Progress0 / 4 steps