Consider the following PostgreSQL trigger function and trigger on a table employees:
CREATE OR REPLACE FUNCTION update_last_modified() RETURNS TRIGGER AS $$ BEGIN NEW.last_modified := NOW(); RETURN NEW; END; $$ LANGUAGE plpgsql; CREATE TRIGGER trg_update_last_modified BEFORE UPDATE ON employees FOR EACH ROW EXECUTE FUNCTION update_last_modified();
If a row in employees is updated, what will be the value of last_modified column after the update?
Think about what the trigger function does before returning the new row.
The trigger function sets the last_modified column to the current timestamp using NOW() before the row is updated. It returns the modified NEW row, so the update applies this new timestamp.
Which option contains the correct syntax for creating a trigger function in PostgreSQL?
CREATE OR REPLACE FUNCTION trg_func() RETURNS TRIGGER AS $$ BEGIN -- some logic RETURN NEW; END; $$ LANGUAGE plpgsql;
Check for missing parentheses, semicolons, and correct keywords.
Option C correctly includes parentheses after the function name, the RETURNS clause, the semicolon after END, and the language declaration.
Given this trigger function that updates a last_modified timestamp on every update:
CREATE OR REPLACE FUNCTION update_last_modified() RETURNS TRIGGER AS $$ BEGIN NEW.last_modified := NOW(); RETURN NEW; END; $$ LANGUAGE plpgsql;
How can you optimize it to only update last_modified if some column other than last_modified actually changed?
Think about how to detect changes between OLD and NEW rows.
By comparing OLD and NEW rows for changes excluding last_modified, the trigger can avoid unnecessary updates and reduce write load.
Consider this trigger function and trigger on table orders:
CREATE OR REPLACE FUNCTION trg_update_total() RETURNS TRIGGER AS $$ BEGIN NEW.total := NEW.quantity * NEW.price; RETURN NEW; END; $$ LANGUAGE plpgsql; CREATE TRIGGER trg_update_total BEFORE UPDATE ON orders FOR EACH ROW EXECUTE FUNCTION trg_update_total();
Updating any row in orders causes an infinite loop. Why?
Think about what happens when a trigger modifies the row it is triggered on.
The trigger modifies the row during an update, which causes the update to fire the trigger again, creating an infinite loop of updates.
Choose the correct statement about trigger functions in PostgreSQL.
Consider the flexibility of languages and return types for trigger functions.
Trigger functions in PostgreSQL can be written in any supported language (like plpgsql, plpython, etc.) but must always return type TRIGGER.