← Back to Chapters

MySQL User Defined Functions

? MySQL User Defined Functions

? Quick Overview

A User Defined Function (UDF) in MySQL is a reusable program unit that accepts parameters, performs operations, and returns a single value. Functions are commonly used inside SQL statements like SELECT, WHERE, and ORDER BY.

? Key Concepts

  • Returns exactly one value
  • Can accept input parameters
  • Cannot return result sets
  • Used inside SQL expressions
  • Improves code reusability and readability

? Syntax / Theory

Basic structure of a MySQL user defined function:

? View Code Example
-- General syntax of MySQL user defined function
CREATE FUNCTION function_name(parameter datatype)
RETURNS return_datatype
DETERMINISTIC
BEGIN
RETURN value;
END;

? Code Example(s)

? Example 1: Simple Addition Function

? View Code Example
-- Function to add two integers
DELIMITER $$
CREATE FUNCTION add_numbers(a INT, b INT)
RETURNS INT
DETERMINISTIC
BEGIN
RETURN a + b;
END$$
DELIMITER ;

? Example 2: Calculate Annual Salary

? View Code Example
-- Function to calculate yearly salary from monthly salary
DELIMITER $$
CREATE FUNCTION annual_salary(monthly_salary DECIMAL(10,2))
RETURNS DECIMAL(10,2)
DETERMINISTIC
BEGIN
RETURN monthly_salary * 12;
END$$
DELIMITER ;

? Live Output / Explanation

? View Code Example
-- Calling user defined functions in SELECT statement
SELECT add_numbers(10, 20) AS result;
SELECT annual_salary(25000) AS yearly_salary;

Output Explanation

  • add_numbers(10, 20) returns 30
  • annual_salary(25000) returns 300000.00

? Interactive Playground

Simulate how a UDF works logically. Below is a Discount Calculator. In MySQL, this would be a function like calculate_final_price(price, discount).

SQL > SELECT calculate_final_price(100, 20);
Result: 80.00

✅ Tips & Best Practices

  • Always use DETERMINISTIC when function output is predictable
  • Keep functions small and focused
  • Use meaningful function and parameter names
  • Prefer functions for calculations, not data manipulation

? Try It Yourself

  • Create a function to calculate square of a number
  • Create a function to check if a number is even or odd
  • Create a function to apply GST (18%) on a price