Introduction
A trigger function runs automatically when certain changes happen in a database table. It helps keep data correct or do extra work without you typing commands every time.
Jump into concepts and practice - no test required
CREATE FUNCTION function_name() RETURNS trigger AS $$ BEGIN -- your code here RETURN NEW; -- or RETURN OLD; END; $$ LANGUAGE plpgsql;
CREATE FUNCTION log_update() RETURNS trigger AS $$ BEGIN RAISE NOTICE 'Row updated'; RETURN NEW; END; $$ LANGUAGE plpgsql;
CREATE FUNCTION prevent_negative() RETURNS trigger AS $$ BEGIN IF NEW.amount < 0 THEN RAISE EXCEPTION 'Negative amount not allowed'; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql;
CREATE TABLE accounts ( id SERIAL PRIMARY KEY, balance INT ); CREATE FUNCTION check_balance() RETURNS trigger AS $$ BEGIN IF NEW.balance < 0 THEN RAISE EXCEPTION 'Balance cannot be negative'; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql; CREATE TRIGGER balance_check BEFORE INSERT OR UPDATE ON accounts FOR EACH ROW EXECUTE FUNCTION check_balance(); -- Try to insert a negative balance (this will fail) INSERT INTO accounts (balance) VALUES (-100);
trigger, not standard types like void or integer.CREATE FUNCTION, return type trigger, and use plpgsql language.NEW or OLD row, so RETURN NEW; is correct here.CREATE FUNCTION check_age() RETURNS trigger AS $$
BEGIN
IF NEW.age < 18 THEN
RAISE EXCEPTION 'Age must be 18 or older';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;NEW.age < 18 and raises an exception if true.RETURN NEW; allows insertion.CREATE FUNCTION update_timestamp() RETURNS trigger AS $$ BEGIN NEW.updated_at = NOW(); RETURN NEW END; $$ LANGUAGE plpgsql;
RETURN NEW lacks a semicolon at the end, causing syntax error.last_modified to the current timestamp whenever a row is updated. Which of the following trigger function definitions correctly achieves this?