Challenge - 5 Problems
Trigger Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
What is the output after updating a row with this trigger?
Consider a table
employees with columns id, salary, and bonus. There is an UPDATE trigger that sets NEW.bonus = OLD.salary * 0.1 before updating the row. If the row with id = 1 has salary = 1000 and bonus = 0, what will be the bonus value after running UPDATE employees SET salary = 1200 WHERE id = 1;?SQL
CREATE TRIGGER update_bonus BEFORE UPDATE ON employees FOR EACH ROW BEGIN SET NEW.bonus = OLD.salary * 0.1; END;
Attempts:
2 left
💡 Hint
Remember that OLD refers to the row before update, NEW is the row after update but before saving.
✗ Incorrect
The trigger uses OLD.salary (1000) to calculate bonus as 1000 * 0.1 = 100, so bonus becomes 100 regardless of the new salary.
🧠 Conceptual
intermediate1:30remaining
Which statement about OLD and NEW in UPDATE triggers is true?
In an UPDATE trigger, what do OLD and NEW represent?
Attempts:
2 left
💡 Hint
Think about what you want to compare or change during an update.
✗ Incorrect
OLD holds the original row data before the update; NEW holds the new data that will be saved.
📝 Syntax
advanced2:00remaining
Which trigger code will cause a syntax error?
Identify the option that will cause a syntax error when creating an UPDATE trigger using OLD and NEW.
Attempts:
2 left
💡 Hint
Can you assign a value to OLD in a trigger?
✗ Incorrect
OLD is read-only in triggers; assigning to OLD.total causes a syntax error.
❓ optimization
advanced2:30remaining
How to optimize an UPDATE trigger that recalculates a column only if a specific column changes?
You have an UPDATE trigger that recalculates the
discount column whenever any column changes. How can you optimize it to recalculate only if price changes?Attempts:
2 left
💡 Hint
Check if the value changed before recalculating.
✗ Incorrect
Using IF NEW.price <> OLD.price avoids unnecessary recalculations when price is unchanged.
🔧 Debug
expert3:00remaining
Why does this UPDATE trigger cause an infinite loop?
Given this trigger code, why does updating the
quantity column cause an infinite loop?
CREATE TRIGGER trg_update_quantity AFTER UPDATE ON inventory
FOR EACH ROW
BEGIN
UPDATE inventory SET quantity = NEW.quantity WHERE id = NEW.id;
END;SQL
CREATE TRIGGER trg_update_quantity AFTER UPDATE ON inventory FOR EACH ROW BEGIN UPDATE inventory SET quantity = NEW.quantity WHERE id = NEW.id; END;
Attempts:
2 left
💡 Hint
Think about what happens when a trigger updates the same table it listens to.
✗ Incorrect
The trigger updates the table on every update, causing itself to fire again and again, creating an infinite loop.