Create an AFTER Trigger in PostgreSQL
📖 Scenario: You are managing a simple employee database. You want to keep track of every new employee added by recording their name and the time they were added into a separate audit table.
🎯 Goal: Build an AFTER INSERT trigger in PostgreSQL that automatically inserts a record into an audit table whenever a new employee is added.
📋 What You'll Learn
Create a table called
employees with columns id (integer primary key) and name (text).Create a table called
employee_audit with columns employee_name (text) and added_at (timestamp).Create a trigger function called
log_employee_insert that inserts the new employee's name and current timestamp into employee_audit.Create an AFTER INSERT trigger called
after_employee_insert on the employees table that calls the log_employee_insert function.💡 Why This Matters
🌍 Real World
AFTER triggers are used in databases to automatically perform actions like logging, auditing, or updating related tables after data changes happen.
💼 Career
Database developers and administrators use triggers to enforce business rules and maintain data integrity without manual intervention.
Progress0 / 4 steps