Row-level vs Statement-level Triggers in PostgreSQL
📖 Scenario: You are managing a PostgreSQL database for a small online store. You want to track changes to the orders table. Specifically, you want to log each individual order change and also keep a count of how many changes happen in a batch.
🎯 Goal: Build two triggers on the orders table: one row-level trigger that logs each changed order, and one statement-level trigger that counts how many changes happened in a statement.
📋 What You'll Learn
Create an
orders table with columns order_id (integer primary key) and amount (numeric).Create a
log_changes table to store logs of individual order changes with columns order_id and changed_at timestamp.Create a
change_count table to store the count of changes per statement with columns count_id (serial primary key) and change_total integer.Write a row-level trigger function that inserts a row into
log_changes for each changed order.Write a statement-level trigger function that inserts a row into
change_count with the total number of changes in the statement.Attach the row-level trigger to fire AFTER each row update on
orders.Attach the statement-level trigger to fire AFTER the entire UPDATE statement on
orders.💡 Why This Matters
🌍 Real World
Triggers help automate tasks like auditing changes or enforcing rules in databases used by businesses.
💼 Career
Understanding triggers is important for database administrators and backend developers to maintain data integrity and automate workflows.
Progress0 / 4 steps