Bird
0
0

Given the following setup:

medium📝 query result Q4 of 15
PostgreSQL - Triggers in PostgreSQL
Given the following setup:
CREATE VIEW v_customer AS SELECT customer_id, customer_name FROM customers;
CREATE FUNCTION trg_v_customer_insert() RETURNS trigger AS $$ BEGIN
INSERT INTO customers(customer_id, customer_name) VALUES (NEW.customer_id, NEW.customer_name);
RETURN NULL;
END; $$ LANGUAGE plpgsql;
CREATE TRIGGER trg_insert INSTEAD OF INSERT ON v_customer FOR EACH ROW EXECUTE FUNCTION trg_v_customer_insert();

What happens when you execute INSERT INTO v_customer VALUES (101, 'Alice');?
AThe trigger causes an infinite loop and the insert never completes.
BThe insert fails because views cannot be directly modified.
CThe insert adds a row to the view but not to the underlying table.
DA new row with customer_id 101 and customer_name 'Alice' is inserted into the customers table.
Step-by-Step Solution
Solution:
  1. Step 1: Understand the trigger function

    The trigger function inserts the NEW row data into the underlying customers table.
  2. Step 2: Trigger execution on insert

    When inserting into the view, the INSTEAD OF trigger fires and runs the function, inserting the data into customers.
  3. Step 3: Result of the insert

    The insert succeeds by adding the row to the base table, even though the view itself is not physically storing data.
  4. Final Answer:

    A new row with customer_id 101 and customer_name 'Alice' is inserted into the customers table. -> Option D
  5. Quick Check:

    INSTEAD OF triggers redirect inserts to base tables [OK]
Quick Trick: INSTEAD OF triggers redirect inserts to base tables [OK]
Common Mistakes:
  • Assuming inserts on views always fail
  • Thinking the view stores data physically
  • Expecting the trigger to modify the view instead of the table

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes