Create a Function

suggest change

The following (trivial) example function simply returns the constant INT value 12.

DELIMITER ||
CREATE FUNCTION functionname()
RETURNS INT
DETERMINISTIC
BEGIN
    RETURN 12;
END;
||
DELIMITER ;

The first line changes the statement delimiter (DELIMITER ||). Set it before creating a function. Otherwise the first ; in the body ends the CREATE statement, which is usually not what you want.

After the CREATE FUNCTION has run you should set the delimiter back to its default of ; as is seen after the function code in the above example (DELIMITER ;).

Call the function as follows:

SELECT functionname();
+----------------+
| functionname() |
+----------------+
|             12 |
+----------------+

A slightly more complex (but still trivial) example takes a parameter and adds a constant to it:

DELIMITER $$
CREATE FUNCTION add_2 ( my_arg INT )
  RETURNS INT
  DETERMINISTIC
BEGIN
  RETURN (my_arg + 2);
END;
$$
DELIMITER ;

SELECT add_2(12);
+-----------+
| add_2(12) |
+-----------+
|        14 |
+-----------+

Note the use of a different argument to the DELIMITER directive. You can actually use any character sequence that does not appear in the CREATE statement body, but the usual practice is to use a doubled non-alphanumeric character such as \\, || or $$.

Change the delimiter before and after creating or replacing a function, procedure, or trigger. Some GUIs do not need that change. The command-line client does. With binary logging on, also declare a characteristic such as DETERMINISTIC or READS SQL DATA, or the CREATE FUNCTION fails.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents