Bird
Raised Fist0
SQLquery~10 mins

INSERT trigger in SQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - INSERT trigger
New row inserted into table
↓
Trigger fires automatically
↓
Trigger code executes
↓
Trigger can modify data, log, or enforce rules
↓
Insert operation completes
When a new row is inserted, the INSERT trigger runs automatically to perform extra actions before or after the insert.
Execution Sample
SQL
CREATE TRIGGER trg_after_insert
AFTER INSERT ON employees
FOR EACH ROW
BEGIN
  INSERT INTO audit_log VALUES (NEW.id, 'Inserted');
END;
This trigger adds a record to audit_log every time a new employee is inserted.
Execution Table
StepActionTable State BeforeTrigger Fired?Trigger ActionTable State After
1Insert new employee (id=101, name='Alice')employees: empty audit_log: emptyYesInsert (101, 'Inserted') into audit_logemployees: (101, 'Alice') audit_log: (101, 'Inserted')
2Insert new employee (id=102, name='Bob')employees: (101, 'Alice') audit_log: (101, 'Inserted')YesInsert (102, 'Inserted') into audit_logemployees: (101, 'Alice'), (102, 'Bob') audit_log: (101, 'Inserted'), (102, 'Inserted')
3No more insertsemployees: (101, 'Alice'), (102, 'Bob') audit_log: (101, 'Inserted'), (102, 'Inserted')NoNo actionNo change
💡 No more insert operations, trigger does not fire.
Variable Tracker
VariableStartAfter 1After 2Final
employeesempty(101, 'Alice')(101, 'Alice'), (102, 'Bob')(101, 'Alice'), (102, 'Bob')
audit_logempty(101, 'Inserted')(101, 'Inserted'), (102, 'Inserted')(101, 'Inserted'), (102, 'Inserted')
Key Moments - 3 Insights
Why does the trigger fire after each insert and not just once?
Because the trigger is defined FOR EACH ROW, it runs once for every inserted row, as shown in execution_table rows 1 and 2.
Can the trigger modify the inserted row before it is saved?
No, this trigger is AFTER INSERT, so it runs after the row is saved. To modify before saving, a BEFORE INSERT trigger is needed.
What happens if the trigger code fails during execution?
The entire insert operation fails and rolls back, so no partial data is saved. This ensures data consistency.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the state of audit_log after step 2?
Aempty
B(101, 'Alice'), (102, 'Bob')
C(101, 'Inserted'), (102, 'Inserted')
D(102, 'Inserted')
💡 Hint
Check the 'Table State After' column in row 2 of execution_table.
At which step does the trigger NOT fire?
AStep 3
BStep 1
CStep 2
DTrigger fires every step
💡 Hint
Look at the 'Trigger Fired?' column in execution_table.
If the trigger was BEFORE INSERT instead of AFTER INSERT, what would change?
ATrigger would not run at all
BTrigger would run before the row is saved, allowing modification of NEW row data
CTrigger would run after the insert and could not modify data
DTrigger would run only once for all rows
💡 Hint
Consider the timing of BEFORE vs AFTER triggers in the key_moments section.
Concept Snapshot
INSERT trigger runs automatically when a new row is added.
Defined FOR EACH ROW to act on every inserted row.
Can run BEFORE or AFTER insert to modify data or log actions.
Useful for auditing, enforcing rules, or cascading changes.
Trigger failure rolls back the insert to keep data safe.
Full Transcript
An INSERT trigger is a special database feature that runs automatically when a new row is added to a table. It can run before or after the insert operation. In this example, the trigger runs after each new employee is inserted and adds a record to an audit_log table. The execution table shows each insert step, the trigger firing, and the resulting table states. Variables track the employees and audit_log contents after each insert. Key moments clarify why the trigger fires for each row, when it can modify data, and what happens if it fails. The visual quiz tests understanding of trigger timing and effects. Overall, INSERT triggers help automate tasks like logging and data validation during inserts.

Practice

(1/5)
1. What is the main purpose of an INSERT trigger in a database?
easy
A. To update existing rows in a table
B. To automatically run code when a new row is added to a table
C. To delete rows from a table
D. To create a new table

Solution

  1. Step 1: Understand what triggers do

    Triggers are special procedures that run automatically in response to certain events in the database.
  2. Step 2: Focus on INSERT triggers

    An INSERT trigger specifically runs when a new row is added to a table.
  3. Final Answer:

    To automatically run code when a new row is added to a table -> Option B
  4. Quick Check:

    INSERT trigger = runs on new row insert [OK]
Hint: INSERT triggers run on new rows added [OK]
Common Mistakes:
  • Confusing INSERT triggers with UPDATE or DELETE triggers
  • Thinking triggers create or drop tables
  • Believing triggers run manually
2. Which of the following is the correct syntax to create an INSERT trigger in SQL?
easy
A. CREATE TRIGGER trg AFTER INSERT ON table_name FOR EACH ROW BEGIN ... END;
B. CREATE TRIGGER trg BEFORE DELETE ON table_name FOR EACH ROW BEGIN ... END;
C. CREATE TRIGGER trg AFTER UPDATE ON table_name FOR EACH ROW BEGIN ... END;
D. CREATE TRIGGER trg ON table_name INSERT BEGIN ... END;

Solution

  1. Step 1: Identify correct event and timing

    For an INSERT trigger, the event is INSERT and timing can be BEFORE or AFTER. CREATE TRIGGER trg AFTER INSERT ON table_name FOR EACH ROW BEGIN ... END; uses AFTER INSERT which is valid.
  2. Step 2: Check syntax structure

    CREATE TRIGGER trg AFTER INSERT ON table_name FOR EACH ROW BEGIN ... END; uses correct syntax: CREATE TRIGGER name AFTER INSERT ON table FOR EACH ROW BEGIN ... END;
  3. Final Answer:

    CREATE TRIGGER trg AFTER INSERT ON table_name FOR EACH ROW BEGIN ... END; -> Option A
  4. Quick Check:

    Correct INSERT trigger syntax = CREATE TRIGGER trg AFTER INSERT ON table_name FOR EACH ROW BEGIN ... END; [OK]
Hint: INSERT triggers use AFTER or BEFORE INSERT ON table [OK]
Common Mistakes:
  • Using DELETE or UPDATE instead of INSERT
  • Wrong order of keywords
  • Missing FOR EACH ROW clause
3. Given this trigger code:
CREATE TRIGGER trg_log AFTER INSERT ON employees FOR EACH ROW BEGIN INSERT INTO log_table VALUES (NEW.id, NEW.name); END;

What happens when a new employee row is inserted?
medium
A. A new row is added to log_table with the inserted employee's id and name
B. The employees table is deleted
C. The trigger causes a syntax error
D. Nothing happens because NEW is invalid

Solution

  1. Step 1: Understand the trigger action

    The trigger runs AFTER a new row is inserted into employees. It inserts a row into log_table using NEW.id and NEW.name.
  2. Step 2: Confirm NEW usage

    NEW refers to the newly inserted row's values, so the insert into log_table uses correct values.
  3. Final Answer:

    A new row is added to log_table with the inserted employee's id and name -> Option A
  4. Quick Check:

    NEW accesses inserted row data [OK]
Hint: NEW accesses inserted row values inside INSERT triggers [OK]
Common Mistakes:
  • Thinking NEW is invalid outside triggers
  • Assuming trigger deletes data
  • Confusing AFTER and BEFORE timing
4. Identify the error in this trigger:
CREATE TRIGGER trg_check BEFORE INSERT ON orders FOR EACH ROW BEGIN IF NEW.quantity < 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Quantity cannot be negative'; END IF; END;
medium
A. Trigger must be AFTER INSERT, not BEFORE INSERT
B. NEW cannot be used in BEFORE INSERT triggers
C. SIGNAL SQLSTATE is invalid syntax
D. Missing delimiter to separate statements inside BEGIN...END

Solution

  1. Step 1: Check trigger syntax for multiple statements

    Inside BEGIN...END, multiple statements need delimiters (like semicolons) or the delimiter must be changed before creating the trigger.
  2. Step 2: Confirm other parts are valid

    NEW can be used in BEFORE INSERT triggers, SIGNAL SQLSTATE is valid in many SQL dialects, and BEFORE INSERT is allowed.
  3. Final Answer:

    Missing delimiter to separate statements inside BEGIN...END -> Option D
  4. Quick Check:

    Multiple statements need delimiters [OK]
Hint: Use delimiters inside BEGIN...END blocks [OK]
Common Mistakes:
  • Forgetting to change delimiter before trigger creation
  • Misusing NEW in triggers
  • Confusing BEFORE and AFTER timing rules
5. You want to create an INSERT trigger that prevents inserting duplicate email addresses into a users table. Which approach is best?
hard
A. Use a trigger to insert the duplicate email into a log table
B. Use an AFTER INSERT trigger to delete the row if email is duplicate
C. Use a BEFORE INSERT trigger to check if NEW.email exists and raise an error if yes
D. Use a trigger to update the existing row with the new email

Solution

  1. Step 1: Understand when to prevent duplicates

    To stop duplicates before they happen, use a BEFORE INSERT trigger to check if the email already exists.
  2. Step 2: Why other options fail

    AFTER INSERT triggers run after insertion, so deleting duplicates after insert is inefficient and can cause issues. Updating existing rows or logging duplicates does not prevent duplicates.
  3. Final Answer:

    Use a BEFORE INSERT trigger to check if NEW.email exists and raise an error if yes -> Option C
  4. Quick Check:

    Prevent duplicates before insert with BEFORE INSERT trigger [OK]
Hint: Prevent duplicates before insert with BEFORE INSERT trigger [OK]
Common Mistakes:
  • Trying to fix duplicates after insertion
  • Using triggers to update instead of prevent
  • Ignoring unique constraints and relying only on triggers
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