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?"
Practice
BEFORE INSERT trigger in MySQL?Solution
Step 1: Understand the trigger timing
ABEFORE INSERTtrigger runs before the new row is saved to the table.Step 2: Identify the trigger's purpose
It allows you to check or change the data before it is inserted, ensuring data integrity or applying rules.Final Answer:
To modify or validate data before it is inserted into a table -> Option CQuick Check:
BEFORE INSERT triggers run before insert = A [OK]
- Confusing BEFORE INSERT with AFTER INSERT triggers
- Thinking triggers create or delete tables
- Assuming triggers run after data is saved
BEFORE INSERT trigger on a table named users?Solution
Step 1: Identify correct trigger timing and event
The question asks for a BEFORE INSERT trigger, so timing is BEFORE and event is INSERT.Step 2: Check syntax details
Triggers must be defined FOR EACH ROW to access NEW values. CREATE TRIGGER before_insert_users BEFORE INSERT ON users FOR EACH ROW SET NEW.name = UPPER(NEW.name); matches this exactly.Final Answer:
CREATE TRIGGER before_insert_users BEFORE INSERT ON users FOR EACH ROW SET NEW.name = UPPER(NEW.name); -> Option BQuick Check:
BEFORE INSERT + FOR EACH ROW = D [OK]
- Using AFTER instead of BEFORE
- Using BEFORE UPDATE instead of BEFORE INSERT
- Using FOR EACH STATEMENT instead of FOR EACH ROW
CREATE TRIGGER check_age BEFORE INSERT ON employees FOR EACH ROW BEGIN IF NEW.age < 18 THEN SET NEW.age = 18; END IF; END;
What will be the age value after running:
INSERT INTO employees (name, age) VALUES ('Alice', 16);Solution
Step 1: Understand trigger logic
The trigger checks if NEW.age is less than 18, and if so, sets NEW.age to 18 before insert.Step 2: Apply trigger to inserted data
The insert tries to add age 16, which is less than 18, so trigger changes it to 18.Final Answer:
18 -> Option AQuick Check:
Trigger sets age to 18 if less than 18 = 18 [OK]
- Assuming original value 16 is saved
- Expecting an error instead of modification
- Confusing NEW with OLD values
CREATE TRIGGER trg BEFORE INSERT ON orders FOR EACH ROW BEGIN IF NEW.quantity < 1 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Quantity must be positive'; END IF; END;
What error will occur if you run:
INSERT INTO orders (product_id, quantity) VALUES (101, 0);
Solution
Step 1: Analyze trigger condition
The trigger checks if NEW.quantity is less than 1, which is true for 0.Step 2: Understand SIGNAL statement effect
The SIGNAL statement raises a runtime error with the given message, stopping the insert.Final Answer:
Runtime error with message 'Quantity must be positive' -> Option AQuick Check:
SIGNAL raises error if condition met = B [OK]
- Thinking insert succeeds with invalid data
- Confusing SIGNAL with warning
- Assuming syntax error instead of runtime error
products table has a unique SKU code in uppercase. Which BEFORE INSERT trigger code correctly enforces this?Solution
Step 1: Ensure SKU is uppercase before insert
CREATE TRIGGER sku_uppercase BEFORE INSERT ON products FOR EACH ROW BEGIN SET NEW.sku = UPPER(NEW.sku); IF EXISTS (SELECT 1 FROM products WHERE sku = NEW.sku) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Duplicate SKU'; END IF; END; uses SET NEW.sku = UPPER(NEW.sku) in a BEFORE INSERT trigger, correctly modifying the new row.Step 2: Check for duplicate SKU before insert
CREATE TRIGGER sku_uppercase BEFORE INSERT ON products FOR EACH ROW BEGIN SET NEW.sku = UPPER(NEW.sku); IF EXISTS (SELECT 1 FROM products WHERE sku = NEW.sku) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Duplicate SKU'; END IF; END; checks if the SKU already exists and raises an error to prevent duplicates.Step 3: Verify other options
CREATE TRIGGER sku_uppercase AFTER INSERT ON products FOR EACH ROW BEGIN SET NEW.sku = UPPER(NEW.sku); END; uses AFTER INSERT, too late to modify NEW. CREATE TRIGGER sku_uppercase BEFORE INSERT ON products FOR EACH ROW BEGIN SET NEW.sku = LOWER(NEW.sku); END; uses LOWER instead of UPPER. CREATE TRIGGER sku_uppercase BEFORE UPDATE ON products FOR EACH ROW BEGIN SET NEW.sku = UPPER(NEW.sku); END; triggers on UPDATE, not INSERT.Final Answer:
CREATE TRIGGER sku_uppercase BEFORE INSERT ON products FOR EACH ROW BEGIN SET NEW.sku = UPPER(NEW.sku); IF EXISTS (SELECT 1 FROM products WHERE sku = NEW.sku) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Duplicate SKU'; END IF; END; -> Option DQuick Check:
Modify NEW and check duplicates BEFORE INSERT = A [OK]
- Using AFTER INSERT to modify NEW values
- Not checking duplicates before insert
- Modifying SKU to lowercase instead of uppercase
Ready to prove it?
Pass the test and this pattern moves unknown
