Stored Procedures and Functions in MySQL
In database management, stored procedures and functions play a significant role in streamlining operations, automating tasks, and improving performance. Both stored procedures and functions allow us to store SQL code that can be executed repeatedly, but they serve slightly different purposes.
1. Stored Procedures
A stored procedure is a collection of SQL statements that are stored in the database and can be executed when required. Stored procedures are often used for repetitive tasks that involve multiple steps, making it easier to automate business processes.
Key Features:
Basic Syntax:
CREATE PROCEDURE procedure_name (parameters)
BEGIN SQL statements;
END;
Example:
Here’s a simple example of a stored procedure to insert data into a table:
CREATE PROCEDURE AddEmployee(IN emp_name VARCHAR(50),
IN emp_salary DECIMAL(10,2))
BEGIN
INSERT INTO employees (name, salary) VALUES (emp_name, emp_salary);
END;
To call the procedure:
CALL AddEmployee('John Doe', 50000.00);
Advantages of Stored Procedures:
2. Functions
A function in MySQL is similar to a stored procedure but with a key distinction—it must return a value. Functions are generally used for computations or transformations where you need a result based on one or more inputs. Unlike procedures, functions can be used in SQL statements like SELECT and can return data directly.
Key Features:
Recommended by LinkedIn
Basic Syntax:
CREATE FUNCTION function_name (parameters)
RETURNS return_data_type
BEGIN SQL statements;
RETURN result;
END;
Example:
Here’s a simple example of a function that calculates the total price after applying a discount:
CREATE FUNCTION CalculateDiscount(price DECIMAL(10,2),
discount DECIMAL(5,2))
RETURNS DECIMAL(10,2)
BEGIN
RETURN price - (price * discount / 100);
END;
To use the function:
SELECT CalculateDiscount(100, 10) AS DiscountedPrice;
Advantages of Functions:
3. Differences Between Stored Procedures and Functions:
4. Best Practices for Using Stored Procedures and Functions:
5. When to Use Stored Procedures vs Functions:
Use Stored Procedures when:
Use Functions when:
Very helpful