Consider a PostgreSQL table users with columns id (serial primary key) and username (text). A BEFORE INSERT trigger modifies the NEW.username to uppercase before insertion.
What will be the output of this query after inserting 'alice'?
INSERT INTO users (username) VALUES ('alice');
SELECT username FROM users WHERE id = currval(pg_get_serial_sequence('users','id'));CREATE TABLE users (id SERIAL PRIMARY KEY, username TEXT); CREATE OR REPLACE FUNCTION uppercase_username() RETURNS TRIGGER AS $$ BEGIN NEW.username := UPPER(NEW.username); RETURN NEW; END; $$ LANGUAGE plpgsql; CREATE TRIGGER before_insert_uppercase BEFORE INSERT ON users FOR EACH ROW EXECUTE FUNCTION uppercase_username();
BEFORE triggers can modify the NEW row before it is saved.
The BEFORE INSERT trigger changes NEW.username to uppercase. So the stored username is ALICE.
In PostgreSQL, what happens if a BEFORE UPDATE trigger returns NULL?
Consider this trigger function:
CREATE OR REPLACE FUNCTION cancel_update() RETURNS TRIGGER AS $$ BEGIN RETURN NULL; END; $$ LANGUAGE plpgsql;
And the trigger is attached BEFORE UPDATE on a table. What is the effect on the UPDATE statement?
Returning NULL in a BEFORE trigger means the row is skipped.
In PostgreSQL, if a BEFORE trigger returns NULL, the operation on that row is skipped, so the UPDATE does not happen for that row.
Which of the following is the correct syntax for a PostgreSQL BEFORE INSERT trigger function that modifies the NEW row?
BEFORE triggers must return the modified NEW row.
Option A correctly defines a trigger function returning TRIGGER, modifies NEW, and returns NEW. Option A returns VOID which is invalid. Option A tries to update table inside trigger which is not correct. Option A returns OLD which cancels the insert.
You have a BEFORE INSERT trigger on a table that modifies the NEW row and then inserts into the same table inside the trigger function. What problem can this cause?
How can you optimize or fix this behavior?
Triggers firing themselves repeatedly cause recursion.
Inserting into the same table inside a BEFORE INSERT trigger causes the trigger to call itself repeatedly, causing infinite recursion. To fix, add a condition to skip the trigger logic for internal inserts.
In PostgreSQL, if a BEFORE INSERT trigger is defined FOR EACH ROW, and an INSERT statement inserts multiple rows at once, how does the trigger behave?
Choose the correct statement.
FOR EACH ROW triggers run once per row.
BEFORE INSERT triggers defined FOR EACH ROW execute once for every row inserted, allowing modification of each row individually.