EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MySQL Tutorial MySQL Stored Procedure
Secondary Sidebar
MySQL Tutorial
  • Functions
    • MySQL Function
    • MySQL Aggregate Function
    • MySQL String functions
    • MySQL Date Functions
    • MySQL Window Functions
    • MySQL Math Functions
    • MySQL Boolean
    • Cursor in MySQL
    • Condition in MySQL
    • MySQL BETWEEN
    • Insert in MySQL
    • MySQL IFNULL()
    • MySQL TIMESTAMPDIFF()
    • MySQL COALESCE()
    • MySQL count()
    • MIN() in MySQL
    • MySQL Numeric
    • MySQL field()
    • MySQL FIND_IN_SET()
    • MySQL avg()
    • MySQL MAX() Function
    • MySQL BIN()
    • MySQL Concat
    • MySQL DECODE()
    • MySQL REGEXP_REPLACE()
    • MySQL Asynchronous
    • MySQL innodb_buffer_pool_size
    • MySQL key_buffer_size
    • MySQL TRUNCATE()
    • MySQL ROW_NUMBER()
    • NOT in MySQL
    • MySQL IN Operator
    • LIKE in MySQL
    • ANY in MySQL
    • MySQL NOT IN
    • MySQL CHECK Constraint
    • MySQL DISTINCT
    • MySQL ALL
    • MySQL Union
    • MySQL UNION ALL
    • MySQL EXISTS
    • MySQL ON DELETE CASCADE
    • MySQL REGEXP
    • MySQL Index
    • MySQL Add Index
    • MySQL REINDEX
    • MySQL UNIQUE INDEX
    • MySQL Clustered Index
    • MySQL? InnoDB Cluster
    • Table in MySQL
    • ALTER TABLE MySQL
    • MySQL Temporary Table
    • MySQL Clone Table
    • MySQL Repair Table
    • MySQL Lock Table
    • MySQL Optimize Table
    • TRUNCATE TABLE MySQL
    • MySQL Table Dump
    • MySQL Update Set
    • MySQL ALTER TABLE Add Column
    • MySQL RANK()
    • MySQL CTE
    • MySQL LAG()
    • MySQL GROUP_CONCAT()
    • MySQL EXTRACT()
    • MySQL REPLACE
    • MySQL AUTO_INCREMENT
    • MySQL SYSDATE()
    • MySQL NULLIF()
    • MySQL Substring
    • MySQL SUBSTRING_INDEX()
    • MySQL LOWERCASE
    • MySQL Row
    • MySQL NOW
    • MySQL CEIL
    • MySQL Alias
    • MySQL Trigger
    • MySQL SHOW Triggers
    • MySQL UPDATE Trigger
    • MySQL DELETE Trigger
    • MySQL AFTER UPDATE Trigger
    • MySQL Stored Procedure
    • ROLLUP in MySQL
    • MySQL? INSTR()
    • MySQL Subquery
    • MySQL Timestamp
    • MySQL? Hour()
    • MySQL MOD()
    • MySQL DATE_FORMAT()
    • ALTER Column in MySQL
    • MySQL Rename Column
    • MySQL Interval
    • MySQL CURDATE
    • MySQL BIT
    • MySQL Binlog
    • MySQL Average
    • MySQL TEXT
    • MySQL SHOW
    • MySQL Offset
    • MySQL Timezone
    • mysql_real_escape_string
    • MySQL Datetime
    • MySQL DATE_SUB()
    • MySQL FULLTEXT
    • MySQL DATE_ADD()
    • MySQL sum()
    • MySQL Merge
    • MySQL BigInt
    • MySQL ROUND
    • MySQL VARCHAR
    • MySQL Decimal
    • MySQL Limit
    • MySQL today()
    • MySQL WEEKDAY
    • MySQL Split
    • MySQL Create Function
    • MySQL BLOB
    • MySQL encode()
    • MySQL Primary Key
    • MySQL Foreign Key
    • Unique Key in MySQL
    • MySQL Drop Foreign Key
    • MySQL DROP TRIGGER
    • MYSQL Database
    • Delete Database MySQL
    • MySQL Root
    • MySQL Root Password
    • MySQL Client
    • MySQL Users
    • MySQL?User Permissions
    • MySQL add user
    • MySQL List User
    • MySQL Show Users
    • MySQL User Password
    • MySQL?Cardinality
    • MySQL Workbench
    • MySQL Backup
    • MySQL REVOKE
    • MySQL Dump
    • MySQL Cluster
    • MySQL Partitioning
    • MySQL Full Text Search
    • MySQL Admin Tool
    • MySQL Export Database
    • MySQL Export to CSV
  • Basic
    • MySQL floor
    • MySQL DESCRIBE table
    • MySQL encryption
    • Introduction to MySQL
    • Is SQL Server a Database?
    • What is MySQL
    • Is MySQL Programming Language
    • MySQL Server
    • MySQL Community Server
    • How To Install MySQL
    • MySQL Versions
    • MySQL OpenSource
    • MySQL GUI Tools
    • MySQL Grant
    • MySQL Error 1064
    • MySQL Drop Database
    • MySQL not equal
    • MySQL SELECT INTO Variable
    • MySQL Commands
    • MySQL Operators
    • What is MySQL Schema
    • Wildcards in MySQL
    • MySQL Constraints
    • MySQL Administration
    • MySQL Data Type
    • MYSQL COMMIT
    • MySQL FORMAT
    • Timestamp to Date in MySQL
    • MySQL DATEDIFF
    • MySQL?Incremental Backup
    • MySQL JSON Data Type
    • MySQL ENUM
    • MySQL Default Port
    • Cheat Sheet MySQL
  • Queries
    • MySQL Queries
    • MySQL Query Commands
    • SELECT in MySQL
    • MySQL INSERT IGNORE
    • MySQL having
    • ORDER BY in MySQL
    • MySQL Cheat Sheet
    • MySQL ORDER BY Random
    • MySQL ORDER BY DESC
    • MySQL GROUP BY
    • MySQL GROUP BY Count
    • MySQL GROUP BY month
    • MySQL WHERE Clause
    • MySQL WITH
    • MySQL FETCH
    • MySQL DDL
    • MySQL DML
    • MySQL WHERE IN Array
    • MySQL Fetch Array
    • MySQL ISNULL
    • MySQL Index Types
    • Mysql? Export Schema
    • Amazon RDS for MySQL
    • MySQL greatest
  • Database
    • What is Data Modeling
    • What is Data Processing
    • DBMS Architecture
    • DBMS Keys
    • Careers in Database Administration
    • What is MySQL Database
    • MySQL Relational Database
    • How to Connect Database to MySQL
    • MySQL Database Repair
    • RDBMS Interview Questions
    • DBMS Interview Questions
  • Joins
    • Joins in MySQL
    • MySQL Outer Join
    • Left Outer Join in MySQL
    • MySQL Self Join
    • Natural Join in MySQL
    • MySQL DELETE JOIN
    • MySQL Update Join
    • MySQL Cross Join
  • Advanced
    • MySQL Formatter
    • MySQL TINYINT
    • MySQL Grant All Privileges
    • MySQL DROP TABLE
    • MySQL rename database
    • MySQL Flush Privileges
    • MySQL super Privilege
    • MySQL Character Set
    • MySQL Log File
    • MySQL Flush Log
    • Grant Privileges MySQL
    • MySQL WHILE LOOP
    • IF Statement in MySQL
    • MySQL CASE Statement
    • MySQL IF Function
    • MySQL IF EXISTS
    • MySQL UUID
    • Views in MySQL
    • MySQL Replication
    • MySQL Partition
    • Toad for MySQL
    • Navicat for MySQL
    • MySQL AES_Encrypt
    • MySQL Performance Tuning
    • MySQL Transaction
    • MySQL? sort_buffer_size
    • MySQL? Sync
    • MySQL? Query Cache
    • MySQL Collation
    • MySQL ODBC Driver
    • MySQL Partitioning
    • MySQL InnoDB
    • MySQL Float vs Decimal
    • MySQL Union vs Union All
  • Interview Questions
    • MySQL Interview Questions

Related Courses

MS SQL Certification Courses

Oracle Certification Courses

PL/SQL Certification Courses

MySQL Stored Procedure

By Payal UdhaniPayal Udhani

MySQL Stored Procedure

Introduction to MySQL Stored Procedure

The stored procedure can be called the subroutine that needs to be called, accepts parameters, and consists of a sequence of database queries that are executed. These queries can be executed on a conditional basis and also looped around using the FOR loop statement. Most of the time, the MySQL stored procedure is used when your application involves certain modules having too many database operations and alterations of the tables, and all this needs o to be performed efficiently within a short timespan.

The stored procedure can allow us to work on multiple databases and execute queries involving tables of one or more than one database. We can even call other stored procedures from certain stored procedures. These stored procedures can be called as many times as you want. Note that stored procedures don’t return any values. In this article, we will learn about the stored procedures in MySQL, how we can create them call them for execution, and drop the stored procedures.

How to Create Stored Procedure in MySQL?

The stored procedure is the subroutine, i.e. a procedure that can be created in MYSQL by using the CREATE PROCEDURE statement.

Let us learn the syntax of creating the stored procedure:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

CREATE PROCEDURE name_of_SP [(nameOfParameter1 datatypeOfParameter1 [,nameOfParameteri datatypeOfParameteri])] BEGIN
// Declaration part of stored procedure
// Execution part of stored procedure
END;

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,171 ratings)

1. name_of_SP: It is the name of the stored procedure that needs to be created in MySQL.

2. NameOfParameter: We can pass the optional parameters to the stored procedures that need to be declared while creating it in the () brackets. A stored procedure can contain none, one or more than one parameter.

These parameters can belong to either of the three types:

  • IN: These types of parameters are assigned the values while calling the stored procedure, and the value cannot be modified or overwritten inside the stored procedure but only referenced and used by the stored procedure.
  • OUT: These are the parameters that can be assigned the values and overridden in the stored procedure but cannot be referenced by it.
  • IN OUT: These types of parameters are assigned the values while calling the stored procedure, and the value can be modified or overwritten inside the stored procedure as well as referenced and used by the stored procedure.

3. BEGIN and END: BEGIN keyword marks the beginning of the stored procedure while END marks the completion of the stored procedure in MYSQL.

4. Declaration part of the stored procedure: We can declare the local variables if we want any in this part of the stored procedure.

5. Execution part of the stored procedure: We can write our program or code in this section of stored procedure that can contain conditional, looping statements, initializing and assigning the value of variables, and preparing and executing the database queries. Calls to other stored procedures can also be included in this part of the stored procedure.

Example to Implement MySQL Stored Procedure

Below are the examples of MySQL Stored Procedure:

1. Let us create one simple stored procedure, but before that, I will create a sample table named last_tran_date that will store the date of the last transaction on the particular object along with its item code and label number using the following query:

CREATE TABLE `last_tran_date` (
`itemCode` int(11) NOT NULL COMMENT 'ItemCode From Item Master',
`LabelNo` int(11) NOT NULL DEFAULT '0' COMMENT 'Generated Label No',
`LastTranDate` date DEFAULT NULL,
KEY `By_item` (`itemCode`,`LabelNo`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

And add some of the values using INSERT statement like the following:

INSERT INTO `last_tran_date` (`itemCode`, `LabelNo`, `LastTranDate`) VALUES('87','8529816','2019-12-03');

2. Let us confirm all the inserted values using the SELECT query:

SELECT * FROM `last_tran_date`;

Output:

MySQL Stored Procedure Example 1

hence 30 rows are present in the last_tran_date table.

Creating the Stored Procedure in MySQL

Now, we will create a stored procedure that will return the label numbers whose last transaction date is passed as the parameter to the GetLabelsOfLastTransDate procedure. Our stored procedure will be as follows:

DELIMITER $$
CREATE PROCEDURE GetLabelsOfLastTransDate(IN last_trans_date DATE)
BEGIN
SELECT
LabelNo
FROM
`last_tran_date
WHERE LastTranDate = last_trans_date ;
END$$
DELIMITER ;

Calling the Stored Procedure in MySQL

Syntax:

The syntax of calling or executing the stored procedure is shown below –

CALL name_of_SP (value of parameters accepted by stored procedure);

In our above example, we can call the GetLabelsOfLastTransDate stored procedure simply by using the following call statement –

CALL GetLabelsOfLastTransDate ('2019-12-01');

The above call to the stored procedure will return the list of all the label numbers whose last transaction was done on the 1st of December of the 2012 year. Executing the above calling statement gives the following output:

The syntax of calling or executing the stored procedure is shown below:

CALL name_of_SP (value of parameters accepted by stored procedure);

In our above example, we can call the  GetLabelsOfLastTransDate stored procedure simply by using the following call statement –

CALL GetLabelsOfLastTransDate ('2019-12-01');

Output:

The above call to the stored procedure will return the list of all the label numbers whose last transaction was done on the 1st of December of the 2012 year. Executing the above calling statement gives the following output:

Calling Statement Example 2

Dropping a Stored Procedure in MySQL

If we want to delete the stored procedure, then we can simply drop it using the following syntax:

DROP procedure [ IF EXISTS ] name_of_SP;

IF EXISTS is the optional statement that can be used to avoid raising the error when no stored procedure with name name_of_SP exists in your database, and you are trying to delete it.

In our above example, we can drop our GetLabelsOfLastTransDate stored procedure using the following statement –

DROP PROCEDURE GetLabelsOfLastTransDate;

Output:

MySQL Stored Procedure Example 3

Pros & Cons of using Stored Procedure in MYSQL

The main advantages of using the stored procedure are that it reduces the traffic in the network as only the name of the stored procedure al the values of the parameter needs to be sent from application server to database server instead of sending multiple long query statements and the sharing of the same business logic written in stored procedures by multiple applications. Besides this, the database administrator can set the privileges to certain users to alter, access, call, and drop the stored procedures.

However, there are some disadvantages of using stored procedures; one of them is it became hard to troubleshoot and debug the stored procedure, and the resources such as CPU might get overused when using many logical operations in MYSQL stored procedures as logical operations are not designed that efficiently in MYSQL.

Conclusion

We can make the use of stored procedures to execute the subroutine that involves many database operations and involve a single purpose. The tables from multiple databases can also be used in queries of MYSQL stored procedures. The advantages of using the stored procedures certainly weigh out more when many logical operations are not involved, and more of the database manipulation queries are involved in your program. They are easy to call and execute.

Recommended Articles

This is a guide to MySQL Stored Procedure. Here we discuss the Introduction of MySQL Stored Procedure and the practical examples and different subquery expressions. You can also go through our suggested articles to learn more –

  1. Introduction to MySQL Operators
  2. Top 23 MySQL String functions
  3. MySQL vs SQLite | Top 14 Comparisons
  4. Guide to MySQL Timestamp
Popular Course in this category
MySQL Training Program (12 Courses, 10 Projects)
  12 Online Courses |  10 Hands-on Projects |  92+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

MS SQL Training (16 Courses, 11+ Projects)4.9
Oracle Training (14 Courses, 8+ Projects)4.8
PL SQL Training (4 Courses, 2+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more