Skip to content

FUNCTION

CREATE FUNCTION function_name ([parameter datatype,…]) RETURNS datatype [LANGUAGE {SQL | language_name}] [DETERMINISTIC | NOT DETERMINISTIC] [SQL DATA ACCESS {CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA}] [COMMENT ‘string’] BEGIN function_body; END;

Section titled “CREATE FUNCTION function_name ([parameter datatype,…]) RETURNS datatype [LANGUAGE {SQL | language_name}] [DETERMINISTIC | NOT DETERMINISTIC] [SQL DATA ACCESS {CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA}] [COMMENT ‘string’] BEGIN function_body; END;”
  • function_name: The name of the function to be created.
  • parameter datatype: A comma separated list of the parameters that the function will use, each followed by its datatype.
  • returns datatype: The datatype of the value that the function will return.
  • language {sql | language_name}: Defines the language that the function is written in. Default is SQL.
  • deterministic | not deterministic: Specifies whether the function always produces the same result for the same input parameters.
  • sql data access {contains sql | no sql | reads sql data | modifies sql data}: Determines the type of SQL statements that can be included in the function.
  • comment ‘string’: An optional parameter that allows you to add a descriptive comment to the function.
  • begin function_body; end: The body of the function which contains the SQL statements to be executed.
CREATE FUNCTION SquareArea(side_length INT)
RETURNS INT
DETERMINISTIC
BEGIN
RETURN side_length * side_length;
END;
```sql
SELECT SquareArea(5);
25

In the given example, a function named SquareArea is created which calculates the area of a square. The function accepts integer side_length as an argument and returns the area by multiplying the side length with itself.

The function is then called by passing 5 as the length of the side, resulting in an output of 25.