Which statement correctly describes the difference between row-level and statement-level triggers in PostgreSQL?
Think about how many times the trigger runs when multiple rows are updated.
Row-level triggers run once for each row affected, allowing row-specific logic. Statement-level triggers run once per statement, regardless of how many rows are affected.
Given a table employees with 3 rows, and a row-level AFTER UPDATE trigger that increments a counter each time it fires, what will be the value of the counter after running UPDATE employees SET salary = salary * 1.1;?
CREATE TABLE employees(id SERIAL PRIMARY KEY, salary NUMERIC); INSERT INTO employees(salary) VALUES (1000), (2000), (3000); CREATE TABLE trigger_log(counter INT); INSERT INTO trigger_log(counter) VALUES (0); CREATE OR REPLACE FUNCTION increment_counter() RETURNS TRIGGER AS $$ BEGIN UPDATE trigger_log SET counter = counter + 1; RETURN NEW; END; $$ LANGUAGE plpgsql; CREATE TRIGGER update_counter AFTER UPDATE ON employees FOR EACH ROW EXECUTE FUNCTION increment_counter(); -- Now run: UPDATE employees SET salary = salary * 1.1;
Remember row-level triggers run once per row updated.
The trigger fires once for each of the 3 rows updated, so the counter increments 3 times.
Which option shows the correct syntax to create a statement-level BEFORE INSERT trigger on table orders in PostgreSQL?
Look for the correct order of clauses and the keyword for statement-level triggers.
Statement-level triggers use FOR EACH STATEMENT. The syntax must specify timing, event, table, and execution function in correct order.
You want to log every update on a large table but only need one log entry per update statement, not per row. Which trigger type is best for performance?
Think about how many times the trigger runs for many rows.
Statement-level triggers run once per statement, reducing overhead compared to row-level triggers that run once per row.
Consider this trigger function and trigger creation:
CREATE OR REPLACE FUNCTION trg_func() RETURNS TRIGGER AS $$
BEGIN
IF NEW.salary > 10000 THEN
RAISE EXCEPTION 'Salary too high';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_check_salary BEFORE UPDATE ON employees
FOR EACH STATEMENT EXECUTE FUNCTION trg_func();Why does this cause an error when updating rows?
Think about what data is available in statement-level triggers.
Statement-level triggers do not have access to row-level variables NEW or OLD, so referencing NEW causes an error.