HomeMYSQLStored Procedures and Triggers in MySQL: Complete Guide

Stored Procedures and Triggers in MySQL: Complete Guide

Databases are not just about storing data—they also allow you to automate and encapsulate business logic. Stored procedures and triggers are two powerful features in MySQL that help you achieve this.


1. Stored Procedures

What is a Stored Procedure?

A stored procedure is a set of SQL statements that you can save and reuse. Think of it as a “function” inside your database. Once created, you can call it multiple times with different parameters.

Key Points:

  • Stored in the database.
  • Accepts input parameters and can return output.
  • Helps reduce client-server traffic.
  • Centralizes logic in the database.

Benefits of Stored Procedures

  1. Reusability: Write once, call many times.
  2. Performance: Reduces the amount of SQL sent over the network.
  3. Security: Can restrict direct access to tables; users call procedures instead.
  4. Maintainability: Changes are centralized; no need to modify application code.

Syntax of Stored Procedures

CREATE PROCEDURE procedure_name (IN param1 INT, OUT param2 VARCHAR(50))
BEGIN
    -- SQL statements
    SELECT * FROM employees WHERE id = param1;
    SET param2 = 'Procedure executed';
END;

//EXAMPLE

DELIMITER $$

CREATE PROCEDURE insert_dummy_data()
BEGIN
    DECLARE i INT DEFAULT 1;
    WHILE i <= 100 DO
        INSERT INTO students (name, age, email)
        VALUES (CONCAT('Student', i), FLOOR(18 + RAND()*5), CONCAT('student', i, '@example.com'));
        SET i = i + 1;
    END WHILE;
END $$

DELIMITER ;

CALL insert_dummy_data();

//FOR SELECT

SHOW PROCEDURE STATUS WHERE Db = 'study_db';

//FOR DROP

DROP PROCEDURE IF EXISTS insert_dummy_students;
  • IN – Input parameter
  • OUT – Output parameter
  • INOUT – Both input and output

Example: Simple Stored Procedure

DELIMITER $$

CREATE PROCEDURE GetEmployeeByID(IN empID INT)
BEGIN
    SELECT * FROM employees WHERE id = empID;
END$$

DELIMITER ;

-- Call the procedure
CALL GetEmployeeByID(101);

Explanation:
This procedure retrieves employee details based on the id provided.


Advanced Stored Procedure Example

DELIMITER $$

CREATE PROCEDURE IncreaseSalary(IN empID INT, IN increment DECIMAL(10,2))
BEGIN
    UPDATE employees
    SET salary = salary + increment
    WHERE id = empID;
END$$

DELIMITER ;

-- Call the procedure
CALL IncreaseSalary(101, 5000);

Explanation:
This procedure increases the salary of a specific employee by the given amount.

IN, OUT, and INOUT parameters mean in Stored Procedures Read More


2. Triggers

What is a Trigger?

A trigger is a set of actions that automatically executes in response to certain events on a table, such as INSERT, UPDATE, or DELETE.

Key Points:

  • Executed automatically; you don’t call it manually.
  • Useful for enforcing rules or auditing changes.
  • Can execute before or after an operation.

Benefits of Triggers

  1. Automation: Automatically perform tasks like logging changes.
  2. Data Integrity: Enforce business rules at the database level.
  3. Auditing: Track changes to important tables.
  4. Consistency: Ensure related changes happen simultaneously.

Syntax of Triggers

CREATE TRIGGER trigger_name
BEFORE|AFTER INSERT|UPDATE|DELETE
ON table_name
FOR EACH ROW
BEGIN
    -- SQL statements
END;
  • BEFORE – Trigger runs before the operation.
  • AFTER – Trigger runs after the operation.
  • FOR EACH ROW – Executes for every row affected.

Example: Simple Trigger

DELIMITER $$

CREATE TRIGGER before_employee_insert
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
    SET NEW.created_at = NOW();
END$$

DELIMITER ;

Explanation:
Whenever a new employee is added, this trigger automatically sets the created_at timestamp.


Example: Auditing Trigger

DELIMITER $$

CREATE TRIGGER after_salary_update
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
    INSERT INTO salary_audit(emp_id, old_salary, new_salary, changed_at)
    VALUES (OLD.id, OLD.salary, NEW.salary, NOW());
END$$

DELIMITER ;

Explanation:
Whenever an employee’s salary is updated, this trigger records the change in an audit table.


3. Differences Between Stored Procedures and Triggers

FeatureStored ProcedureTrigger
ExecutionCalled manually using CALLExecutes automatically
TimingAnytime you chooseAutomatically during INSERT, UPDATE, DELETE
ParametersCan accept IN, OUT, INOUT parametersCannot accept parameters
PurposeEncapsulate reusable logicRespond to table events
Use CaseReporting, data manipulation, batch jobsAuditing, enforcing constraints, automatic updates

4. Best Practices

  1. Keep Procedures Small: Avoid large monolithic procedures.
  2. Use Transactions: Ensure data consistency for complex procedures.
  3. Avoid Overusing Triggers: Too many triggers can slow down performance.
  4. Document Your Logic: Both procedures and triggers should be clearly documented.
  5. Security: Limit who can create or execute stored procedures.

5. Conclusion

Stored procedures and triggers are essential tools for robust, efficient, and automated database management.

  • Stored Procedures centralize business logic and reduce client-server load.
  • Triggers automate reactions to data changes, ensuring consistency and auditing.

By mastering these, you can make your MySQL applications faster, safer, and smarter.

What is a Stored Procedure?

A Stored Procedure is a set of SQL statements stored in the database that can be executed repeatedly. It allows you to encapsulate logic in the database, reduce client-server communication, and improve performance.

Why use Stored Procedures?

Reusability: Write once, use multiple times.
Performance: Reduces network traffic.
Security: Can restrict direct access to tables.
Maintainability: Centralized business logic in DB.

How do you call a Stored Procedure?

CALL procedure_name(); — If no parameters
CALL procedure_name(10); — If IN parameter

How to pass parameters?

IN: Send value to procedure.
OUT: Procedure returns value to caller.
INOUT: Send value and get updated value back.
Example:

CREATE PROCEDURE GetStudentName(IN student_id INT, OUT student_name VARCHAR(50)) BEGIN SELECT name INTO student_name FROM students WHERE id = student_id; END;
CALL GetStudentName(1, @name);
SELECT @name;

How to check if a Stored Procedure exists?

SELECT ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE=’PROCEDURE’
AND ROUTINE_SCHEMA=’your_database’
AND ROUTINE_NAME=’procedure_name’;

🔹 Stored Procedure vs Function

FeatureStored ProcedureFunction
Return typeCan return multiple values (using OUT or result sets)Must return a single value (scalar or table)
UsageCalled with CALL procedure_name(...)Used inside SQL (SELECT function_name(...))
TransactionCan use COMMIT and ROLLBACKCannot use transactions
ParametersSupports IN, OUT, INOUTOnly IN parameters
PurposePerforms business logic (insert, update, delete, select)Performs calculations and returns a value
PerformanceUsed for batch operationsUsed for calculations inside queries

🔹 Stored Procedure vs SQL Query

FeatureStored ProcedureSQL Query
DefinitionPrecompiled collection of queries & logicSingle execution of SQL statement
ReusabilityCan be reused multiple times with parametersNeeds to be written/executed each time
PerformanceFaster (precompiled & cached)Slower if same query executed repeatedly
ComplexityCan include conditions, loops, transactionsLimited to a single operation
SecurityCan hide table structure and restrict accessDirectly exposes table details

🔹 Stored Procedure vs Trigger

FeatureStored ProcedureTrigger
ExecutionExplicitly called using CALLImplicitly executed when an event occurs (INSERT, UPDATE, DELETE)
ControlFull control when to runRuns automatically, cannot be manually invoked
Use CaseBusiness logic, data processing, reportingData integrity, auditing, automatic updates
ParametersSupports IN, OUT, INOUTDoes not support parameters
FlexibilityCan include transactions, loops, multiple queriesLimited to reacting to table events

Summary:

  • Use Stored Procedure for reusable business logic.
  • Use Function for returning computed values inside queries.
  • Use SQL Query for one-time execution.
  • Use Trigger for automatic actions when data changes.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

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