Consider a PostgreSQL table orders with an AFTER INSERT trigger that inserts a record into order_log table. What will be the content of order_log after inserting one row into orders?
CREATE TABLE orders (id SERIAL PRIMARY KEY, product TEXT); CREATE TABLE order_log (order_id INT, action TEXT); CREATE OR REPLACE FUNCTION log_order_insert() RETURNS TRIGGER AS $$ BEGIN INSERT INTO order_log(order_id, action) VALUES (NEW.id, 'inserted'); RETURN NEW; END; $$ LANGUAGE plpgsql; CREATE TRIGGER after_order_insert AFTER INSERT ON orders FOR EACH ROW EXECUTE FUNCTION log_order_insert(); INSERT INTO orders(product) VALUES ('Book'); SELECT * FROM order_log;
AFTER triggers run after the row is inserted, so NEW.id is available.
The AFTER INSERT trigger runs after the row is inserted, so the NEW record has the assigned id. The trigger inserts a log record with that id and action 'inserted'.
Choose the correct statement about when an AFTER trigger executes in PostgreSQL.
Think about the order of BEFORE and AFTER triggers relative to the data change.
AFTER triggers run after the row is modified and before the statement completes, allowing actions that depend on the final data state.
Which option contains a syntax error when creating an AFTER UPDATE trigger in PostgreSQL?
CREATE OR REPLACE FUNCTION update_log() RETURNS TRIGGER AS $$ BEGIN INSERT INTO audit_log(table_name, action) VALUES ('users', 'updated'); RETURN NEW; END; $$ LANGUAGE plpgsql;
Check if the FOR EACH ROW clause is mandatory for row-level triggers.
Option B is missing the FOR EACH ROW clause, which is required for row-level triggers in PostgreSQL.
You have an AFTER DELETE trigger that logs deleted rows into a log table. Which approach optimizes performance best?
Consider how many times the trigger fires and the cost per row.
Statement-level triggers fire once per statement, reducing overhead compared to row-level triggers that fire per row.
You created an AFTER INSERT trigger that queries the same table to count rows. Sometimes, the count does not include the newly inserted row. Why?
Think about transaction isolation and visibility of data within triggers.
AFTER triggers run within the same transaction, but if the trigger queries the table in a way that does not see uncommitted changes (due to isolation levels), it may not see the new row yet.