1 Creating and Using Functions
TopYou already know stored procedures. A function (also called a user-defined function or UDF) is similar, but with one critical difference: a function always returns a value and can be used inside SQL statements like SELECT, WHERE, and ORDER BY. A procedure cannot.
Creating a Scalar Function (MySQL)
DELIMITER //
CREATE FUNCTION calculate_tax(
amount DECIMAL(10,2),
tax_rate DECIMAL(5,2)
)
RETURNS DECIMAL(10,2)
DETERMINISTIC
BEGIN
RETURN ROUND(amount * tax_rate / 100, 2);
END //
DELIMITER ;Now use it directly in queries — just like a built-in function:
SELECT
name,
salary,
calculate_tax(salary, 5) AS tax,
salary - calculate_tax(salary, 5) AS net_salary
FROM employees;name | salary | tax | net_salary --------------|---------|---------|---------- Sara Ahmed | 95000 | 4750.00 | 90250.00 James Wilson | 88000 | 4400.00 | 83600.00 David Chen | 105000 | 5250.00 | 99750.00
Function That Returns Text
DELIMITER //
CREATE FUNCTION salary_grade(salary DECIMAL(10,2))
RETURNS VARCHAR(20)
DETERMINISTIC
BEGIN
IF salary >= 100000 THEN RETURN 'Executive';
ELSEIF salary >= 80000 THEN RETURN 'Senior';
ELSEIF salary >= 60000 THEN RETURN 'Mid';
ELSE RETURN 'Junior';
END IF;
END //
DELIMITER ;
-- Use it in WHERE, ORDER BY, GROUP BY — anywhere!
SELECT salary_grade(salary) AS grade, COUNT(*) AS cnt
FROM employees
GROUP BY salary_grade(salary);grade | cnt ----------|---- Executive | 1 Senior | 3 Mid | 2 Junior | 1
DETERMINISTIC vs NOT DETERMINISTIC: Mark a function DETERMINISTIC if the same inputs always produce the same output (like a tax calculator). Mark it NOT DETERMINISTIC if it depends on external state (like reading from a table or using NOW()). MySQL requires this declaration.
Dropping a Function
DROP FUNCTION IF EXISTS calculate_tax;Key Takeaways
- Functions always
RETURNa value — procedures do not - Functions can be used inside
SELECT,WHERE,ORDER BY,GROUP BY - Declare
DETERMINISTICif same inputs always give same outputs - Functions encapsulate reusable calculations (tax, grades, formatting)