Bird
Raised Fist0
SQLquery~10 mins

Why triggers are needed in SQL - Visual Breakdown

Choose your learning style10 modes available
Concept Flow - Why triggers are needed
Data Change Event
↓
Trigger Activated?
No→No Action
Yes↓
Trigger Code Runs
↓
Automatic Action Performed
↓
Data Updated with Extra Logic
↓
End
When data changes, the system checks if a trigger applies. If yes, it runs extra code automatically to keep data correct or do extra tasks.
Execution Sample
SQL
CREATE TRIGGER update_stock
AFTER INSERT ON sales
FOR EACH ROW
BEGIN
  UPDATE products SET stock = stock - NEW.quantity WHERE id = NEW.product_id;
END;
This trigger runs after a sale is recorded to reduce the stock of the sold product automatically.
Execution Table
StepEventTrigger CheckTrigger ActionData State Change
1Insert new sale recordCheck if 'update_stock' trigger appliesYes, trigger activatesSale record added, stock update starts
2Trigger runsN/AUpdate product stock by subtracting sold quantityProduct stock reduced accordingly
3Finish triggerN/ATrigger endsData consistent with sale recorded
4Next operationNo triggerNo actionData unchanged
💡 No more triggers to run after stock update; data is consistent.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
sale_recordNoneInserted with quantity=3, product_id=101UnchangedUnchangedUnchanged
product_stock505047 (50 - 3)4747
Key Moments - 3 Insights
Why does the trigger run automatically after inserting a sale?
Because the trigger is defined to activate AFTER INSERT on the sales table, as shown in execution_table step 1 where the trigger check is 'Yes'.
What happens if there was no trigger for stock update?
The stock would not change automatically, leading to incorrect data. The trigger ensures stock stays accurate without manual updates (see execution_table step 2).
Can triggers cause changes to other tables?
Yes, triggers can update other tables automatically, like updating the products table stock after a sale (execution_table step 2).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what happens at step 2?
AThe trigger updates the product stock by subtracting the sold quantity
BThe sale record is deleted
CNo trigger runs
DThe stock is increased
💡 Hint
Check the 'Trigger Action' and 'Data State Change' columns at step 2 in execution_table
At which step does the trigger check decide not to run?
AStep 1
BStep 3
CStep 4
DStep 2
💡 Hint
Look for 'No trigger' in the 'Trigger Check' column in execution_table
If the sale quantity was 5 instead of 3, what would be the product_stock after step 2?
A47
B45
C50
D55
💡 Hint
Refer to variable_tracker product_stock changes and subtract quantity from initial stock
Concept Snapshot
Triggers run automatically when data changes.
They perform extra actions like updating related data.
Defined to run BEFORE or AFTER events like INSERT, UPDATE, DELETE.
Help keep data consistent without manual steps.
Useful for enforcing rules and automating tasks.
Full Transcript
Triggers are special database rules that run automatically when data changes. For example, after adding a sale record, a trigger can update the product stock to subtract the sold quantity. This automatic action helps keep data accurate and consistent without needing manual updates. The flow starts with a data change event, checks if a trigger applies, runs the trigger code if yes, performs the automatic action, and ends with updated data. This process ensures related data stays correct and business rules are enforced smoothly.

Practice

(1/5)
1. Why are triggers needed in a database?
Triggers are special procedures that run automatically. What is their main purpose?
easy
A. To write complex queries for reports
B. To manually update data in tables
C. To create new tables in the database
D. To automatically perform actions when data changes happen

Solution

  1. Step 1: Understand what triggers do

    Triggers run automatically when data changes happen in a table, like insert, update, or delete.
  2. Step 2: Identify the main purpose

    The main purpose is to automate actions without manual intervention, such as enforcing rules or logging changes.
  3. Final Answer:

    To automatically perform actions when data changes happen -> Option D
  4. Quick Check:

    Triggers run automatically = D [OK]
Hint: Triggers act automatically on data changes [OK]
Common Mistakes:
  • Thinking triggers are for manual updates
  • Confusing triggers with creating tables
  • Assuming triggers write reports
2. Which of the following is the correct syntax to create a trigger that runs after an INSERT on a table named Employees?
easy
A. CREATE TRIGGER trg AFTER INSERT ON Employees BEGIN ... END;
B. CREATE TRIGGER trg BEFORE UPDATE ON Employees BEGIN ... END;
C. CREATE TRIGGER trg ON Employees AFTER DELETE BEGIN ... END;
D. CREATE TRIGGER trg INSERT AFTER Employees BEGIN ... END;

Solution

  1. Step 1: Identify correct trigger timing and event

    The question asks for a trigger after INSERT on Employees, so syntax must say AFTER INSERT ON Employees.
  2. Step 2: Check syntax structure

    CREATE TRIGGER trg AFTER INSERT ON Employees BEGIN ... END; matches the correct order: CREATE TRIGGER name AFTER INSERT ON table BEGIN ... END;
  3. Final Answer:

    CREATE TRIGGER trg AFTER INSERT ON Employees BEGIN ... END; -> Option A
  4. Quick Check:

    Correct trigger syntax = C [OK]
Hint: Syntax: CREATE TRIGGER name AFTER|BEFORE event ON table [OK]
Common Mistakes:
  • Mixing BEFORE and AFTER keywords
  • Placing table name in wrong position
  • Using ON before event instead of after
3. Consider this trigger on table Orders:
CREATE TRIGGER trg_log AFTER UPDATE ON Orders BEGIN INSERT INTO AuditLog VALUES('Order updated'); END;

What happens when an order is updated?
medium
A. Nothing happens automatically
B. A new row with 'Order updated' is added to AuditLog
C. The Orders table is deleted
D. The update on Orders is canceled

Solution

  1. Step 1: Understand trigger action on UPDATE

    The trigger runs AFTER UPDATE on Orders and inserts a row into AuditLog with text 'Order updated'.
  2. Step 2: Identify the effect of the trigger

    Each time an order is updated, a new row is added to AuditLog recording the event.
  3. Final Answer:

    A new row with 'Order updated' is added to AuditLog -> Option B
  4. Quick Check:

    Trigger inserts log row = B [OK]
Hint: Trigger inserts log row after update [OK]
Common Mistakes:
  • Thinking trigger cancels update
  • Assuming no action happens automatically
  • Confusing trigger with delete operation
4. You wrote this trigger:
CREATE TRIGGER trg_check BEFORE INSERT ON Users BEGIN IF NEW.age < 18 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Age must be 18 or older'; END IF; END;

But it does not prevent inserting users younger than 18. What is the likely error?
medium
A. The trigger does not have a proper delimiter for multiple statements
B. The SIGNAL statement syntax is incorrect
C. The trigger should be AFTER INSERT, not BEFORE
D. Triggers cannot check conditions on NEW data

Solution

  1. Step 1: Analyze trigger structure with multiple statements

    The trigger has IF and SIGNAL inside BEGIN...END, which requires proper statement delimiters (like semicolons) to separate commands.
  2. Step 2: Identify missing delimiter issue

    Without delimiters, the database cannot parse the trigger body correctly, so the condition check fails.
  3. Final Answer:

    The trigger does not have a proper delimiter for multiple statements -> Option A
  4. Quick Check:

    Missing delimiters cause trigger failure = A [OK]
Hint: Use delimiters for multiple statements in triggers [OK]
Common Mistakes:
  • Changing BEFORE to AFTER incorrectly
  • Assuming SIGNAL syntax is wrong without checking
  • Believing triggers can't access NEW data
5. A company wants to ensure that whenever a product's price is updated, the old price is saved in a PriceHistory table automatically. Which trigger design best achieves this?
hard
A. A BEFORE DELETE trigger on Products that inserts old price into PriceHistory
B. An AFTER INSERT trigger on Products that inserts new price into PriceHistory
C. An AFTER UPDATE trigger on Products that inserts old price into PriceHistory
D. A BEFORE UPDATE trigger on Products that inserts old price into PriceHistory

Solution

  1. Step 1: Understand when old price is available

    The old price is available after the update operation starts but before the new data replaces it, so a trigger on UPDATE is needed.
  2. Step 2: Choose trigger timing to save old price

    Using AFTER UPDATE ensures the update succeeded, and the trigger can insert the old price (accessible via OLD) into PriceHistory.
  3. Final Answer:

    An AFTER UPDATE trigger on Products that inserts old price into PriceHistory -> Option C
  4. Quick Check:

    Save old price after update = A [OK]
Hint: Use AFTER UPDATE trigger to save old data changes [OK]
Common Mistakes:
  • Using BEFORE DELETE instead of UPDATE
  • Using AFTER INSERT which doesn't track price changes
  • Choosing BEFORE UPDATE which may block or cause errors
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard