SurrealDB World   |   Join us in September

Back to top
Documentation SurrealQL Statements DEFINE statement FUNCTION

DEFINE FUNCTION statement

The DEFINE FUNCTION statement allows you to define custom functions that can be reused throughout a database.

Requirements

Statement syntax

DEFINE FUNCTION fn::@name(
	[ @argument: @type ... ]
) {
	[ @query ... ]
	[ RETURN @returned ]
}

Example usage

Below shows how you can define a custom function using the DEFINE FUNCTION statement, and how to call it.

-- It is necessary to prefix the name of your function with "fn::"
-- This indicates that it's a custom function
DEFINE FUNCTION fn::greet($name: string) {
	RETURN "Hello, " + $name + "!";
}

-- Returns: "Hello, Tobie!"
RETURN fn::greet("Tobie");

To showcase a slightly more complex custom function, this will check if a relation between two nodes exists:

DEFINE FUNCTION fn::relation_exists(
	$in: record(),
	$tb: string,
	$out: record()
) {
	LET $results = SELECT VALUE id FROM type::table($tb) WHERE in = $in AND out = $out;
    RETURN array::len($results) > 0;
};