Using NEW and OLD Records in PostgreSQL Triggers
📖 Scenario: You work for a company that tracks employee salary changes. You want to keep a log of every salary update, recording the old salary and the new salary.
🎯 Goal: Create a PostgreSQL trigger function that uses OLD and NEW records to log salary changes into a separate table whenever an employee's salary is updated.
📋 What You'll Learn
Create a table called
employees with columns id (integer primary key), name (text), and salary (integer).Create a table called
salary_log with columns employee_id (integer), old_salary (integer), new_salary (integer), and changed_at (timestamp).Create a trigger function called
log_salary_change that uses OLD and NEW to insert a record into salary_log when an employee's salary changes.Create a trigger on the
employees table that calls log_salary_change after an update on the salary column.💡 Why This Matters
🌍 Real World
Companies often need to track changes in important data like employee salaries for auditing and historical records.
💼 Career
Understanding triggers and how to use OLD and NEW records is essential for database administrators and backend developers managing data integrity and audit trails.
Progress0 / 4 steps