Guide to Stored Procedures and Functions in MySQL

Stored procedures allow you to encapsulate complex logic within the database for easy reuse and maintenance. This guide will introduce you to the basics of stored procedures, functions, and triggers in MySQL with practical examples.


Stored Procedures in MySQL

Stored procedures are a set of SQL statements that can be stored in the database. They are useful for repetitive tasks, complex business logic, and reducing network traffic.

Creating Stored Procedures

Example: Creating a Simple Stored Procedure

SQL
DELIMITER //
CREATE PROCEDURE GetAllProducts()
BEGIN    SELECT * FROM Products;
END //
DELIMITER ;

This stored procedure, named GetAllProducts, retrieves all records from the Products table.

Calling a Stored Procedure

SQL
CALL GetAllProducts();

Functions in MySQL

Functions in MySQL are similar to stored procedures but can return a value. They are used to encapsulate frequently used calculations or operations.

Creating Functions

Example: Creating a Simple Function

SQL
DELIMITER //
CREATE FUNCTION GetTotal(Price DECIMAL(10,2), Quantity INT)
RETURNS DECIMAL(10,2)
BEGIN    RETURN Price * Quantity;
END //
DELIMITER ;

This function, GetTotal, takes two arguments (Price and Quantity) and returns the total amount.

Using a Function

SQL
SELECT Name, Price, Quantity, GetTotal(Price, Quantity) AS Total
FROM OrderDetails;

Triggers in MySQL

Triggers are automatic actions that are fired when certain database operations occur (like insert, update, or delete).

Creating Triggers

Example: Creating a Trigger

SQL
DELIMITER //
CREATE TRIGGER BeforeOrderInsert
BEFORE INSERT ON Orders FOR EACH ROW
BEGIN    SET NEW.CreatedAt = NOW();
END //
DELIMITER ;

This trigger, BeforeOrderInsert, automatically sets the CreatedAt field to the current date and time before a new record is inserted into the Orders table.

Combining Stored Procedures, Functions, and Triggers

You can use stored procedures, functions, and triggers together for more complex database operations.

Example: Using a Function Inside a Stored Procedure

SQL
DELIMITER //
CREATE PROCEDURE InsertOrderDetail(ProductID INT, Quantity INT)
BEGIN    DECLARE Price DECIMAL(10,2);    SELECT ProductPrice INTO Price FROM Products WHERE ProductID = ProductID;    INSERT INTO OrderDetails (ProductID, Quantity, Total)    VALUES (ProductID, Quantity, GetTotal(Price, Quantity));
END //
DELIMITER ;

This stored procedure uses the GetTotal function to calculate the total price and insert a record into the OrderDetails table.