A stored procedure is a precompiled SQL routine saved in MariaDB that can accept parameters, perform logic, and return results to callers.
Stored procedures centralize business logic, reduce network traffic, and improve security by granting EXECUTE instead of raw table rights. They also enable compiled execution plans for faster repeat runs.
Switch the statement delimiter, compose the routine body, then restore the delimiter.Use IN, OUT, or INOUT parameters to pass data and return values.
DELIMITER //
CREATE PROCEDURE add_order (
IN p_customer_id INT,
IN p_total DECIMAL(10,2)
)
BEGIN
INSERT INTO Orders(customer_id, order_date, total_amount)
VALUES(p_customer_id, NOW(), p_total);
END //
DELIMITER ;
Invoke CALL with required arguments. OUT parameters need user variables to capture results.
CALL add_order(5, 199.99);
Select rows inside the routine.The client receives the result set like a normal query.
CREATE PROCEDURE list_customer_orders(IN p_customer_id INT)
BEGIN
SELECT *
FROM Orders
WHERE customer_id = p_customer_id
ORDER BY order_date DESC;
END;
MariaDB lacks ALTER PROCEDURE; use DROP PROCEDURE and recreate. Wrap the DROP in IF EXISTS to avoid errors.
DROP PROCEDURE IF EXISTS add_order;
Use explicit transaction control, validate all inputs, keep procedures single-purpose, and document parameters and expected results.Grant only EXECUTE to application roles.
.
Yes. Execute several SELECT statements sequentially. The client library iterates through each set.
They reduce parse time and network latency but won’t fix poor indexing. Tune queries inside the procedure for optimal speed.
Insert SELECT or SIGNAL statements to trace values, or use MariaDB’s CONNECT_OUT plugin with a debugger-aware IDE.