MySQL Stored Procedures: IN, OUT, IF, LOOP and Transactions

MySQL 65 min min read Updated: Nov 27, 2026 Intermediate
MySQL Stored Procedures: IN, OUT, IF, LOOP and Transactions
Intermediate Topic 1 of 3

What Is a Stored Procedure?

A stored procedure is a named block of SQL saved in the database. You run it with CALL. It can take parameters, use variables and loops, and run many statements together. Teams use them to keep complex rules next to the data, or to cut round trips between app and database.

DELIMITER in the mysql Client

In the mysql command-line client the ; ends a statement, but a procedure body contains ;. So you temporarily change the delimiter:

sql DELIMITER // CREATE PROCEDURE hello() BEGIN SELECT 'Hello from MySQL' AS msg; END // DELIMITER ;

DELIMITER is a client command, not SQL, so tools like Workbench or an application driver do not need it. The examples below are executed by a driver, so they show the body without it.

Your First Procedure

sql CREATE PROCEDURE products_in_category(IN cat VARCHAR(50)) BEGIN SELECT name, price FROM products WHERE category = cat ORDER BY price; END; CALL products_in_category('Stationery');

Result:

nameprice
Notebook3.50
Pen Pack5.00

OUT and INOUT Parameters

sql CREATE PROCEDURE order_total(IN oid INT, OUT total DECIMAL(10,2)) BEGIN SELECT COALESCE(SUM(oi.quantity * p.price), 0.00) INTO total FROM order_items oi JOIN products p ON p.id = oi.product_id WHERE oi.order_id = oid; END; CALL order_total(1, @t); SELECT @t AS order_1_total;

Result:

order_1_total
1057.00

@t is a user variable. It lives for the connection and receives the OUT value.

sql CREATE PROCEDURE add_tax(INOUT amount DECIMAL(10,2), IN rate DECIMAL(4,2)) BEGIN SET amount = ROUND(amount * (1 + rate / 100), 2); END; SET @a = 200.00; CALL add_tax(@a, 18); SELECT @a AS with_tax;

Result:

with_tax
236.00

Variables, IF and CASE

sql CREATE PROCEDURE stock_status(IN pid INT) BEGIN DECLARE qty INT DEFAULT 0; DECLARE label VARCHAR(20); SELECT stock INTO qty FROM products WHERE id = pid; IF qty = 0 THEN SET label = 'OUT'; ELSEIF qty < 10 THEN SET label = 'LOW'; ELSE SET label = 'OK'; END IF; SELECT pid AS product_id, qty AS stock, label AS status; END; CALL stock_status(8);

Result:

product_idstockstatus
80OUT

DECLARE creates a local variable and must come first inside BEGIN ... END. Local variables do not use @.

Loops

sql CREATE TABLE squares (n INT, sq INT); CREATE PROCEDURE fill_squares(IN max_n INT) BEGIN DECLARE i INT DEFAULT 1; WHILE i <= max_n DO INSERT INTO squares VALUES (i, i * i); SET i = i + 1; END WHILE; END; CALL fill_squares(5); SELECT n, sq FROM squares ORDER BY n;

Result:

nsq
11
24
39
416
525

REPEAT ... UNTIL and LOOP ... LEAVE are the other loop forms.

A Transaction Inside a Procedure

sql CREATE PROCEDURE place_order(IN cust INT, IN prod INT, IN qty INT) BEGIN DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN ROLLBACK; SELECT 'failed, rolled back' AS result; END; START TRANSACTION; INSERT INTO orders (id, customer_id, order_date, status) VALUES (100, cust, '2025-07-01', 'pending'); INSERT INTO order_items (order_id, product_id, quantity) VALUES (100, prod, qty); UPDATE products SET stock = stock - qty WHERE id = prod; COMMIT; SELECT 'ok' AS result; END; CALL place_order(1, 1, 2); CALL place_order(1, 999, 1); SELECT (SELECT stock FROM products WHERE id = 1) AS laptop_stock, (SELECT COUNT(*) FROM orders WHERE id = 100) AS order_100_rows;

Result:

result
ok

Result:

result
failed, rolled back

Result:

laptop_stockorder_100_rows
131

The first call worked. The second used an unknown product, the foreign key failed, the handler rolled back and reported it. Handlers are explained in a later lesson.

Managing Procedures

sql CREATE PROCEDURE p1() SELECT 1; SELECT ROUTINE_NAME, ROUTINE_TYPE FROM information_schema.ROUTINES WHERE ROUTINE_SCHEMA = DATABASE() ORDER BY ROUTINE_NAME;

Result:

ROUTINE_NAMEROUTINE_TYPE
p1PROCEDURE
sql SHOW CREATE PROCEDURE p1; DROP PROCEDURE IF EXISTS p1;

There is no CREATE OR REPLACE PROCEDURE in MySQL. Drop then create.

When to Use Procedures

Good fitThink twice
Batch jobs near the dataComplex business rules that need version control and tests (keep in the app)
Cutting many round tripsLogic that must run on several database products
Controlled data changes with permissionsHeavy computation (databases are hard to scale out)

Common Beginner Mistakes

MistakeWhat happensFix
Parameter named like a columnQuery compares the parameter to itselfPrefix parameters, for example p_cat
Using @var for localsValue leaks across callsUse DECLARE
Forgetting DELIMITER in the clientSyntax error at the first ;Change the delimiter
No error handler around transactionsHalf-done workHandler with ROLLBACK
Expecting CREATE OR REPLACESyntax errorDROP ... IF EXISTS first

Practice

  1. Write a procedure that returns orders for a customer id.
  2. Add an OUT parameter with the customer's order count.
  3. Write a procedure that raises stock of all products below a given level.
  4. List all routines in your schema.

Conclusion

A stored procedure is saved SQL you CALL. Use IN, OUT and INOUT parameters, DECLARE locals, IF and loops, and wrap multi-step changes in a transaction with an error handler.

Quick Summary: CREATE PROCEDURE, CALL, IN/OUT/INOUT, DECLARE, IF, WHILE, transaction, handler.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators