1. Syntax for Creating a Function
CREATE FUNCTION function_name(parameter_name data_type)
RETURNS return_data_type
DETERMINISTIC
BEGIN
-- SQL statements
RETURN value;
END;
function_name
: The name of the function.parameter_name
: Input parameter for the function.RETURNS
: Specifies the data type of the returned value.Let’s create a function that calculates the annual salary of an employee based on their monthly salary.
CREATE FUNCTION GetAnnualSalary(monthly_salary DECIMAL(10,2))
RETURNS DECIMAL(10,2)
DETERMINISTIC
BEGIN
RETURN monthly_salary * 12;
END;
SELECT GetAnnualSalary(5000);
MySQL Functions provide an efficient way to handle repeated calculations and improve database performance. By defining functions once and reusing them, developers can write cleaner and more efficient SQL queries.