Challenge - 5 Problems
Master of NEW and OLD record access
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of trigger function using OLD and NEW
Consider a PostgreSQL trigger function that logs changes on a table. What will be the output of the following function when an UPDATE occurs changing column
price from 100 to 120?CREATE OR REPLACE FUNCTION log_price_change() RETURNS trigger AS $$ BEGIN RAISE NOTICE 'Price changed from % to %', OLD.price, NEW.price; RETURN NEW; END; $$ LANGUAGE plpgsql;
Attempts:
2 left
💡 Hint
OLD contains the row before the update, NEW contains the row after.
✗ Incorrect
In an UPDATE trigger, OLD holds the original row values, and NEW holds the new values. So the price changed from 100 (OLD.price) to 120 (NEW.price).
🧠 Conceptual
intermediate2:00remaining
Understanding OLD and NEW in DELETE triggers
In a DELETE trigger in PostgreSQL, which of the following statements is true about the availability of OLD and NEW records?
Attempts:
2 left
💡 Hint
Think about what data exists before and after a DELETE.
✗ Incorrect
When a row is deleted, the OLD record holds the row before deletion, but there is no NEW record because the row no longer exists after deletion.
📝 Syntax
advanced2:00remaining
Identify the syntax error in trigger function using OLD and NEW
Which option contains a syntax error in this PostgreSQL trigger function that tries to compare OLD and NEW values?
CREATE OR REPLACE FUNCTION check_update() RETURNS trigger AS $$
BEGIN
IF NEW.value <> OLD.value THEN
RAISE NOTICE 'Value changed';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;Attempts:
2 left
💡 Hint
Check the syntax of IF statements in PL/pgSQL.
✗ Incorrect
In PL/pgSQL, IF statements require THEN keyword after the condition. Option B misses THEN, causing a syntax error.
❓ optimization
advanced2:00remaining
Optimizing trigger function to avoid unnecessary updates
You have a BEFORE UPDATE trigger that updates a timestamp column only if certain columns changed. Which approach is best to avoid unnecessary updates?
Options show different ways to compare OLD and NEW records.
Options show different ways to compare OLD and NEW records.
Attempts:
2 left
💡 Hint
PostgreSQL supports IS DISTINCT FROM for row comparisons.
✗ Incorrect
Using 'NEW IS DISTINCT FROM OLD' compares entire rows safely including NULLs, avoiding multiple OR conditions and unnecessary updates.
🔧 Debug
expert2:00remaining
Debugging a trigger function that causes infinite recursion
A BEFORE UPDATE trigger function updates the same table's row by setting NEW.updated_at = now(). However, this causes infinite recursion and stack overflow. What is the best fix?
Attempts:
2 left
💡 Hint
Think about what causes the trigger to fire repeatedly.
✗ Incorrect
Updating NEW.updated_at unconditionally causes the trigger to fire again. Adding a condition to update only if the timestamp changed prevents recursion.