MySQL functions
This article shows you how to use and create a simple function in MySQL.
函数
What is in MySQL
In the MySQL programming language, 函数
a set of statements that executes a set of rows and returns a value.
When the function block is called externally, this set of code executes the business logic and the conversion happens to return void or any single value.
Function helps to process the data before saving and retrieving it. It is of various types like single value or multiple parameter functions.
The benefits we can get from functions include:
- Use the same function in different places to do some operations.
- One change, and the effect is seen everywhere.
- Functionality is easy to maintain.
- It allows code sharing and consistency across all uses.
- Reduce rework of identical tasks and reuse existing functionality.
The function prototype or syntax in MySQL is as follows.
CREATE FUNCTION function_name [ (parameter datatype [, parameter datatype]) RETURNS return_datatype
BEGIN
Declaration_section
Executable_section
END;
Let's have some more insights and details on the above syntax.
- The syntax starts with
CREATE FUNCTION
a statement; it represents MySQL internally and is required to create a new method. - After the function keyword,
function_name
comes a specific name indicating that the line block is an alias for the provided statement. When a function name is given, the user attempts to execute the given set to perform the desired function. - Next to the function name, there can be
n
parameters passed as arguments to the function. The parameter list consists of two parts: the variable name and the variable data type.
3.1. The variable name can be used in the function operation logic. The set of statements where the conversion occurs uses the parameter variable to process the received data.
3.2 The data type declaration after the variable name restricts the use of the defined parameters. The data type serves as the main validation to verify the passed parameters. RETURNS
The keyword specifies that the next value is the single return value of the function.Return_datatype
Is the data type of the function's return value. It also includes the size of the data type,VARCHAR(20)
e.g.BEGIN
Keywords internally specify that the line next to the keyword is the starting point for the next set of lines to be executed. It indicates that this is the beginning of a function block.Declaration_section
is the location or top of the function block where all variables are declared.Executable_section
Blocks are the actual lines of code used for the operation. These are the exact lines that execute the business transformation logic.END;
Is a terminal keyword that specifies the end of a block. This keywordBEGIN
is used in conjunction with the statement. The statement describes the beginning and end of a block.
CREATE FUNCTION
Create a function in MySQL using
The prerequisites for creating a function are:
- Have a proper MySQL connection and keep the server running.
- Create a database and use it wherever you need to create functions (for example:
myFirstDb
). - Pre-create a table where you can call the function (for example:
stu_name
). - Enter some entries in the table where the function works and responds.
CREATE TABLE `stu` (
`id` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`dob` date DEFAULT NULL
);
INSERT INTO `myFirstDb`.`stu`(`id`,`name`,`dob`) VALUES ('111','Test',DATE('1970-01-08'));
DELIMITER $$
CREATE DEFINER=`root`@`localhost` FUNCTION `get_stu_name`(stu_id VARCHAR(50)) RETURNS varchar(50) CHARSET utf8mb4
BEGIN
declare stu_name varchar(50) ;
select name into stu_name from myFirstDb.stu where id = stu_id;
RETURN stu_name;
END$$
DELIMITER ;
When we use SELECT
the function name with the keyword, the following function call occurs. The calling statement is shown below.
Select get_stu_name('111');
The call statement 1
passes the parameter as studentID and executes the function. To successfully run the function name, there must be a student table with id
as one of the attributes.
When the record exists, the function returns the student name corresponding to the student ID as 1.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Changing max_allowed_packet Size in MySQL Server
Publish Date:2025/04/22 Views:192 Category:MySQL
-
This article explains how to change the max_allowed_packet size in MySQL server. To understand this, we will use two operating systems, Windows 10 and Linux (Ubuntu). Changing max_allowed_packet Size in MySQL Server If we try to upload a fi
Zerofill usage, advantages and alternatives in MySQL
Publish Date:2025/04/22 Views:195 Category:MySQL
-
In this article we will understand the uses, advantages and alternatives of ZEROFILL attribute in MySQL. Use and benefits of the ZEROFILL attribute in MySQL The benefit of using the ZEROFILL attribute is that it has nothing to do with input
Compare only MySQL timestamp dates to date parameters
Publish Date:2025/04/22 Views:64 Category:MySQL
-
In this article we will use the DATE() , CAST() , and CONVERT() functions to compare MySQL timestamp dates with only the date parameter. DATE() vs. CAST() vs. CONVERT() in MySQL Below is a brief description of each function. You can also fi
Calculating Percentages in MySQL
Publish Date:2025/04/22 Views:66 Category:MySQL
-
We will use one or more columns to calculate percentages in MySQL. There are different ways to do this, and for each method we will use an example table. Calculate percentage using a column in MySQL We have a table called sales where ID, Re
Selecting multiple values using WHERE in MySQL
Publish Date:2025/04/22 Views:185 Category:MySQL
-
This article is about using MySQL query to get data from a specific table or relation that satisfies a specific condition. To do this, the WHERE clause is used in the SQL query. WHERE clause in SQL query WHERE The clause specifies the condi
Changing the connection timeout in MySQL
Publish Date:2025/04/22 Views:59 Category:MySQL
-
We are learning how to change the connection timeout in MySQL using Linux (Ubuntu 20.04) and Windows operating systems. Changing the connection timeout in MySQL Sometimes you keep losing connection to the MySQL server because the connect_ti
MySQL fix Data Is Truncated for a Column error
Publish Date:2025/04/22 Views:101 Category:MySQL
-
This article describes possible causes and solutions for the MySQL error Data is truncated for a column . Fix data truncated due to column error in MySQL Here, we will discuss the possible causes and solutions to eliminate MySQL data trunca
MySQL Error Server PID File Could Not Be Found Solution
Publish Date:2025/04/22 Views:192 Category:MySQL
-
In this article, we will study about the Error! Error Server PID File Could Not Be Found! in MySQL and its solution with full explanation. MySQL PID file The file that contains the process identification number or process ID of a running My
Get the last inserted ID using PHP MySQLi function
Publish Date:2025/04/22 Views:99 Category:MySQL
-
This article briefly introduces the PHP mysqli() function and demonstrates how to use it to get the last inserted ID from a MySQL database. PHP mysqli() Function It is an extended version of the MySQL driver called mysqli and is typically u