How to use MySQL Stored Procedures

Introduction

MySQL Stored Procedures is a very powerful programming tool that is becoming commonly used by database professionals to create reusable code that can be executed directly on the database server to save time. To develop reliable and effective database applications, stored procedures are considered an essential tool, as they can enhance performance, lower network traffic, and simplify the development process. In this article, we will explore MySQL stored procedures, how to use them, and how we can make our own stored procedure with some practical use cases.

What IS MySQL Stored Procedure?

During the creation of databases, many queries are often written by database creators to manipulate the database repeatedly. This increases the repeated use of the same queries again and again over time. MySQL Stored Procedures are database objects that contain those precompiled SQL statements used by the Database Admin repeatedly or are to be used in the future. So that the entire query can be made reusable and executed on demand, they provide a mechanism to group database operations into a single object that can be invoked from many different clients and applications. Stored procedures are supported by RDBMS(Relational Database Management System) and are used to simplify the code, enhance database security and improve application performance.

How Stored Procedures Work?

Database developers create stored procedures using a specific syntax defined by the database management system only for stored procedures. Stored procedures can be accessed by any client working on any device after the procedure is created if the client has access to that database. Before executing a stored procedure, it is first parsed and compiled by the database server and then called by the user when required for execution. A stored procedure's working can be compared to the working of a normal method/function in a normal programming language. Stored procedure execution is faster than normal queries, as after a stored procedure is compiled, its execution plan is stored in the memory so that faster execution can be performed in the future.

Stored Procedures can take input parameters, which can be used as arguments while executing the SQL statements written within the procedures, just like normal methods or functions. They can also have a return type parameter, i.e., return output parameters, which can be used to communicate data back to the calling application.

Creating Stored Procedures in MySQL

To use a stored procedure, the procedure must be created first in the database. We can easily create a stored procedure just by writing a simple statement in MySQL, which is CREATE PROCEDURE procedure_name().

Syntax

CREATE PROCEDURE procedure_name()
BEGIN
     --Our SQL Statements goes over here
END;

CREATE PROCEDURE is the keyword used to define a procedure, procedure_name is a user-defined name for the stored procedure, which is used to call the procedure in the future by the user, BEGIN defines the start of the procedure block, and the END keyword defines the end of the procedure block. All the queries written inside BEGIN and END are considered to be the definition of the stored procedure.

For example-  We want to create a stored procedure to show two tables, "users and admin". Here's how we can do it,

CREATE PROCEDURE show_result()
BEGIN
    SELECT * from users,admin;
END;

In the above example, we created a stored procedure named show_result which shows all the fields and data inside user and admin tables. 

Once a stored procedure is created, it can be accessed by any user and used if the user has access to the database. To execute the store procedure created within a database, we just need to call the procedure using the CALL keyword, with the procedure name just like calling a normal function.

Here's how we can use the CALL statement to execute the stored procedure,

CALL show_result();

Just by writing the above-mentioned code, both the users and admin table will be displayed.

Output 

StoredProcedure

Using Parameters

Stored procedures can contain a parameter list; in other words, we can say that stored procedures can both take parameters to be used within the queries written inside its block as well as return values, just like a normal function that we use in other programming languages. To use parameterized stored procedures, we use IN, OUT, or INOUT keywords, where IN keyword represents that the argument's value is to be used inside the procedure's block, the OUT keyword is used before return type arguments, whereas the INOUT keyword is used before arguments which show both the personalities, i.e. the data inside those arguments are used in the block as well as the arguments data is to be modified and then returned to the user who called the procedure.

Syntax

CREATE PROCEDURE procedure_name(IN parameter1 INT, OUT parameter2 varchar(50))
BEGIN
          --code over here
END;

Here, parameter1 is an input type parameter as we used IN keyword before it; parameter1 is holding data of integer type, whereas the second parameter, parameter2, is an OUT or return type parameter having a varchar data type. 

For example- Let's say we are creating a stored procedure to take in student into a table "Students" which has two columns, "Student_name and Student_Email_id" and also an auto-incremented column "Student_id", let's make the stored procedure.

CREATE PROCEDURE insert_info(IN Student_name VARCHAR(50), IN Student_email VARCHAR(50))
BEGIN
    INSERT INTO Students(Student_name,Student_Email_id)VALUES(Student_name,Student_email)
END;

In this example, we've defined a Stored Procedure name insert_info which takes in two IN parameters, Student_name and Student_email, and then stores the values present inside the parameters to the column of the Students table named Student_name and Student_Email_id.

To call a parameterized stored procedure, we just have to write the CALL statement with just the parameter list.

CALL insert_info('Ritik Mishra','[email protected]')

This will call the stored procedure "insert_info" which will store the student name and email id to the table Students.

Advantages of Stored Procedures

  1. Increased application performance
    Stored procedures boost application performance by reducing the network traffic between the client user and the database server. Stored procedures are compiled and stored in the memory of the database. Thus, they are executed in much less time than dynamically created SQL statements.
  2. Reusability
    Stored procedures, once created, can be reused multiple times by multiple clients and applications, which reduces development time and simplifies the code. 
  3. Increased security
    Stored procedures are used to enhance security by restricting the access of unauthorized users to sensitive data and operations within the database. 
  4. Easy to maintain
    Stored procedures are much easier to maintain as they are stored in the memory. Thus, the database queries can be modified if any requirement is needed in the future without changing the application code. This makes maintenance and upgrades much easier and error-prone.
  5. Reduces Network Traffic
    MySQL Stored procedures reduce network traffic as it allows multiple queries to be executed in a single block of code as a single unit. The procedures are compiled and stored in the memory and can be called as many times as needed, but calling every time does not need the procedure to be compiled again and again.

Disadvantages of Stored Procedures

  1. Complexity
    Stored procedures are difficult to develop and maintain; only skilled professionals can easily maintain the database management system.
  2. Less Portable
    Stored procedures are less portable, they are created and belong to a single database, and they cannot be used in different databases.
  3. Difficult to Debugging
    Debugging a stored procedure can be difficult because stored procedures are performed within the database server and are not visible to the caller application; thus, debugging them can be tricky.

Practical Use Cases for Stored Procedures

Stored Procedures can be used by a database base developer in a variety of ways to enhance the performance and functionality of a database application. Below are some practical use case examples,

  1. Data Validation
    Stored procedures are widely used in validating data fields before inserting and updating them into the database, for example. We can create a stored procedure name login which takes the username and password and checks the validation of the user, and give access to the inner information of the site.
  2. Business Logic
    Stored procedures can be used to implement complex business logic that is specific to one application, for example. Let's suppose we need to calculate the salary of employees using some complex mathematical process; then, we can just create a stored procedure that can be called again and again by different users; this will reduce the time of writing the same complex query again and again.
  3. Complex Queries
    Procedures can be used to encapsulate difficult and complex queries and make them easier to maintain and use. 

Conclusion

MySQL Stored Procedures is a powerful tool that helps the database developer to use reusable code for faster execution of SQL queries and enhance the performance of the database. Creating stored procedures and using them is very easy; we just need to follow the syntax and write efficient queries within its block. By using stored procedures, we can reduce the execution and compilation time of the queries and can be saved from writing similar and same complex queries repeatedly. We are ready to use the stored procedures now in our database and increase its efficiency.

FAQ's

Q1. What are MySQL Stored Procedures, and why are they important?
A. MySQL Stored Procedures are precompiled SQL statements that can be used repeatedly, to reduce the development process's complexity, enhance performance, and lower network traffic. They are essential tools that can be used to simplify the code, enhance database security and improve application performance.

Q2. How do MySQL Stored Procedures work?
A. MySQL Stored Procedures work by grouping database operations into a single object that can be invoked from many different clients and applications, thus making the query reusable and executed on demand. Stored procedures are parsed and compiled by the database server before execution, and the execution plan is stored in memory for future faster execution. 

Q3. How can we create a MySQL Stored Procedure?
A. To create a MySQL Stored Procedure, we need to use the CREATE PROCEDURE statement, followed by the procedure's name, and then define the procedure's SQL statements within the BEGIN and END block. Once created, the Stored Procedure can be accessed by any user if they have access to the database by calling the procedure with the CALL statement.

Q4. Can MySQL Stored Procedures have parameters?
A. Yes, MySQL Stored Procedures can have parameters, and they can be used to pass arguments to the procedure's SQL statements.

Q5. What is the syntax for creating a parameterized MySQL Stored Procedure?
A. The syntax for creating a parameterized MySQL Stored Procedure is similar to that of creating a regular Stored Procedure. However, we need to specify the parameters' names and types along with the IN, OUT, or INOUT keywords. Like,

CREATE PROCEDURE procedure_name(IN parameter1 INT, OUT parameter2 varchar(50))
BEGIN
-- SQL statements go here
END;

 


Similar Articles