← Back to Chapters

MySQL Stored Procedures

? MySQL Stored Procedures

? Quick Overview

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.

? Key Concepts

  • Stored procedures are created using CREATE PROCEDURE
  • They support input (IN), output (OUT), and input-output (INOUT) parameters
  • Control-flow statements such as IF, CASE, and loops are supported
  • Executed using the CALL statement
  • Help improve security by restricting direct table access

? Syntax / Theory

Because stored procedures contain multiple SQL statements, MySQL requires a custom delimiter during creation. This prevents the server from prematurely ending the procedure definition.

? View Code Example
-- Basic stored procedure syntax
DELIMITER //

CREATE PROCEDURE procedure_name()
BEGIN
SELECT 'Hello from Stored Procedure';
END //

DELIMITER ;

? Code Example(s)

The following procedure retrieves all records from a table named users. This is commonly used for reusable reporting logic.

? View Code Example
-- 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.

? View Code Example
-- Stored procedure with input parameter
DELIMITER //

CREATE PROCEDURE get_user_by_id(IN uid INT)
BEGIN
SELECT * FROM users WHERE id = uid;
END //

DELIMITER ;

? Live Output / Explanation

Execution Flow

Stored procedures are executed using the CALL keyword. The database processes all internal SQL and returns the result set.

? View Code Example
-- 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.

? Tips & Best Practices

  • Use stored procedures for frequently executed queries
  • Keep procedures focused on a single responsibility
  • Use clear and descriptive procedure names
  • Grant users access to procedures instead of tables

? Try It Yourself

  • Create a stored procedure that inserts a new user record
  • Write a procedure using an IF condition
  • Create a procedure that returns total user count