What are triggers in PostgreSQL?
Answer
A trigger is a function that is automatically called when a specified event (INSERT, UPDATE, DELETE, TRUNCATE) occurs on a table or view. Triggers are created in two steps: (1) create the trigger function that returns TRIGGER: uses NEW (new row data) and OLD (old row data). (2) attach it with CREATE TRIGGER. Timing: BEFORE (can modify NEW), AFTER (sees committed data), INSTEAD OF (for views). Level: FOR EACH ROW or FOR EACH STATEMENT. Example: auto-update updated_at: create a function that sets NEW.updated_at = NOW() and attach as BEFORE UPDATE trigger. Triggers enable audit logging, enforcing complex constraints, and maintaining derived data.
Previous
What is the ON CONFLICT clause (upsert) in PostgreSQL?
Next
What are stored procedures and functions in PostgreSQL?