HomeMYSQLDifference between a trigger and stored procedure?

Difference between a trigger and stored procedure?

Here’s a clear, detailed comparison between Triggers and Stored Procedures in MySQL:

FeatureTriggerStored Procedure
DefinitionA database object that automatically executes in response to certain events (INSERT, UPDATE, DELETE) on a table.A database object that contains a set of SQL statements and is executed explicitly by the user or application.
ExecutionAutomatic – executes when the triggering event occurs.Manual/Explicit – must be called using CALL procedure_name().
EventsTriggered by DML events (INSERT, UPDATE, DELETE) on a table.Can be executed anytime and can perform any SQL operations, including calling other procedures.
ControlCannot be directly invoked; only runs in response to events.Can be invoked anytime using CALL, giving more control.
ParametersCannot accept parameters directly.Can accept input, output, and input-output parameters.
Use CaseEnforce business rules automatically, maintain audit logs, or replicate changes.Encapsulate repetitive logic, perform batch operations, or modularize code.
Transaction ScopePart of the transaction that fired it; failure can roll back the main transaction (depending on DBMS).Can start its own transaction or be part of a transaction; more flexible.
Return ValueCannot return a value to the caller.Can return values via output parameters or result sets.

Example:

  • Trigger: Automatically logs every deletion from employees table:
CREATE TRIGGER log_employee_delete
AFTER DELETE ON employees
FOR EACH ROW
INSERT INTO employee_audit(emp_id, action_date, action_type)
VALUES (OLD.id, NOW(), 'DELETE');
  • Stored Procedure: Deletes an employee by ID and logs it:
CREATE PROCEDURE delete_employee(IN empID INT)
BEGIN
    DELETE FROM employees WHERE id = empID;
    INSERT INTO employee_audit(emp_id, action_date, action_type)
    VALUES (empID, NOW(), 'DELETE');
END;

Key takeaway:

  • Trigger = automatic response to table events
  • Stored Procedure = manual execution of encapsulated logic

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *