Stored procedures and functions are powerful features in MySQL that allow developers to encapsulate frequently used SQL code in a reusable manner. They help in improving performance, enforcing business logic, and reducing the need for repetitive code in applications.
A stored procedure is a set of SQL statements that can be stored on the MySQL server and executed as a single block. Stored procedures allow for more complex logic, including conditional statements, loops, and error handling, which can be executed without sending multiple queries from the application.
DELIMITER //
CREATE PROCEDURE procedure_name ([IN|OUT|INOUT] parameter_name data_type, ...)
BEGIN
-- SQL statements go here
END //
DELIMITER ;
Creating a stored procedure that retrieves an employee’s details based on their ID:
DELIMITER //
CREATE PROCEDURE GetEmployeeByID(IN emp_id INT)
BEGIN
SELECT first_name, last_name, department
FROM employees
WHERE employee_id = emp_id;
END //
DELIMITER ;
CALL GetEmployeeByID(1);
DELIMITER //
CREATE PROCEDURE UpdateSalary(INOUT salary DECIMAL(10,2))
BEGIN
SET salary = salary * 1.10; -- Increase salary by 10%
END //
DELIMITER ;
Calling the procedure:
SET @employee_salary = 1000.00;
CALL UpdateSalary(@employee_salary);
SELECT @employee_salary; -- Will return 1100.00
A function in MySQL is similar to a stored procedure but is designed to return a single value. Functions are often used for calculations, string manipulation, and data transformation, and can be called within SQL statements (such as in SELECT queries).
CREATE FUNCTION function_name (parameter_name data_type, ...)
RETURNS return_data_type
BEGIN
-- SQL statements go here
RETURN value;
END;
Creating a function that returns the full name of an employee:
CREATE FUNCTION GetFullName(emp_id INT) RETURNS VARCHAR(255)
BEGIN
DECLARE full_name VARCHAR(255);
SELECT CONCAT(first_name, ' ', last_name) INTO full_name
FROM employees
WHERE employee_id = emp_id;
RETURN full_name;
END;
SELECT GetFullName(1);
CREATE FUNCTION CalculateTax(salary DECIMAL(10,2)) RETURNS DECIMAL(10,2)
BEGIN
RETURN salary * 0.15; -- Returns 15% of the salary as tax
END;
Feature | Stored Procedure | Function |
---|---|---|
Return Type | Can return zero or multiple values (using OUT parameters). | Always returns a single value. |
Usage in SQL Queries | Cannot be used directly in SQL queries. | Can be used in SQL statements like SELECT. |
Call Syntax | Called with CALL statement. | Called like a regular function. |
Purpose | Typically used for more complex logic and multi-step processes. | Used for calculations and transformations. |
Error Handling | Can handle complex error handling using conditions and loops. | Simple, usually focused on calculations or formatting. |
Side Effects | Can modify database state (e.g., INSERT, UPDATE, DELETE). | Cannot modify the database; only returns a value. |