MySQL Stored Procedures and Functions
Stored programs are pieces of SQL code saved in the database under a name. There are two main kinds:
| Stored procedure | Stored function | |
|---|---|---|
| Called with | CALL name(...) |
inside an expression: SELECT name(...) |
| Returns | result sets and/or OUT parameters |
exactly one value (RETURNS type) |
| Typical use | a multi-step operation (place an order, close a month) | a reusable calculation (price with tax) |
They let several applications share one implementation of a business rule, and they run close to the data, saving round trips.
DELIMITER
A procedure body contains several statements, each ending in ;. The mysql client would normally send the CREATE PROCEDURE to the server at the first ;. DELIMITER // tells the client to use // as the statement terminator for a while, so that the whole definition is sent in one piece. DELIMITER ; switches back. (DELIMITER is a client command, not SQL; GUI tools and drivers don't need it.)
A first procedure
DELIMITER //
CREATE PROCEDURE customer_orders(IN p_customer_id INT)
BEGIN
SELECT order_id, order_date, status
FROM orders
WHERE customer_id = p_customer_id
ORDER BY order_date;
END //
DELIMITER ;
CALL customer_orders(1);
CALL customer_orders(12);+----------+------------+-----------+
| order_id | order_date | status |
+----------+------------+-----------+
| 1 | 2025-01-05 | delivered |
| 4 | 2025-01-27 | delivered |
| 14 | 2025-04-08 | delivered |
+----------+------------+-----------+
+----------+------------+------------+
| order_id | order_date | status |
+----------+------------+------------+
| 13 | 2025-04-01 | delivered |
| 22 | 2025-06-03 | processing |
+----------+------------+------------+
BEGIN ... END wraps the body. A SELECT inside a procedure sends its result set to the caller.
Parameters: IN, OUT, INOUT
IN(default): a value passed to the procedure.OUT: a variable the procedure fills in for the caller.INOUT: both.
DELIMITER //
CREATE PROCEDURE customer_summary(IN p_id INT, OUT p_orders INT, OUT p_spent DECIMAL(10,2))
BEGIN
SELECT COUNT(DISTINCT o.order_id), IFNULL(SUM(d.quantity * d.unit_price * (1 - d.discount)), 0)
INTO p_orders, p_spent
FROM orders AS o
JOIN order_details AS d ON d.order_id = o.order_id
WHERE o.customer_id = p_id AND o.status <> 'cancelled';
END //
DELIMITER ;
CALL customer_summary(1, @n, @total);
SELECT @n AS orders, @total AS spent;
CALL customer_summary(7, @n, @total);
SELECT @n AS orders, @total AS spent;+--------+--------+
| orders | spent |
+--------+--------+
| 3 | 128.01 |
+--------+--------+
+--------+-------+
| orders | spent |
+--------+-------+
| 0 | 0.00 |
+--------+-------+
SELECT ... INTO variables stores a single row's values in variables instead of returning them.
Variables, IF and loops
Inside a body, DECLARE creates local variables (at the start of a BEGIN block), SET assigns them, and IF, CASE, WHILE, REPEAT and LOOP control the flow:
DELIMITER //
CREATE PROCEDURE restock(IN p_product INT, IN p_boxes INT)
BEGIN
DECLARE v_stock INT;
DECLARE v_i INT DEFAULT 0;
SELECT units_in_stock INTO v_stock FROM products WHERE product_id = p_product;
IF v_stock IS NULL THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Unknown product';
END IF;
WHILE v_i < p_boxes DO -- add 12 units per box
SET v_stock = v_stock + 12;
SET v_i = v_i + 1;
END WHILE;
UPDATE products SET units_in_stock = v_stock WHERE product_id = p_product;
SELECT name, units_in_stock FROM products WHERE product_id = p_product;
END //
DELIMITER ;
CALL restock(4, 3);
CALL restock(99, 1);+----------------------+----------------+
| name | units_in_stock |
+----------------------+----------------+
| Sparkling Water 6x1L | 36 |
+----------------------+----------------+
ERROR 1644 (45000) at line 24: Unknown product
SIGNAL SQLSTATE '45000' raises a custom error (45000 means "unhandled user-defined exception"). The caller sees error 1644 with your message, and the script stops, as with any error.
Error handling inside a procedure
DECLARE ... HANDLER catches errors in the procedure itself. Combined with a transaction, it gives all-or-nothing operations:
DELIMITER //
CREATE PROCEDURE move_stock(IN p_from INT, IN p_to INT, IN p_qty INT)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
SELECT 'transfer failed, nothing changed' AS result;
END;
START TRANSACTION;
UPDATE products SET units_in_stock = units_in_stock - p_qty WHERE product_id = p_from;
IF (SELECT units_in_stock FROM products WHERE product_id = p_from) < 0 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'not enough stock';
END IF;
UPDATE products SET units_in_stock = units_in_stock + p_qty WHERE product_id = p_to;
COMMIT;
SELECT 'transfer done' AS result;
END //
DELIMITER ;
CALL move_stock(9, 12, 50);
CALL move_stock(7, 12, 50);
SELECT product_id, units_in_stock FROM products WHERE product_id IN (7, 9, 12);+---------------+
| result |
+---------------+
| transfer done |
+---------------+
+----------------------------------+
| result |
+----------------------------------+
| transfer failed, nothing changed |
+----------------------------------+
+------------+----------------+
| product_id | units_in_stock |
+------------+----------------+
| 7 | 8 |
| 9 | 150 |
| 12 | 120 |
+------------+----------------+
The second call tried to take 50 of the 8 chocolate cakes; the handler rolled back the first UPDATE.
Stored functions
A function returns one value and can be used in any expression. MySQL needs to know whether it changes data: declare it DETERMINISTIC (same inputs → same result), NO SQL or READS SQL DATA. With binary logging enabled (the MySQL 8 default), CREATE FUNCTION without one of these is refused.
DELIMITER //
CREATE FUNCTION price_with_vat(p_price DECIMAL(8,2), p_rate DECIMAL(4,2))
RETURNS DECIMAL(10,2)
DETERMINISTIC
BEGIN
RETURN ROUND(p_price * (1 + p_rate / 100), 2);
END //
DELIMITER ;
SELECT name, unit_price, price_with_vat(unit_price, 21) AS gross
FROM products
WHERE category_id = 3;+--------------------+------------+-------+
| name | unit_price | gross |
+--------------------+------------+-------+
| Whole Milk 1L | 1.45 | 1.75 |
| Aged Gruyere 250g | 7.95 | 9.62 |
| Greek Yogurt 500g | 3.95 | 4.78 |
| Salted Butter 250g | 2.85 | 3.45 |
+--------------------+------------+-------+
Managing stored programs
SHOW PROCEDURE STATUS WHERE Db = 'shop';
SHOW CREATE PROCEDURE restock;
DROP PROCEDURE IF EXISTS restock;
DROP FUNCTION IF EXISTS price_with_vat;There is no CREATE OR REPLACE PROCEDURE in MySQL (MariaDB has it): drop and recreate instead.
Tip: Stored programs are powerful but live outside your application's version control and test suite unless you put them there. Many teams keep business logic in the application and use procedures for data-heavy batch jobs. Store their
CREATEscripts with migrations either way.
Test yourself
How do you run a stored procedure?
- SELECT proc()
- EXEC proc
- CALL proc(...)
- RUN proc
Why is DELIMITER // used before CREATE PROCEDURE in the mysql client?
- Procedures must end with //
- So that the semicolons inside the body don't end the CREATE statement early
- To enable comments
- To switch to procedure mode on the server
Which parameter mode lets a procedure return a value to the caller's variable?
- IN
- OUT
- RETURN
- VAR