The CREATE FUNCTION statement in MySQL is used to create a user-defined stored function. A stored function is a set of SQL statements that perform a specific task and can be reused in various parts of a SQL query or script. Functions are part of MySQL’s support for procedural programming, allowing developers to encapsulate logic and create modular code.
Syntax
Here is the basic syntax for the CREATE FUNCTION statement:
CREATE FUNCTION function_name ( parameter1 data_type, parameter2 data_type, ... ) RETURNS return_data_type BEGIN -- Function body with SQL statements RETURN expression; END;
Let’s break down the components of this syntax:
function_name: The name of the function you are creating.
(parameter1 data_type, parameter2 data_type, …): Input parameters that the function accepts. Each parameter has a name and a data type.
RETURNS return_data_type: Specifies the data type of the value that the function will return.
BEGIN and END: Delimit the body of the function, which contains a set of SQL statements.
RETURN expression;: The value that the function will return. The data type of the expression must match the specified return data type.
Example
Here’s a simple example of a MySQL stored function that calculates the square of a given number:
DELIMITER // CREATE FUNCTION calculate_square (num INT) RETURNS INT DETERMINISTIC BEGIN DECLARE result INT; SET result = num * num; RETURN result; END;
In this example, the function calculate_square takes an integer parameter num and returns an integer. The function body declares a variable result, assigns the square of the input parameter to it, and then returns the result.
Once a function is created, it can be called from SQL queries or other stored procedures. For example:
SELECT calculate_square(5);
This query would return the result of the calculate_square function with the input parameter 5, which is 25.
Benefits of Using Functions
Modular Code: Functions promote modularity by encapsulating related operations into reusable units.
Code Reusability: Functions allow for code reuse, reducing the need to write repetitive code snippets.
Improved Readability: Functions make code more readable by separating common tasks into logical units.
Increased Productivity: Functions can automate tasks, saving time and effort.
MySQL functions are powerful tools that can significantly enhance the development and maintenance of database applications. They provide a flexible and efficient way to organize code, reuse functionality, and improve overall code quality.