Lesson 57 of 60 – MySQL Stored Procedures
95%

MySQL Stored Procedures

A Stored Procedure is a set of SQL statements stored inside the MySQL database. It can be executed whenever required using the CALL statement.

Note: Stored procedures are useful for grouping reusable database operations, accepting parameters, applying logic, and reducing repeated SQL code.

1. What is a Stored Procedure?

A stored procedure is a named collection of SQL statements saved in the database.

Instead of writing the same SQL statements repeatedly, you can store them inside a procedure and execute the procedure whenever needed.

CALL procedure_name();

2. Why Use Stored Procedures?

Stored procedures can be useful when database operations need to be reused.

  • Reuse SQL logic.
  • Reduce repeated SQL code.
  • Accept input parameters.
  • Return output values through OUT parameters.
  • Perform multiple SQL operations together.
  • Use variables and conditional logic.
  • Use loops for repetitive database operations.

3. Basic CREATE PROCEDURE Syntax

The basic syntax is:

CREATE PROCEDURE procedure_name()
BEGIN
    SQL statements;
END;

Because a procedure can contain multiple SQL statements, the BEGIN and END block is commonly used.

4. Creating a Simple Procedure

Suppose we have a students table:

CREATE PROCEDURE get_students()
BEGIN
    SELECT *
    FROM students;
END;

This procedure retrieves all students when it is called.

5. DELIMITER

MySQL normally uses ; as the statement delimiter. A procedure can contain several statements ending with semicolons, so the delimiter is temporarily changed while creating the procedure.

DELIMITER //

CREATE PROCEDURE get_students()
BEGIN
    SELECT * FROM students;
END //

DELIMITER ;

The delimiter is changed back after the procedure is created.

6. Calling a Stored Procedure

Use the CALL statement to execute a stored procedure.

CALL get_students();

When called, the procedure executes its stored SQL statements.

7. Procedure with an IN Parameter

An IN parameter allows a value to be passed into a procedure.

DELIMITER //

CREATE PROCEDURE get_student(IN sid INT)
BEGIN
    SELECT *
    FROM students
    WHERE student_id = sid;
END //

DELIMITER ;

Call it using:

CALL get_student(10);

8. IN Parameter

The IN keyword indicates that the parameter receives a value from the caller.

CREATE PROCEDURE find_student(IN student_name VARCHAR(100))
BEGIN
    SELECT *
    FROM students
    WHERE name = student_name;
END;

Example:

CALL find_student('Amit Kumar');

9. Procedure with an OUT Parameter

An OUT parameter allows a procedure to return a value to the caller.

DELIMITER //

CREATE PROCEDURE count_students(OUT total INT)
BEGIN
    SELECT COUNT(*)
    INTO total
    FROM students;
END //

DELIMITER ;

Call it using a session variable:

CALL count_students(@total);

SELECT @total;

10. INOUT Parameter

An INOUT parameter can receive a value and also return an updated value.

DELIMITER //

CREATE PROCEDURE increase_value(INOUT amount INT)
BEGIN
    SET amount = amount + 100;
END //

DELIMITER ;

Call it using:

SET @amount = 500;

CALL increase_value(@amount);

SELECT @amount;

The resulting value is 600.

11. Procedure with Multiple Parameters

A procedure can have multiple parameters.

DELIMITER //

CREATE PROCEDURE search_students(
    IN student_city VARCHAR(100),
    IN student_status VARCHAR(20)
)
BEGIN
    SELECT *
    FROM students
    WHERE city = student_city
    AND status = student_status;
END //

DELIMITER ;

Call it:

CALL search_students('Patna', 'Active');

12. Procedure with INSERT

A stored procedure can insert data into a table.

DELIMITER //

CREATE PROCEDURE add_student(
    IN student_name VARCHAR(100),
    IN student_email VARCHAR(150)
)
BEGIN
    INSERT INTO students
    (name, email)
    VALUES
    (student_name, student_email);
END //

DELIMITER ;

Call:

CALL add_student(
    'Rahul Sharma',
    'rahul@example.com'
);

13. Procedure with UPDATE

DELIMITER //

CREATE PROCEDURE update_student_status(
    IN sid INT,
    IN new_status VARCHAR(20)
)
BEGIN
    UPDATE students
    SET status = new_status
    WHERE student_id = sid;
END //

DELIMITER ;

Call:

CALL update_student_status(10, 'Active');

14. Procedure with DELETE

A procedure can also delete records.

DELIMITER //

CREATE PROCEDURE delete_student(IN sid INT)
BEGIN
    DELETE FROM students
    WHERE student_id = sid;
END //

DELIMITER ;

Call:

CALL delete_student(10);
Warning: DELETE procedures should be designed carefully because they can permanently remove data after the transaction is committed.

15. Local Variables

A stored procedure can declare local variables using DECLARE.

DELIMITER //

CREATE PROCEDURE student_count()
BEGIN
    DECLARE total INT;

    SELECT COUNT(*)
    INTO total
    FROM students;

    SELECT total AS total_students;
END //

DELIMITER ;

Variables declared inside a procedure are local to that procedure.

16. SET Statement

The SET statement can assign values to variables.

DELIMITER //

CREATE PROCEDURE test_variable()
BEGIN
    DECLARE total INT;

    SET total = 100;

    SELECT total;
END //

DELIMITER ;

Call:

CALL test_variable();

17. IF Statement

Stored procedures can use conditional logic.

DELIMITER //

CREATE PROCEDURE check_marks(IN marks INT)
BEGIN

    IF marks >= 40 THEN
        SELECT 'Pass' AS result;
    ELSE
        SELECT 'Fail' AS result;
    END IF;

END //

DELIMITER ;

Call:

CALL check_marks(75);

18. IF ELSEIF ELSE

A procedure can use multiple conditions.

DELIMITER //

CREATE PROCEDURE student_grade(IN marks INT)
BEGIN

    IF marks >= 80 THEN
        SELECT 'A' AS grade;

    ELSEIF marks >= 60 THEN
        SELECT 'B' AS grade;

    ELSEIF marks >= 40 THEN
        SELECT 'C' AS grade;

    ELSE
        SELECT 'Fail' AS grade;

    END IF;

END //

DELIMITER ;

19. CASE Statement

The CASE statement can be used for multiple conditional results.

DELIMITER //

CREATE PROCEDURE student_grade_case(IN marks INT)
BEGIN

    SELECT
        CASE
            WHEN marks >= 80 THEN 'A'
            WHEN marks >= 60 THEN 'B'
            WHEN marks >= 40 THEN 'C'
            ELSE 'Fail'
        END AS grade;

END //

DELIMITER ;

20. WHILE Loop

A WHILE loop repeats statements while a condition is true.

DELIMITER //

CREATE PROCEDURE print_numbers()
BEGIN

    DECLARE counter INT DEFAULT 1;

    WHILE counter <= 5 DO

        SELECT counter;

        SET counter = counter + 1;

    END WHILE;

END //

DELIMITER ;

Call:

CALL print_numbers();

21. LOOP Statement

The LOOP statement creates a loop that can be stopped using LEAVE.

DELIMITER //

CREATE PROCEDURE loop_example()
BEGIN

    DECLARE counter INT DEFAULT 1;

    number_loop: LOOP

        SELECT counter;

        SET counter = counter + 1;

        IF counter > 5 THEN
            LEAVE number_loop;
        END IF;

    END LOOP;

END //

DELIMITER ;

22. REPEAT Loop

The REPEAT statement executes its statements until the condition becomes true.

DELIMITER //

CREATE PROCEDURE repeat_example()
BEGIN

    DECLARE counter INT DEFAULT 1;

    REPEAT

        SELECT counter;

        SET counter = counter + 1;

    UNTIL counter > 5
    END REPEAT;

END //

DELIMITER ;

23. SHOW CREATE PROCEDURE

You can view the SQL definition of a stored procedure using:

SHOW CREATE PROCEDURE get_students;

This is useful when you want to inspect how the procedure was created.

24. SHOW PROCEDURE STATUS

You can view stored procedure information using:

SHOW PROCEDURE STATUS;

You can filter the result by database:

SHOW PROCEDURE STATUS
WHERE Db = 'schooldb';

25. Dropping a Procedure

Use DROP PROCEDURE to remove a stored procedure.

DROP PROCEDURE get_students;

After dropping it, the procedure can no longer be called.

26. DROP PROCEDURE IF EXISTS

To avoid an error when the procedure does not exist, use:

DROP PROCEDURE IF EXISTS get_students;

This is commonly useful when recreating procedures during development.

27. Stored Procedure with Transaction

A stored procedure can contain transaction statements when appropriate.

DELIMITER //

CREATE PROCEDURE transfer_money(
    IN from_account INT,
    IN to_account INT,
    IN amount DECIMAL(12,2)
)
BEGIN

    START TRANSACTION;

    UPDATE accounts
    SET balance = balance - amount
    WHERE account_id = from_account;

    UPDATE accounts
    SET balance = balance + amount
    WHERE account_id = to_account;

    COMMIT;

END //

DELIMITER ;

Call:

CALL transfer_money(1, 2, 1000.00);

28. Stored Procedures vs Normal SQL

Normal SQL Stored Procedure
Statements are sent individually by the application. SQL logic can be stored in the database.
Repeated logic may need to be sent again. Reusable logic can be called by name.
Application usually controls the flow. Procedure can contain SQL control flow.
Parameters are handled by application code. Procedures can define IN, OUT, and INOUT parameters.

29. Practical Student Management Procedure

Suppose an application frequently searches students by city.

DELIMITER //

CREATE PROCEDURE get_students_by_city(
    IN student_city VARCHAR(100)
)
BEGIN

    SELECT
        student_id,
        name,
        email,
        city,
        status
    FROM students
    WHERE city = student_city
    ORDER BY name;

END //

DELIMITER ;

Call:

CALL get_students_by_city('Patna');

This procedure can be reused whenever the application needs students from a particular city.

30. Complete Stored Procedure Example

CREATE TABLE students (
    student_id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(150),
    city VARCHAR(100),
    status VARCHAR(20)
);

INSERT INTO students
(name, email, city, status)
VALUES
('Amit Kumar', 'amit@example.com', 'Patna', 'Active'),
('Priya Singh', 'priya@example.com', 'Gaya', 'Active'),
('Rahul Sharma', 'rahul@example.com', 'Patna', 'Inactive');

DELIMITER //

CREATE PROCEDURE get_active_students(
    IN student_city VARCHAR(100)
)
BEGIN

    SELECT
        student_id,
        name,
        email,
        city,
        status
    FROM students
    WHERE city = student_city
    AND status = 'Active'
    ORDER BY name;

END //

DELIMITER ;

CALL get_active_students('Patna');

SHOW CREATE PROCEDURE get_active_students;

DROP PROCEDURE IF EXISTS get_active_students;

This complete example demonstrates creating a procedure, using an IN parameter, filtering records, ordering results, calling the procedure, viewing its definition, and dropping it.

📌 Key Points

  • A stored procedure is a named collection of SQL statements stored in MySQL.
  • CREATE PROCEDURE is used to create a procedure.
  • CALL is used to execute a procedure.
  • DELIMITER is commonly changed when defining procedures containing multiple statements.
  • IN parameters receive values from the caller.
  • OUT parameters can return values to the caller.
  • INOUT parameters can receive and return values.
  • Procedures can contain INSERT, UPDATE, DELETE, and SELECT statements.
  • DECLARE is used to declare local variables.
  • IF, CASE, WHILE, LOOP, and REPEAT can be used for procedural logic.
  • SHOW CREATE PROCEDURE displays a procedure definition.
  • SHOW PROCEDURE STATUS displays procedure information.
  • DROP PROCEDURE removes a stored procedure.
  • DROP PROCEDURE IF EXISTS avoids an error when the procedure does not exist.
  • Stored procedures can help organize and reuse database operations.

🧠 Quick Quiz

Question: Which statement is used to execute a stored procedure in MySQL?