A Stored Procedure in MySQL is a named block of SQL statements stored on the database server. It allows developers to group SQL logic together and execute it repeatedly using a single command. Stored procedures reduce application-side SQL, improve performance, and enforce consistent logic.
CREATE PROCEDUREIN), output (OUT), and input-output (INOUT) parametersIF, CASE, and loops are supportedCALL statementBecause stored procedures contain multiple SQL statements, MySQL requires a custom delimiter during creation. This prevents the server from prematurely ending the procedure definition.
-- Basic stored procedure syntax
DELIMITER //
CREATE PROCEDURE procedure_name()
BEGIN
SELECT 'Hello from Stored Procedure';
END //
DELIMITER ;
The following procedure retrieves all records from a table named users. This is commonly used for reusable reporting logic.
-- Stored procedure to return all users
DELIMITER //
CREATE PROCEDURE get_all_users()
BEGIN
SELECT * FROM users;
END //
DELIMITER ;
Stored procedures can also accept parameters to make them dynamic.
-- Stored procedure with input parameter
DELIMITER //
CREATE PROCEDURE get_user_by_id(IN uid INT)
BEGIN
SELECT * FROM users WHERE id = uid;
END //
DELIMITER ;
Stored procedures are executed using the CALL keyword. The database processes all internal SQL and returns the result set.
-- Executing a stored procedure
CALL get_all_users();
The output displayed is the same as running the SELECT query directly, but with the advantage of reusable and centralized logic.
IF condition