Why do we use triggers in a database system like PostgreSQL?
Think about how to make the database respond by itself when data changes.
Triggers are special procedures that run automatically when data is inserted, updated, or deleted. They help keep data consistent and automate tasks.
Which situation best shows when a trigger is useful?
Triggers help automate tasks that happen right after data changes.
Triggers can run code automatically after data changes, like sending notifications when new data is added.
Given a trigger that updates a 'last_modified' timestamp column whenever a row is inserted or updated, what will be the value of 'last_modified' after inserting a new row?
CREATE TABLE products (id SERIAL PRIMARY KEY, name TEXT, last_modified TIMESTAMP); 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 INSERT OR UPDATE ON products FOR EACH ROW EXECUTE FUNCTION update_last_modified(); INSERT INTO products (name) VALUES ('Book'); SELECT last_modified FROM products WHERE name = 'Book';
The trigger sets the 'last_modified' field to the current time before inserting.
The trigger runs before insert and sets 'last_modified' to NOW(), so the inserted row has the current timestamp.
A developer created a trigger to log deletions on a table, but the trigger never runs. What is the most likely reason?
CREATE OR REPLACE FUNCTION log_delete() RETURNS TRIGGER AS $$ BEGIN INSERT INTO deletions_log(table_name, deleted_id, deleted_at) VALUES ('users', OLD.id, NOW()); RETURN OLD; END; $$ LANGUAGE plpgsql; CREATE TRIGGER trg_log_delete AFTER DELETE ON users FOR EACH ROW EXECUTE FUNCTION log_delete(); -- Then they run: DELETE FROM users WHERE id = 10;
Check if all referenced tables exist and the trigger function runs without errors.
If the deletions_log table is missing, the trigger's insert fails, and the trigger does not complete, so it looks like it never runs.
You have a trigger that runs a complex calculation on every row update in a large table. What is the best way to improve performance without losing the trigger's benefits?
Think about reducing unnecessary trigger executions.
By limiting the trigger to fire only when relevant columns change, you reduce overhead and keep automation.