A newer version of this documentation is available.

View Latest

Call a User-Defined Function

  • how-to
    +
    How to call a user-defined function from SQL++ statements.

    Introduction

    A user-defined function can be called like any other SQL++ function.

    If you want to try out the examples in this section, follow the instructions given in Do a Quick Install to install Couchbase Server, configure a cluster, and load a sample dataset. Read the following for further information about the tools available for editing and executing queries:

    Global and Scoped User-Defined Functions

    A user-defined function can be global or scoped.

    • When you call a global function, any partial keyspace references within the function definition are resolved against the default: namespace, regardless of the current query context.

    • When you call a scoped function, any partial keyspace references within the function definition are resolved against the function’s bucket and scope, regardless of the current query context.

    Executing a SQL++ User-Defined Function

    To execute a user-defined function:

    1. If required, set the query context for a scoped function, or unset the context for a global function.

    2. Use the EXECUTE FUNCTION statement and specify the name of the function.

    3. Specify the function parameters within parentheses ().

    The following query executes a function called GetBusinessDays, which was created in the current query context.

    EXECUTE FUNCTION GetBusinessDays("02/14/2025", "04/16/2025");

    Calling a SQL++ User-Defined Function

    The SQL++ user-defined function can be used in any SQL++ statement in exactly the same way as a standard built-in function.

    To call a user-defined function in any SQL++ statement:

    1. If required, set the query context for a scoped function, or unset the context for a global function.

    2. Specify the name of the function.

    3. Specify the function parameters within parentheses ().

    The following query calls the GetBusinessDays function, which was created in the current query context, from a SELECT statement.

    SELECT CASE
      WHEN GetBusinessDays('02/14/2025', '4/16/2025') > 40 THEN "late"
      ELSE "on time"
    END
    AS response; (1)

    For more information and examples, see User-Defined Functions.

    Reference:

    Administrator guides: