Stored procedures are a powerful feature of MySQL that allow you to store and execute a set of SQL statements on the database server. A stored procedure is a named collection of SQL statements that can accept parameters, perform operations (such as querying or updating data), and return results. They help encapsulate complex logic, improve performance, enhance security, and promote code reuse.
In this document, we will cover the detailed concepts, syntax, best practices, and examples related to creating and executing stored procedures in MySQL using the CREATE PROCEDURE statement.
A stored procedure is a precompiled set of one or more SQL statements stored under a name and processed as a unit. Once created, it resides in the database and can be invoked (called) repeatedly by applications or users.
DELIMITER //
CREATE PROCEDURE procedure_name (parameters)
BEGIN
-- SQL statements
END //
DELIMITER ;
Stored procedures can accept three types of parameters:
| Parameter Type | Description | Direction |
|---|---|---|
| IN | Input parameter passed from the caller to the procedure. | Input only |
| OUT | Output parameter that the procedure sets and the caller retrieves. | Output only |
| INOUT | Parameter that is passed in, modified inside the procedure, and passed back to the caller. | Input and output |
This example creates a procedure that returns all records from the employees table.
DELIMITER //
CREATE PROCEDURE GetAllEmployees()
BEGIN
SELECT * FROM employees;
END //
DELIMITER ;
To execute this procedure, you would run:
CALL GetAllEmployees();
This procedure takes a department name as an input and returns employees belonging to that department.
DELIMITER //
CREATE PROCEDURE GetEmployeesByDepartment(IN dept_name VARCHAR(50))
BEGIN
SELECT employee_id, name, department
FROM employees
WHERE department = dept_name;
END //
DELIMITER ;
Example execution:
CALL GetEmployeesByDepartment('Sales');
This procedure counts the number of employees in a specified department and returns the count via an OUT parameter.
DELIMITER //
CREATE PROCEDURE CountEmployeesByDept(
IN dept_name VARCHAR(50),
OUT emp_count INT
)
BEGIN
SELECT COUNT(*) INTO emp_count
FROM employees
WHERE department = dept_name;
END //
DELIMITER ;
To execute and retrieve the OUT parameter value:
CALL CountEmployeesByDept('HR', @count);
SELECT @count;
This example increments a given salary value by a fixed percentage and returns the new salary through an INOUT parameter.
DELIMITER //
CREATE PROCEDURE IncreaseSalary(INOUT salary DECIMAL(10,2))
BEGIN
SET salary = salary * 1.10;
END //
DELIMITER ;
Execution example:
SET @sal = 50000;
CALL IncreaseSalary(@sal);
SELECT @sal;
Stored procedures support typical programming constructs such as:
DELIMITER //
CREATE PROCEDURE GetEmployeeStatus(IN emp_id INT)
BEGIN
DECLARE status VARCHAR(20);
SELECT employment_status INTO status
FROM employees
WHERE employee_id = emp_id;
IF status = 'active' THEN
SELECT 'Employee is active.' AS message;
ELSEIF status = 'inactive' THEN
SELECT 'Employee is inactive.' AS message;
ELSE
SELECT 'Employee status unknown.' AS message;
END IF;
END //
DELIMITER ;
You can declare local variables inside procedures with the DECLARE statement. These variables exist only during the execution of the procedure.
DECLARE var_name datatype [DEFAULT value];
DELIMITER //
CREATE PROCEDURE GetAverageSalary(IN dept VARCHAR(50))
BEGIN
DECLARE avg_salary DECIMAL(10,2);
SELECT AVG(salary) INTO avg_salary
FROM employees
WHERE department = dept;
SELECT avg_salary AS AverageSalary;
END //
DELIMITER ;
The CALL statement is used to invoke stored procedures.
CALL procedure_name([parameters]);
Most programming languages (PHP, Java, Python, etc.) support calling stored procedures via database connectors or APIs, allowing the application to pass parameters and retrieve results seamlessly.
Stored procedures are precompiled and stored on the server, so their execution is faster compared to sending multiple individual SQL queries.
Access rights can be granted on stored procedures instead of tables, controlling what operations users can perform indirectly.
Centralizing SQL logic in procedures reduces duplication and eases maintenance.
Executing multiple statements in a single call reduces client-server roundtrips.
DROP PROCEDURE IF EXISTS procedure_name;
MySQL does not support the ALTER PROCEDURE statement directly. To modify a stored procedure, you must drop and recreate it:
DROP PROCEDURE IF EXISTS procedure_name;
CREATE PROCEDURE procedure_name (parameters)
BEGIN
-- new procedure body
END;
Stored procedures in MySQL are essential tools for encapsulating database logic, enhancing performance, security, and maintainability. Using CREATE PROCEDURE, you can define reusable blocks of SQL statements that accept parameters, perform conditional logic, and return results. Executing these procedures via the CALL statement integrates them into your database workflows effectively.
Mastering stored procedures allows database developers and administrators to build efficient, secure, and robust data-driven applications.
Use the command: CREATE INDEX index_name ON table_name (column_name); to create an index on a MySQL table.
To install MySQL on Windows, download the installer from the official MySQL website, run the setup, and follow the installation wizard to configure the server and set up user accounts.
MySQL is an open-source relational database management system (RDBMS) that uses SQL (Structured Query Language) for managing and manipulating databases. It is widely used in web applications for its speed and reliability.
Use the command: INSERT INTO table_name (column1, column2) VALUES (value1, value2); to add records to a MySQL table.
Use the command: mysql -u username -p database_name < data.sql; to import data from a SQL file into a MySQL database.
DELETE removes records based on a condition and can be rolled back, while TRUNCATE removes all records from a table and cannot be rolled back.
A trigger is a set of SQL statements that automatically execute in response to certain events on a MySQL table, such as INSERT, UPDATE, or DELETE.
The default MySQL port is 3306, and the root password is set during installation. If not set, you may need to configure it manually.
Replication in MySQL allows data from one MySQL server (master) to be copied to one or more servers (slaves), providing data redundancy and load balancing.
A primary key is a unique identifier for a record in a MySQL table, ensuring that no two records have the same key value.
Use the command: SELECT column1, column2 FROM table_name; to fetch data from a MySQL table.
Use the command: CREATE DATABASE database_name; to create a new MySQL database.
Use the command: CREATE PROCEDURE procedure_name() BEGIN SQL_statements; END; to define a stored procedure in MySQL.
Indexing in MySQL improves query performance by allowing the database to find rows more quickly. Common index types include PRIMARY KEY, UNIQUE, and FULLTEXT.
Use the command: UPDATE table_name SET column1 = value1 WHERE condition; to modify existing records in a MySQL table.
CHAR is a fixed-length string data type, while VARCHAR is variable-length. CHAR is faster for fixed-size data, whereas VARCHAR saves space for variable-length data.
MyISAM is a storage engine that offers fast read operations but lacks support for transactions, while InnoDB supports transactions and foreign keys, providing better data integrity.
A stored procedure is a set of SQL statements that can be stored and executed on the MySQL server, allowing for modular programming and code reuse.
Use the command: mysqldump -u username -p database_name > backup.sql; to create a backup of a MySQL database.
Use the command: DELETE FROM table_name WHERE condition; to remove records from a MySQL table.
A foreign key is a column or set of columns in one MySQL table that references the primary key in another, establishing a relationship between the two tables.
Use the command: CREATE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW BEGIN SQL_statements; END; to create a trigger in MySQL.
Normalization in MySQL is the process of organizing data to reduce redundancy and improve data integrity by dividing large tables into smaller ones.
JOIN is used to combine rows from two or more MySQL tables based on a related column, allowing for complex queries and data retrieval.
Use the command: mysqldump -u username -p database_name > backup.sql; to export a MySQL database to a SQL file.
Copyrights © 2024 letsupdateskills All rights reserved