Skip to content

Concepts & guides

Custom functions

DEFINE FUNCTION registers reusable SurrealQL under a name beginning with the fn:: prefix. You need appropriate access (root / namespace / database owner or editor), and you must USE the right namespace and database first. For more clauses and edge cases, see the reference documentation.

The examples on this page build the functions of a small lending library, in which members borrow books.

Custom functions are always named with the fn:: prefix. The first function works out when a loan is due back, three weeks after the book was borrowed:

DEFINE FUNCTION fn::due_date($borrowed: datetime) -> datetime {
	$borrowed + 3w
};

fn::due_date(d'2026-11-16T10:00:00Z');
Output
d'2026-12-07T10:00:00Z'

A function can take more than one parameter, and its body can use LET, subqueries and anything else a block can hold. The function below checks whether a member has a loan of a book, where each loan is a loan relation from a member to a book:

CREATE member:ana SET name = 'Ana';
CREATE book:dune SET title = 'Dune';
CREATE book:emma SET title = 'Emma';
RELATE member:ana->loan->book:dune;

DEFINE FUNCTION fn::has_loan($member: record<member>, $book: record<book>) -> bool {
	LET $loans = SELECT VALUE id FROM loan WHERE in = $member AND out = $book;
	$loans.len() > 0
};

fn::has_loan(member:ana, book:dune);
//- true

fn::has_loan(member:ana, book:emma);
//- false

If the last parameters use option<T>, callers may omit them. An omitted argument is NONE inside the body, so ?? can give it a default. Here the fine for a late book is 20 per day unless the caller passes another rate:

DEFINE FUNCTION fn::fine($days_late: int, $per_day: option<int>) -> int {
	$days_late * ($per_day ?? 20)
};

fn::fine(3, 50);
//- 150

fn::fine(3);
//- 60

Adding -> type is recommended for extra type safety, as well as readability. A function whose parameters are both int can clearly only return an int when it adds them, but the annotation tells a casual reader so without making them work it out.

The annotation also checks the value the function returns. The second function below accepts any input, so a call with two strings passes the argument checks, and the return type catches the result instead:

DEFINE FUNCTION fn::total_copies($shelf: int, $store: int) -> int {
	$shelf + $store
};

-- Accept any input; coercion to the return type happens when returning
DEFINE FUNCTION fn::total_copies_any($shelf: any, $store: any) -> int {
	$shelf + $store
};

fn::total_copies(3, 2);
//- 5

fn::total_copies("3", "2");
//- "Incorrect arguments for function fn::total_copies(). Failed to coerce argument `$shelf`: Expected `int` but found `'3'`"

fn::total_copies_any("3", "2");
//- "Couldn't coerce return value from function `fn::total_copies_any`: Expected `int` but found `'32'`"

You can also return literal union types for structured data or a fallback string instead of throwing:

CREATE book:dune SET title = 'Dune', copies = 4;

DEFINE FUNCTION fn::book_summary($key: string)
	-> { title: string, copies: int } | string {
	LET $book = type::record("book", $key);
	IF $book.exists() {
		$book.{ title, copies }
	} ELSE {
		"No book with the key " + $key
	}
};

fn::book_summary("dune");
//- { copies: 4, title: 'Dune' }

fn::book_summary("emma");
//- 'No book with the key emma'

Though not a commonly used pattern in SurrealQL, a function may call itself. Below, each book in a series links to the book before it. The function follows those links back to the first book, then adds each title on the way back, which gives the series in reading order:

CREATE book:dune SET title = 'Dune';
CREATE book:messiah SET title = 'Dune Messiah', prequel = book:dune;
CREATE book:children SET title = 'Children of Dune', prequel = book:messiah;

DEFINE FUNCTION fn::reading_order($book: record<book>) -> array<string> {
	IF $book.prequel = NONE {
		[$book.title]
	} ELSE {
		fn::reading_order($book.prequel).append($book.title)
	}
};

fn::reading_order(book:children);
Output
['Dune', 'Dune Messiah', 'Children of Dune']

PERMISSIONS controls whether record users may invoke the function: FULL (typical default), NONE, or WHERE with a boolean expression (often involving $auth).

In the library, no member may read the email addresses of the other members, and only librarians may list the overdue loans. Neither clause limits a system user such as root, so both calls below return their records when root runs them:

CREATE member:ana SET email = 'ana@example.com';
RELATE member:ana->loan:one->book:dune SET due = d'2026-01-10T00:00:00Z';
RELATE member:ana->loan:two->book:emma SET due = d'2099-01-10T00:00:00Z';

-- PERMISSIONS NONE: record users cannot call this
DEFINE FUNCTION fn::member_emails() -> array<string> {
	SELECT VALUE email FROM member
} PERMISSIONS NONE;

-- PERMISSIONS WHERE: record users can call this when the expression is true
DEFINE FUNCTION fn::overdue_loans() -> array<record<loan>> {
	SELECT VALUE id FROM loan WHERE due < time::now()
} PERMISSIONS WHERE $auth.librarian = true;

fn::member_emails();
//- ['ana@example.com']

fn::overdue_loans();
//- [loan:one]

Clauses like IF NOT EXISTS and OVERWRITE can be used when defining a function. Without either of them, defining a function that already exists is an error. Below, the library changes its loan period from three weeks to four:

DEFINE FUNCTION fn::due_date($borrowed: datetime) -> datetime {
	$borrowed + 3w
};

-- IF NOT EXISTS: the function exists already, so nothing changes
DEFINE FUNCTION IF NOT EXISTS fn::due_date($borrowed: datetime) -> datetime {
	$borrowed + 4w
};
fn::due_date(d'2026-11-16T10:00:00Z');
//- d'2026-12-07T10:00:00Z'

-- OVERWRITE: replace the existing definition with this one
DEFINE FUNCTION OVERWRITE fn::due_date($borrowed: datetime) -> datetime {
	$borrowed + 4w
};
fn::due_date(d'2026-11-16T10:00:00Z');
//- d'2026-12-14T10:00:00Z'

Handlers for DEFINE API middleware are ordinary fn:: functions with a specific signature. See custom middleware and the learn page on middleware for more details.

Was this page helpful?

Last updated