Complete the code to create a BEFORE INSERT trigger that calls the function.
CREATE TRIGGER before_insert_trigger
BEFORE INSERT ON employees
FOR EACH ROW
EXECUTE FUNCTION [1]();The trigger must call the function named before_insert_function which is defined to run BEFORE INSERT.
Complete the code to define a BEFORE UPDATE trigger that modifies the NEW row.
CREATE FUNCTION [1]() RETURNS trigger AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;The function update_timestamp is designed to update the updated_at column before the row is updated.
Fix the error in the trigger function by completing the missing keyword.
CREATE FUNCTION validate_salary() RETURNS trigger AS $$ BEGIN IF NEW.salary < 0 THEN RAISE EXCEPTION 'Salary cannot be negative'; [1] NEW; END; $$ LANGUAGE plpgsql;
In a BEFORE trigger function, you must RETURN NEW to apply the changes to the row.
Fill both blanks to create a BEFORE DELETE trigger that logs the deleted row.
CREATE FUNCTION [1]() RETURNS trigger AS $$ BEGIN INSERT INTO audit_log(table_name, operation, old_data, changed_at) VALUES ('employees', 'DELETE', ROW_TO_JSON([2]), NOW()); RETURN OLD; END; $$ LANGUAGE plpgsql;
The function log_delete logs the old row data before deletion. The OLD keyword refers to the row being deleted.
Fill all three blanks to create a BEFORE INSERT trigger that sets a default value if NULL.
CREATE FUNCTION [1]() RETURNS trigger AS $$ BEGIN IF NEW.status IS NULL THEN NEW.status = [2]; END IF; RETURN [3]; END; $$ LANGUAGE plpgsql;
The function set_default_status sets the status to 'active' if it is NULL, then returns the modified row NEW.