MySQL Stored Procedures: Creating Procedures
Quick Answer
In MySQL, stored procedures are created using the CREATE PROCEDURE statement, which defines a reusable set of SQL statements. Procedures can accept parameters, include control flow, and improve code modularity and performance by executing complex logic on the server side.
Learning Objectives
- Understand the syntax and structure of MySQL stored procedures.
- Learn how to define input and output parameters for procedures.
- Practice creating and calling stored procedures in MySQL.
Introduction to Creating MySQL Stored Procedures
Stored procedures in MySQL allow you to group SQL statements into a single callable routine. This helps in organizing complex logic and reusing code efficiently.
Creating procedures involves defining the procedure name, parameters, and the SQL statements that execute when the procedure is called.
Encapsulate logic once, reuse it many times.
Understanding Stored Procedure Syntax
The basic syntax for creating a stored procedure in MySQL starts with the CREATE PROCEDURE statement, followed by the procedure name and optional parameters.
The procedure body contains SQL statements enclosed within BEGIN and END keywords.
- CREATE PROCEDURE procedure_name ([parameters])
- Procedure parameters can be IN, OUT, or INOUT
- Procedure body contains SQL statements between BEGIN and END
- DELIMITER command is used to change statement delimiter during creation
Using DELIMITER to Define Procedures
MySQL uses the semicolon (;) as the default statement delimiter. When creating procedures, you need to change the delimiter temporarily to avoid premature termination.
Use the DELIMITER command to set a different delimiter before and after the procedure definition.
- Set DELIMITER to // or $$ before CREATE PROCEDURE
- Write the procedure ending with the new delimiter
- Reset DELIMITER back to semicolon after procedure creation
Defining Parameters in Stored Procedures
Parameters allow passing data into and out of stored procedures. MySQL supports three types of parameters:
You specify parameters in the procedure definition inside parentheses after the procedure name.
- IN: Passes a value into the procedure (default)
- OUT: Returns a value from the procedure
- INOUT: Passes a value in and returns a modified value
Example: Creating a Simple Stored Procedure
Let's create a stored procedure that takes an employee ID and returns the employee's name from a sample employees table.
Practical Example
This procedure accepts an employee ID as input and returns the employee's name via an OUT parameter.
Here, we call the procedure with employee ID 101 and retrieve the output parameter value stored in the user variable @name.
Examples
DELIMITER //
CREATE PROCEDURE GetEmployeeName(IN emp_id INT, OUT emp_name VARCHAR(100))
BEGIN
SELECT name INTO emp_name FROM employees WHERE id = emp_id;
END //
DELIMITER ;This procedure accepts an employee ID as input and returns the employee's name via an OUT parameter.
CALL GetEmployeeName(101, @name);
SELECT @name;Here, we call the procedure with employee ID 101 and retrieve the output parameter value stored in the user variable @name.
Best Practices
- Use meaningful procedure and parameter names for clarity.
- Keep procedures focused on a single task for maintainability.
- Handle exceptions and errors inside procedures where possible.
- Use comments to document procedure purpose and parameters.
Common Mistakes
- Forgetting to change the DELIMITER before creating procedures.
- Not specifying parameter modes (IN, OUT, INOUT) correctly.
- Using procedures for simple queries that don't require reuse.
- Ignoring error handling inside procedures.
Hands-on Exercise
Create a Procedure to Calculate Total Sales
Write a stored procedure that accepts a product ID and returns the total sales amount for that product.
Expected output: A procedure that calculates and returns total sales for a given product.
Hint: Use SUM() aggregate function and an OUT parameter for the result.
Modify Procedure to Include Error Handling
Enhance the previous procedure to handle cases where the product ID does not exist by returning zero.
Expected output: Procedure returns zero if no sales found or product ID is invalid.
Hint: Use IF statements and set the OUT parameter accordingly.
Interview Questions
What is the purpose of stored procedures in MySQL?
InterviewStored procedures encapsulate SQL logic on the server side, allowing code reuse, improved performance, and better security by controlling database operations.
How do you define input and output parameters in a MySQL stored procedure?
InterviewParameters are defined with modes: IN for input, OUT for output, and INOUT for both input and output, specified in the procedure declaration.
Why do you need to change the delimiter when creating stored procedures?
InterviewBecause the procedure body contains multiple statements ending with semicolons, changing the delimiter prevents premature termination of the CREATE PROCEDURE statement.
MCQ Quiz
1. What is the best first step when learning Creating Procedures?
A. Understand the purpose and basic idea
B. Skip directly to advanced implementation
C. Ignore examples and practice
D. Memorize terms without context
Correct answer: A
Starting with the purpose and basic idea makes later examples and practice easier to understand.
2. Which activity helps reinforce Creating Procedures?
A. Reading once without practice
B. Building or writing a small practical example
C. Avoiding review questions
D. Skipping the summary
Correct answer: B
A small practical example helps connect the topic to real usage.
3. Which statement is most accurate about this topic?
A. In MySQL, stored procedures are created using the CREATE PROCEDURE statement, which defines a reusable set of SQL statements.
B. Creating Procedures never needs examples
C. Creating Procedures is unrelated to practical work
D. Creating Procedures should be learned without checking results
Correct answer: A
The correct option is based on the available topic explanation.
Key Takeaways
- Stored procedures encapsulate SQL logic for reuse and maintainability.
- CREATE PROCEDURE syntax includes procedure name, parameters, and body.
- Parameters can be IN, OUT, or INOUT to control data flow.
- Procedures improve performance by reducing client-server communication.
- In MySQL, stored procedures are created using the CREATE PROCEDURE statement, which defines a reusable set of SQL statements.
Summary
Creating stored procedures in MySQL involves defining reusable SQL routines with parameters and control flow.
Proper use of DELIMITER and parameter modes is essential for successful procedure creation.
Stored procedures help organize database logic, improve performance, and simplify application development.
Frequently Asked Questions
What is a stored procedure in MySQL?
A stored procedure is a set of SQL statements stored on the server that can be executed repeatedly with parameters.
How do I pass parameters to a MySQL stored procedure?
You define parameters as IN, OUT, or INOUT in the procedure declaration and pass values when calling the procedure.
Why use stored procedures instead of direct SQL queries?
Stored procedures improve performance by reducing client-server communication and enhance security by controlling database operations.





