MySQL UDFs (User-Defined Functions) let you encapsulate reusable logic that can be called in SQL, similar to built-in functions.
A User-Defined Function (UDF) is a piece of reusable SQL or external code registered in MySQL and callable like SUM()
or NOW()
. UDFs help centralize business logic, improve readability, and reduce repetition.
Create a UDF when the same calculation appears in multiple queries, when complex logic clutters SELECT lists, or when enforcing consistent business rules across reports.
Use CREATE FUNCTION
with a deterministic body that returns a single value. Store the function in the chosen database schema so any user with EXECUTE privilege can call it.
1. Switch to the target schema.
2. Write the CREATE FUNCTION
statement.
3. Grant privileges if others need to execute it.
Suppose every order requires a 2% marketplace fee. Instead of repeating total_amount * 0.02
, wrap it in fn_marketplace_fee()
. Analysts and services now call the function, guaranteeing identical logic.
• Mark functions DETERMINISTIC
when they always return the same output for the same input.
• Keep functions side-effect-free—avoid INSERT/UPDATE.
• Version functions with clear names (fn_
prefix) to avoid collisions.
• Document parameter types and units in comments.
MySQL lacks ALTER FUNCTION
; instead, drop the function and recreate it. Use DROP FUNCTION IF EXISTS fn_name;
to avoid errors in deployment scripts.
Run GRANT EXECUTE ON FUNCTION db.fn_name TO 'analyst'@'%';
. Revoke with REVOKE EXECUTE ON FUNCTION db.fn_name FROM 'analyst'@'%';
.
Yes. Define the return type as JSON and build the object with JSON_OBJECT()
inside the function body.
Scalar UDFs introduce minimal overhead, but complex calculations in large result sets can add latency. Mark functions DETERMINISTIC and avoid unnecessary calls.
Query information_schema.routines
: SELECT routine_name FROM information_schema.routines WHERE routine_type='FUNCTION' AND routine_schema='mydb';