A stored function in MySQL is a user-defined routine that accepts parameters, performs calculations or data operations, and returns a single value. You create it with CREATE FUNCTION, define its return type, write the body in SQL or procedural code, and then call it like a built-in function (e.g., SELECT my_function(10)).
What Is a Stored Function and How Does It Differ From a Stored Procedure?
Both stored functions and stored procedures are named database objects that contain SQL logic. The key difference is that a function must return a value and can be used inside SQL expressions, while a procedure does not return a value directly (though it can have OUT parameters). Procedures are called with CALL, cannot be used in a SELECT list, and are better for performing actions like inserts, updates, or complex multi-step operations. Functions, on the other hand, are ideal for computations, data transformations, and reusable logic that fits into queries.
For example, a function can compute a discount:
CREATE FUNCTION discount(price DECIMAL(10,2), pct DECIMAL(5,2))
RETURNS DECIMAL(10,2)
DETERMINISTIC
RETURN price * (1 - pct/100);
Then you can use it in a query: SELECT discount(100.00, 15) AS result; returns 85.00.
How to Create a Stored Function: Syntax and Requirements
The basic syntax is:
CREATE FUNCTION function_name (param1 type, param2 type, ...)
RETURNS return_type
[characteristics]
BEGIN
-- SQL statements
RETURN value;
END
Key requirements:
- You must have the
CREATE ROUTINEprivilege. - The function must have a
RETURNSclause specifying the data type of the return value. - Every function must contain at least one
RETURNstatement. - The body can include SQL statements, but if you use
BEGIN...END, you need to change the delimiter if the body contains semicolons (as shown below).
Example with a compound body:
DELIMITER //
CREATE FUNCTION get_full_name(first VARCHAR(50), last VARCHAR(50))
RETURNS VARCHAR(100)
DETERMINISTIC
BEGIN
DECLARE full_name VARCHAR(100);
SET full_name = CONCAT(first, ' ', last);
RETURN full_name;
END //
DELIMITER ;
After creation, you call it: SELECT get_full_name('John', 'Doe'); returns John Doe.
Characteristics of Stored Functions: DETERMINISTIC, SQL Security, and More
When creating a function, you can specify characteristics that affect how MySQL treats it:
- DETERMINISTIC: The function always returns the same result for the same input parameters. If not marked, MySQL may assume it is non-deterministic, which can limit its use in replication or indexing.
- NO SQL: The function does not contain SQL statements (only computations).
- READS SQL DATA: The function reads data via SELECT, but does not modify it.
- MODIFIES SQL DATA: The function performs INSERT, UPDATE, DELETE, or DDL statements.
- SQL SECURITY DEFINER / INVOKER: Controls whether the function executes with the privileges of the definer (the user who created it) or the invoker (the user who calls it). The default is
DEFINER.
These characteristics matter because MySQL uses them to optimize queries and to determine whether a function can be used in certain contexts, like indexed generated columns or replication.
How to Call a Stored Function
You call a stored function exactly like a built-in function, in any SQL expression:
- In a SELECT list:
SELECT my_function(column) FROM table; - In a WHERE clause:
SELECT * FROM orders WHERE discount(amount, 10) > 100; - In an INSERT statement:
INSERT INTO table (col) VALUES (my_function(5)); - In a SET statement:
SET @x = my_function(5);
You cannot call a stored function with CALL; that is for procedures only.
Dropping and Altering Stored Functions
To remove a function, use:
DROP FUNCTION IF EXISTS function_name;
MySQL does not provide an ALTER FUNCTION statement to change the body. To modify a function, you must drop it and recreate it with the new definition. However, you can change the characteristics (like SQL SECURITY) using ALTER FUNCTION in some versions, but the body remains unchanged.
Common Errors and Troubleshooting
Here are frequent issues when working with stored functions:
- Error 1418: This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA – This occurs when binary logging is enabled and you haven’t declared the function as deterministic or as not modifying data. Add
DETERMINISTICorREADS SQL DATAas appropriate. - Error 1064: Syntax error near ‘RETURN’ – Often due to missing delimiter handling when the body contains semicolons. Use
DELIMITER //before creating the function. - Error 1339: A RETURN statement is missing – Ensure every code path in the function returns a value.
- Function not found – Check the database name. Functions are schema-specific; you need to qualify with the database name if calling from another schema, e.g.,
SELECT db_name.function_name().
Stored Functions vs. Built-in Functions vs. Views
Built-in functions like CONCAT or ROUND are always available and are optimized by the server. Stored functions are user-defined and can encapsulate business logic, but they may be slower because they are interpreted and can be subject to privilege checks. Views are virtual tables that encapsulate a query; they return a result set, not a single value. Use stored functions when you need a reusable scalar computation; use views when you need to reuse a complex query as a table.
Performance and Security Considerations
Stored functions can impact performance, especially if called many times in a query. Since they are executed per row, a function that reads data (READS SQL DATA) can cause many queries. To mitigate, consider using joins or generated columns instead. Security-wise, be careful with the SQL SECURITY DEFINER setting: if the definer has elevated privileges, a malicious invoker could exploit the function. Always grant execute privileges only to trusted users.
Frequently Asked Questions
Can a stored function return a table or result set?
No. In MySQL, a stored function can only return a single scalar value. If you need to return a result set, you must use a stored procedure or a view.
What is the difference between DETERMINISTIC and NOT DETERMINISTIC?
A DETERMINISTIC function always returns the same result for the same input parameters. NOT DETERMINISTIC (the default if not specified) means the result may vary, for example, if it uses RAND() or NOW(). Marking a function as DETERMINISTIC when it is not can lead to incorrect results in replication or query caching.
Can I use a stored function in a CHECK constraint?
Yes, in MySQL 8.0.16 and later, you can use a stored function in a CHECK constraint, but the function must be deterministic and not modify data. For example: CHECK (my_function(col) > 0).
How do I see the definition of an existing stored function?
Use SHOW CREATE FUNCTION function_name; or query the information_schema.ROUTINES table.
Can a stored function call another stored function?
Yes, a stored function can call other stored functions or even stored procedures, but the called function must exist and the caller must have EXECUTE privilege on it.
Is there a limit to the number of stored functions?
There is no explicit limit on the number of stored functions, but the total size of stored routines is limited by the max_allowed_packet and system resources.
Related
- Entry Level Data Entry Companies: Real Jobs & How to Start
- Google Sheets QUERY Concatenate: How to Join Columns
- How to Get a Random Number in Java
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Formula for Tax Calculation: The Complete GuideThe core Excel formula for tax calculation is =A2*B2, where A2 contains the taxable amount and B2 contains…
- How to Filter by Color in ExcelTo filter by color in Excel for Microsoft 365 on Windows, turn on filters for your data, open…
- Excel Sort by Name Not Responding? Fixes to TryIf Excel’s sort by name appears not to respond, first select a cell in the full data range…
- CAGR Calc Excel Formula: Calculate Annual Growth RateIf the beginning value is in B2, the ending value is in C2, and the number of years…
- XLOOKUP to Compare Two Sheets in Excel Step by StepIf Sheet1 has IDs in A2:A100 and Sheet2 has IDs in A2:A100, enter this in Sheet1 cell B2…
- Excel Column Compare: Find Differences With FormulasTo compare values on the same rows in Excel, put this formula in C2 when the two columns…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.