BEFORE INSERT triggers in MySQL - Time & Space Complexity
We want to understand how the time it takes to run a BEFORE INSERT trigger changes as we add more data.
How does the work inside the trigger grow when many rows are inserted?
Analyze the time complexity of the following code snippet.
CREATE TRIGGER before_insert_example
BEFORE INSERT ON orders
FOR EACH ROW
BEGIN
SET NEW.created_at = NOW();
SET NEW.status = 'pending';
END;
This trigger sets default values for new rows before they are inserted into the orders table.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The trigger runs once for each new row inserted.
- How many times: Exactly once per row, no loops inside the trigger.
Each inserted row causes the trigger to run once, doing a fixed amount of work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 trigger executions |
| 100 | 100 trigger executions |
| 1000 | 1000 trigger executions |
Pattern observation: The work grows directly with the number of rows inserted.
Time Complexity: O(n)
This means the time to run the trigger grows in a straight line with the number of rows inserted.
[X] Wrong: "The trigger runs only once no matter how many rows are inserted."
[OK] Correct: In MySQL, BEFORE INSERT triggers run once for each row, so the work adds up with more rows.
Knowing how triggers scale helps you design efficient databases and avoid surprises when handling many inserts.
"What if the trigger contained a loop that checked all rows in the table? How would the time complexity change?"