A stored function is a user-defined function stored in the database that accepts parameters, performs a calculation or lookup, and returns a single value. Unlike a stored procedure, a function can be called inline anywhere an expression is valid — inside a SELECT list, a WHERE clause, or as a default value.
DELIMITER $$
CREATE FUNCTION function_name(param1 type, param2 type, ...)
RETURNS return_type
DETERMINISTIC
BEGIN
DECLARE result return_type;
-- logic here
RETURN result;
END$$
DELIMITER ;
RETURNS (with an S) declares the data type the function will return.RETURN (no S) is the statement that actually sends the value back.DETERMINISTIC tells MySQL the function always returns the same output for the same input — required (or NOT DETERMINISTIC) for binary logging.DELIMITER $$
CREATE FUNCTION DiscountedPrice(p_price DECIMAL(10,2), p_pct INT)
RETURNS DECIMAL(10,2)
DETERMINISTIC
BEGIN
RETURN p_price - (p_price * p_pct / 100);
END$$
DELIMITER ;
Call it directly inside a SELECT:
SELECT name, price, DiscountedPrice(price, 15) AS sale_price
FROM products;
| name | price | sale_price |
|---|---|---|
| Laptop | 75000.00 | 63750.00 |
| Phone | 35000.00 | 29750.00 |
| Headphones | 12000.00 | 10200.00 |
| Mouse | 2000.00 | 1700.00 |
DELIMITER $$
CREATE FUNCTION FullName(p_first VARCHAR(50), p_last VARCHAR(50))
RETURNS VARCHAR(101)
DETERMINISTIC
BEGIN
RETURN CONCAT(p_first, ' ', p_last);
END$$
DELIMITER ;
SELECT FullName('Rahim', 'Uddin'); -- 'Rahim Uddin'
| Stored Function | Stored Procedure | |
|---|---|---|
| Returns | Always exactly one value | Zero or more result sets; uses OUT params |
| Called with | Inline in any expression | CALL procedure_name() |
| Use in SELECT | Yes | No |
| Best for | Computed values, formatting | Multi-step operations, batch processing |
DROP FUNCTION IF EXISTS DiscountedPrice;
RETURN statement.RETURNS type in the function header.DETERMINISTIC if it always returns the same value for the same inputs.SELECT, WHERE, or any expression — unlike a procedure which needs CALL.