MySQL Stored Procedures
MySQL Stored Procedures: Reusable Server-Side Routines
A MySQL stored procedure is a named block of SQL statements saved inside the database and executed with CALL. Procedures accept IN, OUT, and INOUT parameters and can wrap multi-step transactions, loops, and conditional checks close to the data.
Why DELIMITER Is Needed
Because statements inside a stored procedure end with semicolons (;), you must temporarily change the client statement terminator using DELIMITER // so the mysql CLI does not stop parsing halfway through CREATE PROCEDURE:
DELIMITER //
CREATE PROCEDURE demo_get_customer_orders(IN p_customer_id BIGINT)
BEGIN
SELECT id, status, total_amount, created_at
FROM demo_orders
WHERE customer_id = p_customer_id
ORDER BY created_at DESC;
END //
DELIMITER ;
-- Execute the stored procedure
CALL demo_get_customer_orders(101);
Practical Example With OUT Parameter
This procedure computes a customer's total paid spend and passes the result back through an OUT parameter:
DELIMITER //
CREATE PROCEDURE demo_customer_spend(
IN p_customer_id BIGINT,
OUT p_total_spent DECIMAL(10, 2)
)
BEGIN
SELECT COALESCE(SUM(total_amount), 0.00)
INTO p_total_spent
FROM demo_orders
WHERE customer_id = p_customer_id
AND status = 'paid';
END //
DELIMITER ;
CALL demo_customer_spend(101, @spend);
SELECT @spend AS total_spent;
Common Mistakes and Best Practices
- Prefix Parameters (
p_customer_id): If a parameter shares the exact same name as a table column (customer_id), MySQL interpretsWHERE customer_id = customer_idas always true and returns every row! Always prefix parameters withp_. - Keep Business Logic in Application Code Unless Needed: Stored procedures are harder to version-control, unit-test, and scale horizontally than backend PHP/Node/Python services. Reserve them for DBA maintenance jobs or batch data migrations.
Frequently Asked Questions
What is the difference between a stored procedure and a stored function?
A stored function returns a single scalar value and can be called inside a SELECT expression, whereas a stored procedure is invoked with CALL and can return full result sets and multiple OUT parameters.
How do I delete an existing stored procedure?
Run DROP PROCEDURE IF EXISTS demo_get_customer_orders;.
Do stored procedures prevent SQL injection automatically?
Only if queries inside the procedure use parameters directly rather than concatenating strings inside PREPARE / EXECUTE.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.