A MariaDB UDF (user-defined function) lets you encapsulate reusable logic in SQL and call it like a built-in function.
User-defined functions wrap business logic into callable routines, returning a single value per row. They improve readability and reuse across queries that touch tables such as Orders
or OrderItems
.
Run CREATE FUNCTION
with a name, input parameters, return type, and routine body. Mark deterministic functions and set the SQL level (e.g., READS SQL DATA
) for optimal planning.
DELIMITER //
CREATE FUNCTION total_after_tax(subtotal DECIMAL(10,2), tax_rate DECIMAL(5,2))
RETURNS DECIMAL(10,2)
DETERMINISTIC
BEGIN
RETURN subtotal + (subtotal * tax_rate/100);
END //
DELIMITER ;
Deterministic tells the optimizer the function returns the same result for identical inputs, enabling better caching and parallelization.
Invoke it like any built-in function:
SELECT id, total_after_tax(total_amount, 8) AS total_with_tax
FROM Orders
WHERE order_date >= '2024-01-01';
MariaDB lacks ALTER FUNCTION
; instead, DROP FUNCTION name;
and recreate with new logic. Use versioned names or deploy in maintenance windows.
Keep logic pure and side-effect-free, return scalar values only, document parameter units, and watch for data-type mismatches. Version control your .sql
files to track changes.
NULL handling: Always coalesce nullable inputs to avoid unexpected NULL results. Privilege errors: GRANT EXECUTE ON FUNCTION to application roles before production use.
Yes, but you must declare MODIFIES SQL DATA
. Avoid side effects unless absolutely necessary because they hinder composability.
Properly written deterministic functions incur minimal overhead. Avoid loops inside the body and prefer set-based SQL when possible.
Run GRANT EXECUTE ON FUNCTION function_name TO 'app_user'@'%';
so application roles can call it without full schema privileges.