Bird
Raised Fist0
PostgreSQLquery~5 mins

Row-level vs statement-level triggers in PostgreSQL

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction

Triggers help run extra actions automatically when data changes. Row-level triggers run once for each row changed. Statement-level triggers run once for the whole action.

When you want to check or change each row individually after an update.
When you want to log or audit all changes made by a single command at once.
When you want to enforce rules on every row inserted or deleted.
When you want to do a summary action after a batch update or delete.
When you want to avoid repeating the same action many times for each row.
Syntax
PostgreSQL
CREATE TRIGGER trigger_name
{ BEFORE | AFTER | INSTEAD OF }
{ INSERT | UPDATE | DELETE }
ON table_name
[ FOR EACH { ROW | STATEMENT } ]
EXECUTE FUNCTION function_name();

FOR EACH ROW means the trigger runs once per row changed.

FOR EACH STATEMENT means the trigger runs once per SQL command, no matter how many rows it affects.

Examples
This trigger runs after each row in the employees table is updated.
PostgreSQL
CREATE TRIGGER log_update
AFTER UPDATE ON employees
FOR EACH ROW
EXECUTE FUNCTION log_employee_update();
This trigger runs once after any insert or delete command on the orders table, no matter how many rows changed.
PostgreSQL
CREATE TRIGGER audit_changes
AFTER INSERT OR DELETE ON orders
FOR EACH STATEMENT
EXECUTE FUNCTION audit_order_changes();
Sample Program

This example shows two triggers on the products table. One runs after each row update and prints 'Row updated'. The other runs once after the whole update statement and prints 'Update statement executed'.

PostgreSQL
-- Create a simple table
CREATE TABLE products (id SERIAL PRIMARY KEY, name TEXT, price NUMERIC);

-- Create a function to count updated rows
CREATE OR REPLACE FUNCTION count_updates() RETURNS TRIGGER AS $$
DECLARE
  counter INTEGER := 0;
BEGIN
  IF TG_OP = 'UPDATE' THEN
    counter := counter + 1;
  END IF;
  RAISE NOTICE 'Row updated';
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Row-level trigger: runs once per updated row
CREATE TRIGGER product_update_row
AFTER UPDATE ON products
FOR EACH ROW
EXECUTE FUNCTION count_updates();

-- Statement-level trigger function
CREATE OR REPLACE FUNCTION statement_update_notice() RETURNS TRIGGER AS $$
BEGIN
  RAISE NOTICE 'Update statement executed';
  RETURN NULL;
END;
$$ LANGUAGE plpgsql;

-- Statement-level trigger: runs once per update statement
CREATE TRIGGER product_update_statement
AFTER UPDATE ON products
FOR EACH STATEMENT
EXECUTE FUNCTION statement_update_notice();

-- Insert sample data
INSERT INTO products (name, price) VALUES ('Pen', 1.20), ('Notebook', 2.50);

-- Update data to see triggers in action
UPDATE products SET price = price + 1 WHERE id IN (1, 2);
OutputSuccess
Important Notes

Row-level triggers can slow down operations if many rows are affected because they run once per row.

Statement-level triggers are good for actions that only need to happen once per command.

Use RAISE NOTICE in PostgreSQL to see messages during trigger execution for learning or debugging.

Summary

Row-level triggers run once for each row affected by a command.

Statement-level triggers run once for the entire command, no matter how many rows change.

Choose the trigger type based on whether you need per-row or per-command actions.

Practice

(1/5)
1. What is the main difference between a row-level trigger and a statement-level trigger in PostgreSQL?
easy
A. Row-level triggers only work on INSERT; statement-level triggers only work on UPDATE.
B. Row-level triggers execute once per SQL statement; statement-level triggers execute once for each affected row.
C. Row-level triggers execute once for each affected row; statement-level triggers execute once per SQL statement.
D. Row-level triggers cannot modify data; statement-level triggers can modify data.

Solution

  1. Step 1: Understand trigger execution scope

    Row-level triggers run once for every row affected by the SQL command, meaning if 10 rows are updated, the trigger runs 10 times.
  2. Step 2: Understand statement-level trigger behavior

    Statement-level triggers run only once per SQL command, regardless of how many rows are affected.
  3. Final Answer:

    Row-level triggers execute once for each affected row; statement-level triggers execute once per SQL statement. -> Option C
  4. Quick Check:

    Row-level = per row, Statement-level = per statement [OK]
Hint: Row-level = per row; statement-level = per statement [OK]
Common Mistakes:
  • Confusing which trigger runs per row vs per statement
  • Thinking row-level triggers run only once per statement
  • Assuming statement-level triggers run per row
  • Believing trigger types depend on operation type (INSERT/UPDATE)
2. Which of the following is the correct syntax to create a row-level trigger in PostgreSQL?
easy
A. CREATE TRIGGER trg AFTER INSERT ON table FOR EACH ROW EXECUTE FUNCTION func();
B. CREATE TRIGGER trg AFTER INSERT ON table FOR EACH STATEMENT EXECUTE FUNCTION func();
C. CREATE TRIGGER trg AFTER INSERT ON table EXECUTE FUNCTION func();
D. CREATE TRIGGER trg FOR EACH ROW EXECUTE FUNCTION func();

Solution

  1. Step 1: Identify correct trigger syntax

    The syntax for creating a row-level trigger requires the clause FOR EACH ROW to specify it runs per affected row.
  2. Step 2: Check full syntax correctness

    CREATE TRIGGER trg AFTER INSERT ON table FOR EACH ROW EXECUTE FUNCTION func(); correctly includes AFTER INSERT, ON table, FOR EACH ROW, and EXECUTE FUNCTION func(); which is the proper syntax.
  3. Final Answer:

    CREATE TRIGGER trg AFTER INSERT ON table FOR EACH ROW EXECUTE FUNCTION func(); -> Option A
  4. Quick Check:

    Row-level triggers use FOR EACH ROW [OK]
Hint: Row-level triggers always use FOR EACH ROW clause [OK]
Common Mistakes:
  • Omitting FOR EACH ROW for row-level triggers
  • Using FOR EACH STATEMENT for row-level triggers
  • Missing EXECUTE FUNCTION keyword
  • Incorrect order of clauses
3. Consider this trigger function and trigger:
CREATE FUNCTION trg_func() RETURNS trigger AS $$ BEGIN RAISE NOTICE 'Triggered'; RETURN NEW; END; $$ LANGUAGE plpgsql;
CREATE TRIGGER trg AFTER UPDATE ON employees FOR EACH ROW EXECUTE FUNCTION trg_func();
UPDATE employees SET salary = salary * 1.1 WHERE department = 'Sales';
What will be the output when the UPDATE affects 3 rows?
medium
A. The notice 'Triggered' will appear 3 times.
B. The notice 'Triggered' will appear once.
C. No notice will appear because AFTER UPDATE triggers do not raise notices.
D. The notice 'Triggered' will appear once per statement plus once per row.

Solution

  1. Step 1: Identify trigger type and execution count

    The trigger is defined FOR EACH ROW, so it runs once for every row updated.
  2. Step 2: Calculate total trigger executions

    Since 3 rows are updated, the trigger function runs 3 times, each raising the notice 'Triggered'.
  3. Final Answer:

    The notice 'Triggered' will appear 3 times. -> Option A
  4. Quick Check:

    Row-level trigger runs per row = 3 notices [OK]
Hint: FOR EACH ROW triggers run once per affected row [OK]
Common Mistakes:
  • Assuming notice appears only once per statement
  • Confusing FOR EACH ROW with FOR EACH STATEMENT
  • Thinking AFTER UPDATE triggers don't raise notices
  • Believing trigger runs multiple times per row
4. You created a statement-level trigger but it seems to run multiple times when you update multiple rows. What is the most likely cause?
medium
A. PostgreSQL does not support statement-level triggers.
B. Statement-level triggers always run once per row by design.
C. The trigger function contains a loop causing multiple executions.
D. You accidentally defined the trigger as FOR EACH ROW instead of FOR EACH STATEMENT.

Solution

  1. Step 1: Understand trigger definition impact

    If a trigger runs multiple times per row update, it is likely defined as FOR EACH ROW, not FOR EACH STATEMENT.
  2. Step 2: Verify PostgreSQL trigger capabilities

    PostgreSQL supports both row-level and statement-level triggers; statement-level triggers run once per statement.
  3. Final Answer:

    You accidentally defined the trigger as FOR EACH ROW instead of FOR EACH STATEMENT. -> Option D
  4. Quick Check:

    FOR EACH ROW triggers run per row, causing multiple executions [OK]
Hint: Check FOR EACH ROW vs FOR EACH STATEMENT clause [OK]
Common Mistakes:
  • Believing statement-level triggers run per row
  • Ignoring trigger definition syntax
  • Assuming PostgreSQL lacks statement-level triggers
  • Blaming trigger function code without checking trigger type
5. You want to log a summary message once after any UPDATE statement on a table, regardless of how many rows are changed. Which trigger type and timing should you use?
hard
A. A BEFORE UPDATE row-level trigger
B. An AFTER UPDATE statement-level trigger
C. An AFTER UPDATE row-level trigger
D. A BEFORE UPDATE statement-level trigger

Solution

  1. Step 1: Determine trigger timing for logging after update

    Logging after the update completes requires an AFTER trigger.
  2. Step 2: Choose trigger level for single summary message

    To log once per statement regardless of rows, use a statement-level trigger (FOR EACH STATEMENT).
  3. Final Answer:

    An AFTER UPDATE statement-level trigger -> Option B
  4. Quick Check:

    Summary logging = AFTER + statement-level trigger [OK]
Hint: Use AFTER statement-level trigger for single summary action [OK]
Common Mistakes:
  • Using row-level triggers causing multiple logs
  • Using BEFORE triggers missing final state
  • Confusing timing and level for logging
  • Assuming row-level triggers can log once per statement