← Back to MySQL Course | Chapter 15: Stored Procedures & Functions | Lesson 1 of 5

Stored Procedures

Introduction to Stored Procedures

A stored procedure bundles a group of SQL statements together and saves them inside the database under a name, so that entire sequence can be re-run on demand instead of being retyped or resent from the application every time.

Example: Introduction to Stored Procedures

sql
DELIMITER //
CREATE PROCEDURE GetAllUsers()
BEGIN
  SELECT * FROM users;
END //
DELIMITER ;

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

Calling a Stored Procedure

Once defined, a stored procedure is executed with the CALL statement, which triggers every query saved inside it to run in order as a single unit of work.

Example: Calling a Stored Procedure

sql
CALL GetAllUsers();

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

Dropping a Stored Procedure

DROP PROCEDURE removes a saved procedure permanently. Adding IF EXISTS to the statement prevents an error if the procedure was already deleted or never existed in the first place.

Example: Dropping a Stored Procedure

sql
DROP PROCEDURE IF EXISTS GetAllUsers;

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

Listing Stored Procedures

You can list every stored procedure currently defined in a database, which is a useful way to rediscover what reusable logic is already available before writing new, possibly duplicate, procedures.

Example: Listing Stored Procedures

sql
SHOW PROCEDURE STATUS WHERE Db = DATABASE();

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

Benefits of Stored Procedures

Stored procedures reduce the amount of data sent back and forth over the network since only the CALL and its arguments travel across, and they add a layer of security by hiding table structure details behind a fixed interface.

Example: Benefits of Stored Procedures

sql
-- One CALL travels over the network instead of several separate queries,
-- and the caller never needs to know the underlying table structure.
CALL GetAllUsers();

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.