Understanding Trigger Execution Order in PostgreSQL
📖 Scenario: You are managing a simple employee database. You want to track changes to employee salaries and log these changes in a separate table. To do this, you will create triggers that execute in a specific order when an employee's salary is updated.
🎯 Goal: Create a table for employees and a table for salary change logs. Then create two triggers on the employees table that execute in a defined order when a salary update happens. The first trigger will log the old and new salary, and the second trigger will update a timestamp column to record when the salary was last changed.
📋 What You'll Learn
Create an
employees table with columns id (primary key), name (text), salary (numeric), and last_salary_change (timestamp).Create a
salary_changes table with columns employee_id, old_salary, new_salary, and change_time.Create a trigger function
log_salary_change that inserts a record into salary_changes when an employee's salary is updated.Create a trigger function
update_last_salary_change that updates last_salary_change column to current timestamp on salary update.Create two triggers on
employees table that fire log_salary_change first, then update_last_salary_change second, both BEFORE UPDATE.Verify the trigger execution order by updating an employee's salary.
💡 Why This Matters
🌍 Real World
Tracking changes in employee salaries is common in HR systems to maintain audit trails and ensure data integrity.
💼 Career
Understanding trigger execution order helps database administrators and developers automate workflows and maintain consistent data states.
Progress0 / 4 steps