mysql
  1. mysql-stored-function

Stored Function - (MySQL Misc)

In MySQL, a stored function is a precompiled routine that can be called from within an SQL statement. It's similar to a stored procedure, but it returns a value that can be used in an expression.

Syntax

The syntax for creating a stored function in MySQL is as follows:

CREATE FUNCTION function_name (arguments)
RETURNS return_type
BEGIN
  -- Function body goes here
END

In this syntax:

  • function_name: The name of the function.
  • arguments: The arguments that the function takes.
  • return_type: The data type of the value returned by the function.
  • BEGIN and END: The block of code that defines the function body.

Example

Let's say we want to create a stored function called get_student_avg_score that takes a student ID as an argument and returns the average score for that student. Here's how we can implement it:

CREATE FUNCTION get_student_avg_score (student_id INT)
RETURNS FLOAT
BEGIN
  DECLARE avg_score FLOAT;
  SELECT AVG(score) INTO avg_score FROM exam_results WHERE student_id = student_id;
  RETURN avg_score;
END

Now, we can call this function from within an SQL statement:

SELECT student_name, get_student_avg_score(student_id) AS avg_score FROM students;

Output

When we run the SQL statement above, the output will be a table with two columns: student_name and avg_score.

Explanation

In the example above, we created a stored function called get_student_avg_score that takes a student ID as an argument and returns the average score for that student. The function body contains a declaration for a local variable avg_score, which is used to store the result of the AVG() aggregate function. The SELECT statement retrieves the average score for the given student ID and stores it in avg_score. Finally, the function returns avg_score.

Use

Stored functions can be used in a variety of scenarios, such as calculations and data processing. They provide a way to reuse SQL code and simplify complex SQL statements.

Important Points

  • Stored functions are precompiled routines that can be called from within an SQL statement.
  • Stored functions return a value that can be used in an expression.
  • The syntax for creating a stored function in MySQL consists of the CREATE FUNCTION statement followed by the function body.
  • Stored functions can be used in a variety of scenarios, such as calculations and data processing.

Summary

In this tutorial, we covered the syntax and use of stored functions in MySQL. We also provided an example of how to create a stored function that takes an argument and returns a value. With this knowledge, you can now use stored functions in your MySQL database to simplify complex queries and calculations.

Published on: