# SurrealDB documentation - SurrealQL statements

> Every statement, with syntax and examples. This is one of the bundles the SurrealDB documentation is split into. The page index at https://surrealdb.com/docs/llms.txt lists every bundle, and https://surrealdb.com/docs/llms-full.txt holds every page. Each page starts with a "Source:" line naming its canonical URL, and every page is also available individually by appending `.md` to its URL. In code examples, a fenced block whose title contains "output" holds the result of the block above it rather than runnable code, and a qualifier such as "Example output" or "Possible output" means the value shown is one of several possible ones. Inside a block, a "//-" comment marks a value the statement above it returned, while "--" is an ordinary comment.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/access

# ACCESS

The ACCESS statement can be used to manage access grants.

> [!NOTE]
> Before SurrealDB 3.0.0, the `ACCESS` statement was experimental and required the server to be started with `--allow-experimental bearer_access`. From 3.0.0 it is available without that flag.

The `ACCESS` statement can be used to manage access grants. It provides the ability to generate access grants using certain access methods, such as bearer keys defined with the [`DEFINE ACCESS ... TYPE BEARER`](/docs/reference/query-language/statements/define/access/bearer.md) statement, as well as the ability to show, revoke and purge such grants.

By default, the `ACCESS` statement will default to referencing access methods defined at the current level specified with the [`USE`](/docs/reference/query-language/statements/use.md) statement. As with other statements, access methods defined at any level can be referenced by using the `ON` clause.

Operations that either create, revoke or purge access grants using the `ACCESS` statement will be logged in the server as long as it is running with the `INFO` level (the default) or any higher verbosity level. These log lines carry a target ending in `statements::access`, such as `surrealdb_core::expr::statements::access`.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
ACCESS @name [ ON [ ROOT | NAMESPACE | DATABASE ] ]
	GRANT [ FOR USER @name | FOR RECORD @record ]
	| SHOW [ GRANT @id | ALL | WHERE @expression ] 
	| REVOKE [ GRANT @id | ALL | WHERE @expression ] 
	| PURGE [ EXPIRED | REVOKED [ , EXPIRED | REVOKED ] ] [ FOR @duration ]
```

## `GRANT`

The `GRANT` clause creates and returns a grant for a certain subject using the specified access method. This subject can be a [system user](/docs/learn/security/authentication/users.md#system-users) or [record user](/docs/learn/security/authentication/users.md#record-users). Access grants can be used to access SurrealDB as that subject until they become expired or revoked.

When creating a grant, a secret (e.g. a key) corresponding with the grant will be returned. This secret should be stored securely, as it will no longer be displayed by SurrealDB, instead being printed as `[REDACTED]` whenever the grant details are shown.

```syntax title="SurrealQL Syntax"
ACCESS @name [ ON [ ROOT | NAMESPACE | DATABASE ] ] 
	GRANT [ FOR USER @name | FOR RECORD @record ]
```

### Example: grant for automation using system user

```surql
-- Define system user for automation
DEFINE USER automation ON DATABASE PASSWORD 'secret' ROLES VIEWER;
-- Define bearer access method to generate API keys
DEFINE ACCESS api
  ON DATABASE TYPE BEARER FOR USER DURATION FOR GRANT 10d;
-- Generate bearer grant to be used by the automation
ACCESS api GRANT FOR USER automation;
```

```surql title="Example output"
-- Query 1
NONE
-- Query 2
NONE
-- Query 3
{
        ac: 'api',
        creation: d'2024-12-16T16:15:51.517384293Z',
        expiration: d'2024-12-26T16:15:51.517386053Z',
        grant: {
                id: 'BNb2pS0GmaJz',
                key:
                  'surreal-bearer-BNb2pS0GmaJz-5eTfQ5uEu8jbRb3oblqVMAt8'
        },
        id: 'BNb2pS0GmaJz',
        revocation: NONE,
        subject: {
                user: 'automation'
        },
        type: 'bearer'
}
```

### Example: grant for end-user using record user

```surql
-- Create record representing a user
CREATE user:1 CONTENT { name: "tobie" };
-- Define bearer access method to generate API keys
DEFINE ACCESS api
  ON DATABASE TYPE BEARER FOR RECORD DURATION FOR GRANT 10d;
-- Generate bearer grant to be used by the user
ACCESS api GRANT FOR RECORD user:1;
```

```surql title="Example output"
-- Query 1
[
        {
                id: user:1,
                name: 'tobie'
        }
]
-- Query 2
NONE
-- Query 3
{
        ac: 'api',
        creation: d'2024-12-16T16:16:41.996932810Z',
        expiration: d'2024-12-26T16:16:41.996934501Z',
        grant: {
                id: 'sRLEKGxObJuM',
                key:
                  'surreal-bearer-sRLEKGxObJuM-iUUFe1vijFDaFDW7jceZJDkX'
        },
        id: 'sRLEKGxObJuM',
        revocation: NONE,
        subject: {
                record: user:1
        },
        type: 'bearer'
}
```

## `SHOW`

The `SHOW` clause displays the details of grants created with a specific access method. The statement allows showing the details of individual grants, all grants or only grants matching a particular SurrealQL expression. Beware that, in situations where grants are automatically created, showing all grants at once may be impractical and filtering is advised.

Note that any secrets (e.g. keys) associated with the grant will not be displayed and instead will be shown as `[REDACTED]`.

```syntax title="SurrealQL Syntax"
ACCESS @name [ ON [ ROOT | NAMESPACE | DATABASE ] ]
	SHOW [ GRANT @id | ALL | WHERE @expression ] 
```

### Example: Showing the details of a specific grant

```surql
-- Create record representing a user
CREATE user:1 CONTENT { name: "tobie" };
-- Define bearer access method to generate API keys
DEFINE ACCESS api
  ON DATABASE TYPE BEARER FOR RECORD DURATION FOR GRANT 10d;
-- Generate bearer grant to be used by the user
ACCESS api GRANT FOR RECORD user:1;
```

```surql title="Example output"
-- Query 1
[
        {
                id: user:1,
                name: 'tobie'
        }
]
-- Query 2
NONE
-- Query 3
{
        ac: 'api',
        creation: d'2024-12-16T16:17:24.903832476Z',
        expiration: d'2024-12-26T16:17:24.903834523Z',
        grant: {
                id: 'JdvDFKMCVYoM',
                key:
                  'surreal-bearer-JdvDFKMCVYoM-0ahEAVY6egVdg33Vs5gc6J4h'
        },
        id: 'JdvDFKMCVYoM',
        revocation: NONE,
        subject: {
                record: user:1
        },
        type: 'bearer'
}
```

```surql
ACCESS api SHOW GRANT JdvDFKMCVYoM;
```

```surql title="Output"
{
        ac: 'api',
        creation: d'2024-12-16T16:17:24.903832476Z',
        expiration: d'2024-12-26T16:17:24.903834523Z',
        grant: {
                id: 'JdvDFKMCVYoM',
                key: '[REDACTED]'
        },
        id: 'JdvDFKMCVYoM',
        revocation: NONE,
        subject: {
                record: user:1
        },
        type: 'bearer'
}
```

### Example: Showing the details of all grants for users of a certain name

Since the `subject` attribute of grants associated with a record is a record identifier, it can be used as a [record link](/docs/reference/query-language/language-primitives/record-links.md) in order to access any record fields. This can be used to filter grants associated with record users matching certain conditions based on arbitrary data.

```surql
-- Create records representing users
CREATE user:1 CONTENT { name: "tobie" };
CREATE user:2 CONTENT { name: "jaime" };
-- Define bearer access method to generate API keys
DEFINE ACCESS api
  ON DATABASE TYPE BEARER FOR RECORD DURATION FOR GRANT 10d;
-- Generate bearer grants to be used by the users
ACCESS api GRANT FOR RECORD user:1;
ACCESS api GRANT FOR RECORD user:2;
```

```surql title="Example output"
-- Query 1
[
        {
                id: user:1,
                name: 'tobie'
        }
]
-- Query 2
[
        {
                id: user:2,
                name: 'jaime'
        }
]
-- Query 3
NONE
-- Query 4
{
        ac: 'api',
        creation: d'2024-12-16T16:18:57.061692071Z',
        expiration: d'2024-12-26T16:18:57.061694228Z',
        grant: {
                id: 'HaJ19zCnP6RI',
                key:
                  'surreal-bearer-HaJ19zCnP6RI-R545vHcTbSCYdHnxIsVnjSFu'
        },
        id: 'HaJ19zCnP6RI',
        revocation: NONE,
        subject: {
                record: user:1
        },
        type: 'bearer'
}
-- Query 5
{
        ac: 'api',
        creation: d'2024-12-16T16:18:57.063673293Z',
        expiration: d'2024-12-26T16:18:57.063674755Z',
        grant: {
                id: 'ND2ZegEHfUGl',
                key:
                  'surreal-bearer-ND2ZegEHfUGl-JGPSr162qJ2bN8kURV8mYaLv'
        },
        id: 'ND2ZegEHfUGl',
        revocation: NONE,
        subject: {
                record: user:2
        },
        type: 'bearer'
}
```

```surql
-- Setup from the example above
-- Create records representing users
CREATE user:1 CONTENT { name: "tobie" };
CREATE user:2 CONTENT { name: "jaime" };
-- Define bearer access method to generate API keys
DEFINE ACCESS api
  ON DATABASE TYPE BEARER FOR RECORD DURATION FOR GRANT 10d;
-- Generate bearer grants to be used by the users
ACCESS api GRANT FOR RECORD user:1;
ACCESS api GRANT FOR RECORD user:2;

ACCESS api SHOW WHERE subject.record.name = "tobie";
```

```surql title="Example output"
[
        {
                ac: 'api',
                creation: d'2024-12-16T16:18:57.061692071Z',
                expiration: d'2024-12-26T16:18:57.061694228Z',
                grant: {
                        id: 'HaJ19zCnP6RI',
                        key: '[REDACTED]'
                },
                id: 'HaJ19zCnP6RI',
                revocation: NONE,
                subject: {
                        record: user:1
                },
                type: 'bearer'
        }
]
```

## `REVOKE`

The `REVOKE` clause revokes grants created with a specific access method. Revoking a grant ensures that the grant can no longer be used to authenticate. The grant will continue existing in revoked form and the time of the revocation is recorded in the details of the grant. Grants that have already been revoked cannot be revoked again. The statement allows revoking individual grants, all grants or only grants matching a particular SurrealQL expression.

From SurrealDB 4.0, a token issued by a bearer access method is checked against its grant on every request, so revoking a grant also refuses every token already issued from it, from the next request. A session that is already authenticated, such as an open WebSocket connection, stays signed in until the session expires. Tokens issued before 4.0 are refused after the upgrade, and their holders sign in again with the bearer key.

```syntax title="SurrealQL Syntax"
ACCESS @name [ ON [ ROOT | NAMESPACE | DATABASE ] ]
	REVOKE [ GRANT @id | ALL | WHERE @expression ] 
]
```

### Example: Revoking a specific grant

```surql
-- Create record representing a user
CREATE user:1 CONTENT { name: "tobie" };
-- Define bearer access method to generate API keys
DEFINE ACCESS api
  ON DATABASE TYPE BEARER FOR RECORD DURATION FOR GRANT 10d;
-- Generate bearer grant to be used by the user
ACCESS api GRANT FOR RECORD user:1;
```

```surql title="Example output"
-- Query 1
[
        {
                id: user:1,
                name: 'tobie'
        }
]
-- Query 2
NONE
-- Query 3
{
        ac: 'api',
        creation: d'2024-12-17T10:36:09.215762475Z',
        expiration: d'2024-12-27T10:36:09.216227523Z',
        grant: {
                id: 'NJ2I2d7OXxN9',
                key:
                  'surreal-bearer-NJ2I2d7OXxN9-Oa5LqF36IzfURpo6Bhxy9WMF'
        },
        id: 'NJ2I2d7OXxN9',
        revocation: NONE,
        subject: {
                record: user:1
        },
        type: 'bearer'
}
```

```surql
ACCESS api REVOKE GRANT NJ2I2d7OXxN9;
```

```surql title="Output"
[
        [
                {
                        ac: 'api',
                        creation: d'2024-12-17T10:36:09.215762475Z',
                        expiration: d'2024-12-27T10:36:09.216227523Z',
                        grant: {
                                id: 'NJ2I2d7OXxN9',
                                key: '[REDACTED]'
                        },
                        id: 'NJ2I2d7OXxN9',
                        revocation: d'2024-12-17T10:36:52.740438379Z',
                        subject: {
                                record: user:1
                        },
                        type: 'bearer'
                }
        ]
]
```

### Example: Revoking all grants for users of a certain name

Since the `subject` attribute of grants associated with a record is a record identifier, it can be used as a [record link](/docs/reference/query-language/language-primitives/record-links.md) in order to access any record fields. This can be used to filter grants associated with record users matching certain conditions based on arbitrary data.

```surql
-- Create records representing users
CREATE user:1 CONTENT { name: "tobie" };
CREATE user:2 CONTENT { name: "jaime" };
-- Define bearer access method to generate API keys
DEFINE ACCESS api
  ON DATABASE TYPE BEARER FOR RECORD DURATION FOR GRANT 10d;
-- Generate bearer grants to be used by the users
ACCESS api GRANT FOR RECORD user:1;
ACCESS api GRANT FOR RECORD user:2;
```

```surql title="Example output"
-- Query 1
[
        {
                id: user:1,
                name: 'tobie'
        }
]
-- Query 2
[
        {
                id: user:2,
                name: 'jaime'
        }
]
-- Query 3
NONE
-- Query 4
{
        ac: 'api',
        creation: d'2024-12-17T10:42:35.040901759Z',
        expiration: d'2024-12-27T10:42:35.040903414Z',
        grant: {
                id: 'mjSACes6sej4',
                key:
                  'surreal-bearer-mjSACes6sej4-WbEPMgmLTO3Jfg3po4we9m0V'
        },
        id: 'mjSACes6sej4',
        revocation: NONE,
        subject: {
                record: user:1
        },
        type: 'bearer'
}
-- Query 5
{
        ac: 'api',
        creation: d'2024-12-17T10:42:35.043162877Z',
        expiration: d'2024-12-27T10:42:35.043164533Z',
        grant: {
                id: 'RFilJMRp9lZi',
                key:
                  'surreal-bearer-RFilJMRp9lZi-OmflYxXwikDAvm8CNpsWYxd6'
        },
        id: 'RFilJMRp9lZi',
        revocation: NONE,
        subject: {
                record: user:2
        },
        type: 'bearer'
}
```

```surql
-- Setup from the example above
-- Create records representing users
CREATE user:1 CONTENT { name: "tobie" };
CREATE user:2 CONTENT { name: "jaime" };
-- Define bearer access method to generate API keys
DEFINE ACCESS api
  ON DATABASE TYPE BEARER FOR RECORD DURATION FOR GRANT 10d;
-- Generate bearer grants to be used by the users
ACCESS api GRANT FOR RECORD user:1;
ACCESS api GRANT FOR RECORD user:2;

ACCESS api REVOKE WHERE subject.record.name = "tobie";
```

```surql title="Example output"
[
        [
                {
                        ac: 'api',
                        creation: d'2024-12-17T10:42:35.040901759Z',
                        expiration: d'2024-12-27T10:42:35.040903414Z',
                        grant: {
                                id: 'mjSACes6sej4',
                                key: '[REDACTED]'
                        },
                        id: 'mjSACes6sej4',
                        revocation: d'2024-12-17T10:43:23.944198560Z',
                        subject: {
                                record: user:1
                        },
                        type: 'bearer'
                }
        ]
]
```

## `PURGE`

The `PURGE` clause completely removes grants created with a specific access method that have already been expired or revoked. In scenarios with very large amount of grants associated with an access method (e.g. when grants are automatically generated), purging inactive grants can improve the performance and experience of auditing grants with the `SHOW` clause. In some very high volume scenarios where grants are created by the hundreds of millions, purging may be necessary to limit the probability of collisions resulting in failure to create new grants. Note that the performance cost of validating a grant is independent from the number of existing grants, regardless of whether they are active or inactive.

Beware that any details associated with purged grants will be permanently lost and will no longer be available for auditing purposes. The `FOR` clause can be used to establish a minimum grace period after which expired or revoked grants should be purged. As with other security-sensitive operations related with the `ACCESS` statement, the purging of grants is logged in the SurrealDB server.

The clause will return the details of all grants that have successfully been purged and its performance will depend on the number of purged grants.

```syntax title="SurrealQL Syntax"
ACCESS @name [ ON [ ROOT | NAMESPACE | DATABASE ] ]
	PURGE [ EXPIRED | REVOKED [ , EXPIRED | REVOKED ] ] [ FOR @duration ]
]
```

### Example: Purging grants that have been expired

```surql
DEFINE ACCESS api ON DATABASE TYPE BEARER FOR RECORD;
ACCESS api PURGE EXPIRED;
```

### Example: Purging grants that have been revoked for more than 90 days

```surql
DEFINE ACCESS api ON DATABASE TYPE BEARER FOR RECORD;
ACCESS api PURGE REVOKED FOR 90d;
```

### Example: Purging all grants that have been invalid for more than a year

```surql
DEFINE ACCESS api ON DATABASE TYPE BEARER FOR RECORD;
ACCESS api PURGE EXPIRED, REVOKED FOR 1y;
```

## Improving error output

To improve the output of an error message inside an `ACCESS` statement, a [`THROW`](/docs/reference/query-language/statements/throw.md) statement can be used.

Follow these steps to see the output in practice.

First, start the SurrealDB server with a root user:

```bash
surreal db start --user root --pass secret
```

Log in as the root user, choose the namespace `test` and database `test`, and run the following `DEFINE ACCESS` command.

```surql
DEFINE ACCESS account ON DATABASE TYPE RECORD
    SIGNUP ({
    IF $email = "me@me.com" {
        THROW "That's my email!!!"
    } ELSE {
        CREATE user SET email = $email,
          pass = crypto::argon2::generate($pass)}
    })
    SIGNIN ( SELECT * FROM user WHERE email = $email
      AND crypto::argon2::compare(pass, $pass) )
    DURATION FOR TOKEN 15m, FOR SESSION 12h
;
```

As the `THROW` statement checks for the email address `me@me.com`, this can be tested using CURL at the [`signup`](/docs/reference/protocols/http-protocol.md#signup) endpoint via the following command.

```bash
curl -X POST -H "Accept: application/json" -d '{"ns":"main","db":"main","ac":"account", "email": "me@me.com", "pass": "strongpassword"}' http://localhost:8000/signup
```

The error output shows the user-defined error message `That's my email!!!`.

```bash title="Output"
{"code":400,"details":"Request problems detected","description":"There is a problem with your request. Refer to the documentation for further information.","information":"There was a problem with the database: An error occurred: That's my email!!!"
```

In all other cases, the signup process will work, returning a token.

```bash
curl -X POST -H "Accept: application/json" -d '{"ns":"main","db":"main","ac":"account", "email": "someotheremail@me.com", "pass": "strongpassword"}' http://localhost:8000/signup
```

```bash title="Output"
{"code":200,"details":"Authentication succeeded","token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE3NDYwNzIxOTAsIm5iZiI6MTc0NjA3MjE5MCwiZXhwIjoxNzQ2MDczMDkwLCJpc3MiOiJTdXJyZWFsREIiLCJqdGkiOiI3YTc0ZjQ5ZS02OWMxLTRiMjMtYmRhNy05YThkNTNjNWFiZmIiLCJOUyI6InRlc3QiLCJEQiI6InRlc3QiLCJBQyI6ImFjY291bnQiLCJJRCI6InVzZXI6b2tlZjN5bmI4eXJkd2l3b3h1YjEifQ.4t1xwVkl36PeTFuBj0d41D6A-bwCx7LoNoLlj6yokA8wOKwEa1ldjBzTldZEmylLgP5-q8D4wp6f9Y6ntBZyPA","refresh":null}
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/alter/access

# ALTER ACCESS

The ALTER ACCESS statement can be used to modify an existing defined access.

_(since v3.0.5)_

The `ALTER ACCESS` statement can be used to modify an existing defined [access](/docs/reference/query-language/statements/define/access.md).

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
ALTER ACCESS [ IF EXISTS ] @name
  ON [ ROOT | NAMESPACE | DATABASE ]
  [ AUTHENTICATE @expression | DROP AUTHENTICATE ]
  [ CONTEXT @expression | DROP CONTEXT ]
  [ DURATION
    [ FOR GRANT [ @duration | NONE ] ]
    [ FOR TOKEN [ @duration | NONE ] ]
    [ FOR SESSION [ @duration | NONE ] ]
  ]
  [ COMMENT @string | DROP COMMENT ]
```

Note that this statement does not allow modification of the access type itself (`RECORD` / `JWT` / `BEARER`), only its duration, the `AUTHENTICATE` and `CONTEXT` clauses, and a `COMMENT`.

## Example usage

```surql
-- Define an access
DEFINE ACCESS account ON DATABASE TYPE RECORD
	SIGNUP ( CREATE user SET email = $email,
	  pass = crypto::argon2::generate($pass) )
	SIGNIN ( SELECT * FROM user WHERE email = $email
	  AND crypto::argon2::compare(pass, $pass) )
	DURATION FOR TOKEN 15m, FOR SESSION 12h;

-- Shorten the token duration
ALTER ACCESS account ON DATABASE DURATION FOR TOKEN 1m;
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/alter/analyzer

# ALTER ANALYZER

The ALTER ANALYZER statement can be used to modify an existing defined analyzer.

_(since v3.0.5)_

The `ALTER ANALYZER` statement can be used to modify an existing defined [analyzer](/docs/reference/query-language/statements/define/analyzer.md).

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
ALTER ANALYZER [ IF EXISTS ] @name
  [ FUNCTION fn::@function | DROP FUNCTION ]
  [ TOKENIZERS @tokenizer, ... | DROP TOKENIZERS ]
  [ FILTERS @filter, ... | DROP FILTERS ]
  [ COMMENT @string | DROP COMMENT ]
```

## Example usage

```surql
-- Define an analyzer
DEFINE ANALYZER example_edgengram TOKENIZERS class FILTERS
  edgengram(1,3);

-- Shorten the edgengram
ALTER ANALYZER example_edgengram FILTERS edgengram(1,2);

-- Check the output
search::analyze("example_edgengram", "Apple banana!!");
```

```surql title="Output"
[
	'A',
	'Ap',
	'b',
	'ba',
	'!',
	'!!'
]
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/alter/api

# ALTER API

The ALTER API statement can be used to modify an existing defined API.

_(since v3.0.5)_

The `ALTER API` statement can be used to modify an existing defined [API](/docs/reference/query-language/statements/define/api.md).

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
ALTER API [ IF EXISTS ] @endpoint
  [ FOR any [ @api_config ] [ THEN @expression | DROP THEN ] ]
  [ FOR @http_method, ... [ MIDDLEWARE @function, ... ] [ THEN @expression ] ]
  [ FOR @http_method, ... DROP THEN ]
  [ SECURITY DEFINER | SECURITY INVOKER ]
  [ COMMENT @string | DROP COMMENT ]
```

## Example usage

```surql
-- Define a simple API
DEFINE API "/test"
    FOR get
        THEN {
            {
                body: {
                    some: "data"
                }
            };
        };

-- Make a random function
DEFINE FUNCTION fn::feeling_lucky() -> int {
    rand::enum(200, 404)
};

-- Set it as the HTTP status
ALTER API "/test" FOR get THEN {
    {
        status: fn::feeling_lucky(),
        body: {
            some: "data"
        }
    }
};

-- status is either 200 or 404
api::invoke("/test");
```

```surql title="Possible output"
{
	body: {
		some: 'data'
	},
	headers: {
		"x-surreal-request-id": '95fd0577-5b97-4dc1-b98e-c284f0e36a63'
	},
	request_id: '95fd0577-5b97-4dc1-b98e-c284f0e36a63',
	status: 404
}
```

### Changing the security mode

From SurrealDB 4.0, the `SECURITY` clause changes whether the endpoint's body runs with the permissions of the user who defined it (`SECURITY DEFINER`) or with those of the caller (`SECURITY INVOKER`), and leaves the rest of the definition as it is. An `ALTER API` statement without the clause keeps the current mode. See [Running the body with the caller's permissions](/docs/reference/query-language/statements/define/api.md#running-the-body-with-the-callers-permissions) for how the two modes differ.

```surql
-- Setup from the example above
DEFINE API "/test"
    FOR get
        THEN {
            {
                body: {
                    some: "data"
                }
            };
        };

ALTER API "/test" SECURITY INVOKER;
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/alter/bucket

# ALTER BUCKET

The ALTER BUCKET statement can be used to modify an existing defined bucket.

_(since v3.0.5)_

The `ALTER BUCKET` statement can be used to modify an existing defined [bucket](/docs/reference/query-language/statements/define/bucket.md).

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
ALTER BUCKET [ IF EXISTS ] @name
  [ ON [ ROOT | NAMESPACE | DATABASE ] ]
  [ READONLY | DROP READONLY ]
  [ BACKEND @string ]
  [ PERMISSIONS @expression ]
  [ COMMENT @string | DROP COMMENT ]
  [ REVOKE SIGNATURES ]
```

## Example usage

```surql
DEFINE BUCKET my_bucket BACKEND "memory";

ALTER BUCKET my_bucket COMMENT "Should we make this read-only too??";
```

## Changing the backend

_(since v4.0.0)_

`BACKEND` moves the bucket to another backend. The files in the old backend stay where they are, and the bucket serves the files of the new one. A `global://` backend needs a root user, as on [`DEFINE BUCKET`](/docs/reference/query-language/statements/define/bucket.md#global-backend). From SurrealDB 4.0, a bucket always has a backend, so `DROP BACKEND` no longer parses.

Changing `BACKEND` or `READONLY` makes SurrealDB open a new connection to the backend once the statement commits. For a `memory` backend, a new connection starts empty, so a `memory` bucket loses its files when either clause changes.

## Root and namespace buckets

_(since v4.0.0)_

Without `ON`, `ALTER BUCKET` changes a bucket of the database in use. To change a [root or namespace bucket](/docs/reference/query-language/statements/define/bucket.md#root-and-namespace-buckets), name its level:

```surql
-- Setup
DEFINE BUCKET shared ON NAMESPACE BACKEND "memory";

ALTER BUCKET shared ON NAMESPACE COMMENT "Files for every database in this namespace";
```

## Revoking presigned URLs

_(since v4.0.0)_

`REVOKE SIGNATURES` stops every [presigned URL](/docs/learn/schema-management/files/presigned-urls.md) already issued for the bucket from working. A request with one of those URLs then answers `403`. URLs created after the statement work as usual.

```surql
-- Setup from the example above
DEFINE BUCKET my_bucket BACKEND "memory";

ALTER BUCKET my_bucket REVOKE SIGNATURES;
```

Each bucket holds a random value that is part of the key that signs its URLs, and `REVOKE SIGNATURES` replaces it. `DEFINE BUCKET ... OVERWRITE` keeps the value, so redefining a bucket does not make revoked URLs work again. Removing a bucket and defining it again gives it a new value, which also revokes its URLs. To revoke the URLs of every bucket on a server at once, change `SURREAL_BUCKET_PRESIGN_SECRET`.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/alter/config

# ALTER CONFIG

The ALTER statement can be used to change authentication access and behaviour, global parameters, table configurations, table events, schema definitions, and indexes.

_(since v3.0.5)_

The `ALTER CONFIG` statement can be used to modify an existing defined [config](/docs/reference/query-language/statements/define/config.md).

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
ALTER CONFIG [ IF EXISTS ]
  ( API
      [ MIDDLEWARE @function(...), ... ]
      PERMISSIONS [ NONE | FULL | @expression ]
  | GRAPHQL
      TABLES [ AUTO | NONE | INCLUDE @table, ... | EXCLUDE @table, ... ]
      FUNCTIONS [ AUTO | NONE | INCLUDE @function, ... | EXCLUDE @function, ... ]
      [ DEPTH @integer ]
      [ COMPLEXITY @integer ]
      [ INTROSPECTION NONE ]
  | DEFAULT
      NAMESPACE @namespace
      DATABASE @database
  )
  [ COMMENT @string | DROP COMMENT ]
```

## Example usage

```surql
DEFINE CONFIG GRAPHQL TABLES AUTO FUNCTIONS AUTO;

ALTER CONFIG GRAPHQL FUNCTIONS NONE;
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/alter/database

# ALTER DATABASE

The ALTER DATABASE statement can be used to modify the database.

_(since v3.0.0)_

The `ALTER DATABASE` statement can be used to modify a database. Without a name, it applies to the current database, which is why an `IF EXISTS` clause does not exist.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
ALTER DATABASE [ @name ]
    COMPACT |
    COMPATIBILITY 3 | 4
```

## COMPACT

Performs storage compaction on the current database keyspace. To compact other resources, use [ALTER SYSTEM](/docs/reference/query-language/statements/alter/system.md) to compact the entire datastore, [ALTER NAMESPACE](/docs/reference/query-language/statements/alter/namespace.md) to compact the current namespace keyspace, or [ALTER TABLE](/docs/reference/query-language/statements/alter/table.md) to compact a specific table keyspace.

The storage engine carries out the compaction. In SurrealDB 4.0, SurrealKV supports it: it writes recent changes to disk, merges the data files that hold the keys, and drops deleted data and old versions that no reader can see, which frees their space. The statement returns once the compaction is done, and reads and writes carry on meanwhile. Before 4.0, RocksDB was the only engine that supported compaction requests. The in-memory engine and TiKV do not support them, and return the following error:

```surql
'There was a problem with the key-value store: The storage layer does not support compaction requests.'
```

A successful compaction returns `NONE`.

```surql
ALTER DATABASE COMPACT;
```

```surql title="Output"
NONE
```

## COMPATIBILITY

_(since v4.0.0)_

Sets the [compatibility level](/docs/reference/query-language/statements/define/database.md#compatibility-level) of a database, `3` or `4`. A database that a 3.x release created is at level 3 after an upgrade, and moves to level 4 with:

```surql
ALTER DATABASE COMPATIBILITY 4;
```

Raising a database to level 4 checks every field of its `SCHEMAFULL` tables in the background. `INFO FOR TABLE` then lists, under `migrations.verification`, each field with the number of records whose value does not fit its definition, and the fields whose values all fit under `migrations.guaranteed`:

```surql
INFO FOR TABLE person;
```

```surql title="Example output"
{
	events: {},
	fields: {
		age: 'DEFINE FIELD age ON person TYPE string PERMISSIONS FULL'
	},
	indexes: {},
	lives: {},
	migrations: {
		generation: 3,
		guaranteed: [],
		migrations: [],
		verification: [
			{
				failures: 2,
				field: 'age',
				finished: true
			}
		]
	},
	tables: {}
}
```

A field with failures is one that was changed at level 3 without its records being updated. A [`MIGRATE EXISTING ROWS`](/docs/reference/query-language/statements/define/field.md#migrating-existing-records) clause on the field's definition converts those records:

```surql
DEFINE FIELD OVERWRITE age ON person TYPE string
    MIGRATE EXISTING ROWS AS age_to_string USING <string> $value FALLBACK '';
```

Raise the level only once every node runs 4.0. A datastore that still writes the 3.x record format, such as a TiKV cluster that has not been switched with `SURREAL_FEATURE_LEVEL=4.0`, refuses level 4.

## See also

* [`DEFINE DATABASE`](/docs/reference/query-language/statements/define/database.md)

---

Source: https://surrealdb.com/docs/reference/query-language/statements/alter/event

# ALTER EVENT

The ALTER EVENT statement can be used to modify an existing defined event.

_(since v3.0.5)_

The `ALTER EVENT` statement can be used to modify an existing defined [event](/docs/reference/query-language/statements/define/event.md).

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
ALTER EVENT [ IF EXISTS ] @name ON [ TABLE ] @table
  [ ASYNC [ RETRY @retry ] [ MAXDEPTH @max_depth ] | DROP ASYNC ]
  [ WHEN @condition | DROP WHEN ]
  [ THEN @action, ... | DROP THEN ]
  [ COMMENT @string | DROP COMMENT ]
```

## Example usage

```surql
DEFINE FIELD status ON post TYPE "submitted" | "published" DEFAULT "submitted";

-- Define an event
DEFINE EVENT publish_post ON TABLE publication
    WHEN $event = "CREATE"
    THEN (
        FOR $post IN $after.posts {
            UPDATE $post SET status = "published";
        }        
    );

-- Make it async
ALTER EVENT publish_post ON TABLE publication ASYNC;

CREATE post:one SET content = "I read the news today, oh boy...";
CREATE post:two SET content = "On the banks of Tuonela Bleach the skeletons of kings";
CREATE post:three SET content = "뭐 화끈한 일 뭐 신나는 일 없을까";
CREATE publication SET posts = [post:one, post:two, post:three];

SELECT * FROM post;
```

```surql title="Output once async events processed"
[
	{
		content: 'I read the news today, oh boy...',
		id: post:one,
		status: 'submitted'
	},
	{
		content: '뭐 화끈한 일 뭐 신나는 일 없을까',
		id: post:three,
		status: 'submitted'
	},
	{
		content: 'On the banks of Tuonela Bleach the skeletons of kings',
		id: post:two,
		status: 'submitted'
	}
]
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/alter/field

# ALTER FIELD

The ALTER FIELD statement is used to change or entirely drop clauses of a defined field on a table.

The `ALTER FIELD` statement is used to change or entirely drop clauses of a defined field on a table.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
ALTER FIELD [ IF EXISTS ] @name ON [ TABLE ] @table 
[ 
    DROP TYPE |
    DROP SQL TYPE |
    DROP FLEXIBLE |
    DROP READONLY |
    DROP INLINE |
    DROP VALUE |
    DROP ASSERT |
    DROP DEFAULT |
    DROP COMMENT |
    DROP REFERENCE |
    FLEXIBLE |
    READONLY |
    INLINE |
    REFERENCE |
    TYPE @type |
    SQL TYPE [ POSTGRESQL | MYSQL | DYNAMODB ] @string |
    VALUE @value |
    ASSERT @expression |
    DEFAULT [ ALWAYS ] @expression |
    [ PERMISSIONS [ NONE | FULL
		| FOR select @expression
		| FOR create @expression
		| FOR update @expression
		| FOR delete @expression
	] ]
    COMMENT @string |
    MIGRATE EXISTING ROWS AS @name USING @expression [ FALLBACK @value ]
]
```

## Examples

As `ALTER FIELD` contains the same clauses available in a [`DEFINE FIELD`](/docs/reference/query-language/statements/define/field.md) statement, be sure to see that page for more examples.

Here is one example in which the `name` field is defined for a record `user`:

```surql
DEFINE FIELD name ON user TYPE string;
```

Later on, a database-wide [parameter](/docs/reference/query-language/statements/define/param.md) is defined to disallow certain user names. This can be followed up with an `ALTER FIELD` statement to add the `ASSERT` clause to it.

```surql
-- Setup from the example above
DEFINE FIELD name ON user TYPE string;

DEFINE PARAM $DISALLOWED_NAMES VALUE ["Lord British", "Lord Blackthorn"];
ALTER FIELD name ON user ASSERT $value NOT IN $DISALLOWED_NAMES;
CREATE user SET name = "Lord British";
```

```surql title="Output"
"Found 'Lord British' for field `name`, with record `user:yn4yttkg5w683q2937bq`, but field must conform to: $value NOTINSIDE $DISALLOWED_NAMES"
```

## Migrating existing records

_(since v4.0.0)_

`MIGRATE EXISTING ROWS` converts the values that records already hold when `ALTER FIELD` changes the field's type. In a database at [compatibility level](/docs/reference/query-language/statements/define/database.md#compatibility-level) 4, a `SCHEMAFULL` table that holds records refuses a type change without it unless the new type accepts every old value.

```surql
-- In a database at compatibility level 4
DEFINE TABLE person SCHEMAFULL;
DEFINE FIELD age ON person TYPE int;
CREATE person:1 SET age = 37;

ALTER FIELD age ON person TYPE string
    MIGRATE EXISTING ROWS AS age_to_string USING <string> $value FALLBACK '';
SELECT * FROM person;
```

```surql title="Output"
[{ age: '37', id: person:1 }]
```

The rules for the transform, the `FALLBACK` value and the fields that cannot be migrated are in [Migrating existing records](/docs/reference/query-language/statements/define/field.md#migrating-existing-records).

When several fields share the same set of values, a type defined with `DEFINE TYPE` can change all of them in one statement. [`ALTER TYPE` or `ALTER FIELD`](/docs/reference/query-language/statements/alter/type.md#alter-type-or-alter-field) compares the two with the same example.

## Changing the declared SQL type

_(since v4.0.0)_

`SQL TYPE` sets or replaces the [declared SQL type](/docs/reference/query-language/statements/define/field.md#declaring-a-sql-type) of a field, and `DROP SQL TYPE` removes it. The new type applies to the writes that follow. Records that the table already holds are not checked when the type changes, so a record that does not fit the new type fails its next write.

```surql
DEFINE TABLE customer SCHEMAFULL;
DEFINE FIELD name ON customer TYPE string
    SQL TYPE POSTGRESQL 'varchar(20)';

ALTER FIELD name ON customer SQL TYPE POSTGRESQL 'varchar(40)';
CREATE customer:2 SET name = 'Augusta Ada King, Countess of Lovelace';
//- [{ id: customer:2, name: 'Augusta Ada King, Countess of Lovelace' }]

ALTER FIELD name ON customer DROP SQL TYPE;
(INFO FOR TABLE customer).fields.name;
//- 'DEFINE FIELD name ON customer TYPE string PERMISSIONS FULL'
```

## See also

* [`DEFINE FIELD`](/docs/reference/query-language/statements/define/field.md)

---

Source: https://surrealdb.com/docs/reference/query-language/statements/alter/function

# ALTER FUNCTION

The ALTER FUNCTION statement can be used to modify an existing defined function.

_(since v3.0.5)_

The `ALTER FUNCTION` statement can be used to modify an existing defined [function](/docs/reference/query-language/statements/define/function.md).

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
ALTER FUNCTION [ IF EXISTS ] fn::@name
  [ ( [ $argument: @type, ... ] ) ] [ -> @type | DROP RETURNS ]
  [ { @query ... } ]
  [ COMMENT @string | DROP COMMENT ]
  [ PERMISSIONS [ NONE | FULL | WHERE @condition ] ] 
```

## Example usage

```surql
-- Declare a function
DEFINE FUNCTION fn::get_message($input: any) -> option<string> {
    $input.message
};

-- No `message` field, returns nothing
fn::get_message("wrong input");

-- Tighten up the valid input for the function
ALTER FUNCTION fn::get_message(
    $input:
        { error_code: 200, message: string }
        | {error_code: 404, message: string}
) {
    $input.message
};

-- Returns an error now
fn::get_message("wrong input");
//- "Incorrect arguments for function fn::get_message(). Failed to coerce argument `$input`: Expected `{ error_code: 200, message: string } | { error_code: 404, message: string }` but found `'wrong input'`"

-- Okay, returns 'Looks good'
fn::get_message({ error_code: 200, message: "Looks good" });
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/alter/indexes

# ALTER INDEX

The ALTER INDEX statement is used to alter a defined index on a table.

_(since v3.0.0)_

The `ALTER INDEX` statement is used to alter a defined index on a table.

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
ALTER INDEX @name ON TABLE @table
    COMMENT @string |
    PREPARE REMOVE |
    DROP COMMENT
```

## `PREPARE REMOVE` clause

As the name implies, an `ALTER INDEX PREPARE REMOVE` statement alters an index to prepare it for removal. This statement sets up a step in which the index has been decommissioned (prepared for removal), but not yet removed. At this point, `SELECT` queries with the `EXPLAIN` clause can be used to monitor query performance without the index.

```surql
DEFINE INDEX my_index ON my_table FIELDS name;

-- 1. Decommission the index
ALTER INDEX my_index ON my_table PREPARE REMOVE;

-- 2. Monitor query performance and verify queries still work
SELECT * FROM my_table WHERE name = 'Bob' EXPLAIN;

-- 3. If satisfied, permanently remove the index
REMOVE INDEX my_index ON my_table;
```

If removing the index is no longer desired, it can be restored to a useful state by using a [REBUILD INDEX](/docs/reference/query-language/statements/rebuild.md) statement.

```surql
-- Setup from the example above
DEFINE INDEX my_index ON my_table FIELDS name;
ALTER INDEX my_index ON my_table PREPARE REMOVE;

REBUILD INDEX my_index ON my_table;
```

## See also

* [`DEFINE INDEX`](/docs/reference/query-language/statements/define/indexes.md)

---

Source: https://surrealdb.com/docs/reference/query-language/statements/alter/namespace

# ALTER NAMESPACE

The ALTER NAMESPACE statement can be used to modify the namespace.

_(since v3.0.0)_

The `ALTER NAMESPACE` statement can be used to modify the namespace. `ALTER NAMESPACE` is used on the current namespace, which is why a `IF EXISTS` clause does not exist.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
ALTER NAMESPACE COMPACT
```

## COMPACT

Performs storage compaction on the current namespace keyspace. To compact other resources, use [ALTER SYSTEM](/docs/reference/query-language/statements/alter/system.md) to compact the entire datastore, [ALTER DATABASE](/docs/reference/query-language/statements/alter/database.md) to compact the current database keyspace, or [ALTER TABLE](/docs/reference/query-language/statements/alter/table.md) to compact a specific table keyspace.

The storage engine carries out the compaction. In SurrealDB 4.0, SurrealKV supports it: it writes recent changes to disk, merges the data files that hold the keys, and drops deleted data and old versions that no reader can see, which frees their space. The statement returns once the compaction is done, and reads and writes carry on meanwhile. Before 4.0, RocksDB was the only engine that supported compaction requests. The in-memory engine and TiKV do not support them, and return the following error:

```surql
'There was a problem with the key-value store: The storage layer does not support compaction requests.'
```

A successful compaction returns `NONE`.

```surql
ALTER NAMESPACE COMPACT;
```

```surql title="Output"
NONE
```

## See also

* [`DEFINE NAMESPACE`](/docs/reference/query-language/statements/define/namespace.md)

---

Source: https://surrealdb.com/docs/reference/query-language/statements/alter/overview

# ALTER

The ALTER statement can be used to change the behaviour of database resources.

The `ALTER` statement can be used to change the behaviour of database resources.

There are two main cases in which to use an `ALTER` statement:

* Modifying previously defined resources. This can currently be used to modify tables and fields. For other such modifications, use the `OVERWRITE` clause in other `DEFINE` statements.
* Modifying other resources using clauses not present in other `DEFINE` statements. Examples of this are the `PREPARE REMOVE` clause to prepare an index for removal, the `COMPACT` clause to compact the system/namespace/database/single table, and the `QUERY_TIMEOUT` clause to define or drop the query timeout for the entire datastore.

Each resource has its own `ALTER` statement:

| Statement | Alters |
| --- | --- |
| [`ALTER ACCESS`](/docs/reference/query-language/statements/alter/access.md) | An existing access method |
| [`ALTER ANALYZER`](/docs/reference/query-language/statements/alter/analyzer.md) | An existing analyzer |
| [`ALTER API`](/docs/reference/query-language/statements/alter/api.md) | An existing API definition |
| [`ALTER BUCKET`](/docs/reference/query-language/statements/alter/bucket.md) | An existing bucket |
| [`ALTER CONFIG`](/docs/reference/query-language/statements/alter/config.md) | Authentication access and GraphQL behaviour |
| [`ALTER DATABASE`](/docs/reference/query-language/statements/alter/database.md) | The current database |
| [`ALTER EVENT`](/docs/reference/query-language/statements/alter/event.md) | An existing event |
| [`ALTER FIELD`](/docs/reference/query-language/statements/alter/field.md) | A field's clauses, or drop them entirely |
| [`ALTER FUNCTION`](/docs/reference/query-language/statements/alter/function.md) | An existing custom function |
| [`ALTER INDEX`](/docs/reference/query-language/statements/alter/indexes.md) | An index on a table, including `PREPARE REMOVE` |
| [`ALTER NAMESPACE`](/docs/reference/query-language/statements/alter/namespace.md) | The current namespace |
| [`ALTER PARAM`](/docs/reference/query-language/statements/alter/param.md) | An existing parameter |
| [`ALTER SEQUENCE`](/docs/reference/query-language/statements/alter/sequence.md) | An existing sequence |
| [`ALTER SYSTEM`](/docs/reference/query-language/statements/alter/system.md) | The entire datastore, including `QUERY_TIMEOUT` |
| [`ALTER TABLE`](/docs/reference/query-language/statements/alter/table.md) | A table's schema, such as moving from schemaless to schemafull |
| [`ALTER TYPE`](/docs/reference/query-language/statements/alter/type.md) | The values of a union type, by adding or renaming them |
| [`ALTER USER`](/docs/reference/query-language/statements/alter/user.md) | An existing database, namespace or root user |

Some examples of `ALTER` statements are as follows.

## Modify a table schema

When starting a new project, you may require a table to be schemaless to allow for flexibility in the data structure. However, as the project progresses, you may want to lock down the schema to prevent new fields from being added.

An example of `ALTER` to modify an existing table:

```surql
DEFINE TABLE user SCHEMALESS;
DEFINE FIELD name ON TABLE user TYPE string;
CREATE user SET name = "LordofSalty";

-- Now make it schemafull to ensure that no other fields can be used
ALTER TABLE user SCHEMAFULL;
```

## Modify table permissions

You can also use the `ALTER` statement to change a table's permissions. An `ALTER` statement only needs to include the items to be altered, not the entire definition.

```surql
-- Shown as DEFINE TABLE user TYPE ANY SCHEMAFULL PERMISSIONS NONE
DEFINE TABLE user SCHEMAFULL;

-- Now shown as DEFINE TABLE user TYPE ANY SCHEMAFULL PERMISSIONS FULL
ALTER TABLE user PERMISSIONS FOR create FULL;
```

## Using `IF EXISTS` clause

You can use the `IF EXISTS` clause to prevent an error from occurring when trying to alter a table that does not exist.

```surql
ALTER TABLE IF EXISTS user SCHEMAFULL;
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/alter/param

# ALTER PARAM

The ALTER PARAM statement can be used to modify an existing defined param.

_(since v3.0.5)_

The `ALTER PARAM` statement can be used to modify an existing defined [param](/docs/reference/query-language/statements/define/param.md).

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
ALTER PARAM [ IF EXISTS ] $name
  [ VALUE @value ]
  [ COMMENT @string | DROP COMMENT ]
  [ PERMISSIONS [ NONE | FULL | WHERE @condition ] ]
```

Note that `ALTER PARAM` does not support `DROP VALUE` as a parameter without a value is not valid.

## Example usage

```surql
DEFINE PARAM $MODE VALUE "production" COMMENT "Don't use this param yet";

ALTER PARAM $MODE DROP COMMENT;

-- Check the statement
(INFO FOR DB).params.MODE;
```

```surql title="Output: comment is gone"
"DEFINE PARAM $MODE VALUE 'production' PERMISSIONS FULL"
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/alter/sequence

# ALTER SEQUENCE

The ALTER SEQUENCE statement is used to modify a defined sequence.

_(since v3.0.0)_

The `ALTER SEQUENCE` statement is used to modify a defined sequence.

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
ALTER SEQUENCE [ IF EXISTS ] @name [ TIMEOUT @duration ]
```

## Examples

The timeout of a sequence can be modified via an `ALTER SEQUENCE` statement. For example, a sequence can be included in the schema but effectively disabled if given a timeout of 0ns, after which `ALTER SEQUENCE` can be used to modify the timeout to make it available.

```surql
DEFINE SEQUENCE mySeq3 BATCH 1000 START 100 TIMEOUT 0ns;
INFO FOR DB.sequences;
//- { mySeq3: 'DEFINE SEQUENCE mySeq3 BATCH 1000 START 100 TIMEOUT 0ns' }
sequence::nextval('mySeq3');
//- 'The query was not executed because it exceeded the timeout: 0ns'

ALTER SEQUENCE mySeq3 TIMEOUT 100ms;
sequence::nextval('mySeq3');
//- 100
```

## See also

* [`DEFINE SEQUENCE`](/docs/reference/query-language/statements/define/sequence.md)

---

Source: https://surrealdb.com/docs/reference/query-language/statements/alter/system

# ALTER SYSTEM

The ALTER SYSTEM statement is used to alter the entire datastore.

_(since v3.0.0)_

The `ALTER SYSTEM` statement is used to alter the entire datastore. It can be used to compact the system, to set or drop a systemwide query timeout, or to set the compatibility level of new databases.

This statement is the only `ALTER` statement that does not have a corresponding `DEFINE` statement.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
ALTER SYSTEM 
    COMPACT |
    QUERY_TIMEOUT @duration |
    DROP QUERY_TIMEOUT |
    COMPATIBILITY 3 | 4
```

## `QUERY_TIMEOUT` clause

A query timeout can be set for the system as a whole. The minimum possible timeout is one millisecond, below which the value will be set as `NONE`.

```surql
ALTER SYSTEM QUERY_TIMEOUT 100ns;
INFO FOR ROOT.config;
```

```surql title="Output"
{ QUERY_TIMEOUT: NONE }
```

A value of `1ms` or more sets the timeout. It applies to each request that starts after the `ALTER SYSTEM` statement, and limits the request as a whole. A request that is already running keeps the timeout it started with, and that includes the rest of the request that holds the `ALTER SYSTEM` statement, so send the statement on its own:

```surql
ALTER SYSTEM QUERY_TIMEOUT 1ms;
```

A query sent afterwards that runs for longer than one millisecond then fails:

```surql notest
CREATE |person:100000| RETURN NONE;
```

```surql title="Error output"
'The query was not executed because it exceeded the timeout: 1ms'
```

## `COMPATIBILITY` clause

_(since v4.0.0)_

Sets the [compatibility level](/docs/reference/query-language/statements/define/database.md#compatibility-level) that a database starts at when a `DEFINE DATABASE` statement does not give one. A datastore created by SurrealDB 4.0 starts new databases at level 4. One that a 3.x release created starts them at level 3, so that every database in it behaves the same way until the level is raised.

```surql
ALTER SYSTEM COMPATIBILITY 4;
```

The clause changes only databases defined afterwards. To change an existing database, use [`ALTER DATABASE`](/docs/reference/query-language/statements/alter/database.md#compatibility).

## COMPACT clause

Compacts the entire datastore. To compact other resources, use [ALTER NAMESPACE](/docs/reference/query-language/statements/alter/namespace.md) to compact the current namespace keyspace, [ALTER DATABASE](/docs/reference/query-language/statements/alter/database.md) to compact the current database keyspace, or [ALTER TABLE](/docs/reference/query-language/statements/alter/table.md) to compact a specific table keyspace.

The storage engine carries out the compaction. In SurrealDB 4.0, SurrealKV supports it: it writes recent changes to disk, merges the data files that hold the keys, and drops deleted data and old versions that no reader can see, which frees their space. The statement returns once the compaction is done, and reads and writes carry on meanwhile. Before 4.0, RocksDB was the only engine that supported compaction requests. The in-memory engine and TiKV do not support them, and return the following error:

```surql
'There was a problem with the key-value store: The storage layer does not support compaction requests.'
```

A successful compaction returns `NONE`.

```surql
ALTER SYSTEM COMPACT;
```

```surql title="Output"
NONE
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/alter/table

# ALTER TABLE

The ALTER TABLE statement is used to alter a defined table.

The `ALTER TABLE` statement is used to alter a defined table.

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
ALTER TABLE [
	[ IF EXISTS ] @name
		[ DROP COMMENT ]
        [ DROP CHANGEFEED ]
        [ DROP INLINE EDGES ]
        [ DROP INLINE REFERENCES ]
        [ COMPACT ]
		[ SCHEMAFULL | SCHEMALESS ]
		[ TYPE [ ANY | NORMAL | RELATION [ [ IN | FROM ] @table ]
			[ [ OUT | TO ] @table ] [ ENFORCED ] [ LIGHTWEIGHT ]]]
		[ PERMISSIONS [ NONE | FULL
			| FOR select @expression
			| FOR create @expression
			| FOR update @expression
			| FOR delete @expression
		] ]
    [ CHANGEFEED @duration [ INCLUDE ORIGINAL ] ]
    [ COMMENT @string ] 
    [ INLINE EDGES @number ]
    [ INLINE REFERENCES @number ]
    [ MIGRATE EXISTING ROWS AS @name REMOVE UNDECLARED FIELDS ]
]
```

## COMPACT

_(since v3.0.0)_

Performs storage compaction on a specific table keyspace. To compact other resources, use [ALTER SYSTEM](/docs/reference/query-language/statements/alter/system.md) to compact the entire datastore, [ALTER NAMESPACE](/docs/reference/query-language/statements/alter/namespace.md) to compact the current namespace keyspace, or [ALTER DATABASE](/docs/reference/query-language/statements/alter/database.md) to compact the current database keyspace.

The storage engine carries out the compaction. In SurrealDB 4.0, SurrealKV supports it: it writes recent changes to disk, merges the data files that hold the keys, and drops deleted data and old versions that no reader can see, which frees their space. The statement returns once the compaction is done, and reads and writes carry on meanwhile. Before 4.0, RocksDB was the only engine that supported compaction requests. The in-memory engine and TiKV do not support them, and return the following error:

```surql
'There was a problem with the key-value store: The storage layer does not support compaction requests.'
```

A successful compaction returns `NONE`.

```surql
-- Setup
DEFINE TABLE user;

ALTER TABLE user COMPACT;
```

```surql title="Output"
NONE
```

## INLINE EDGES and INLINE REFERENCES

_(since v3.3.0)_

`INLINE EDGES @number` and `INLINE REFERENCES @number` set or change the cap of a table's [adjacency and reference caches](/docs/reference/query-language/statements/define/table.md#using-inline-edges-and-inline-references-to-cache-adjacency), from 0 to 256. `DROP INLINE EDGES` and `DROP INLINE REFERENCES` remove a cap, which turns that cache off. One statement can set one cap and drop the other:

```surql
-- Setup
DEFINE TABLE person;

ALTER TABLE person INLINE EDGES 8 DROP INLINE REFERENCES;
```

Any change to a cap discards the table's existing caches of that kind. They are rebuilt as edges or references are written.

## Changing the table type

`TYPE` changes what kind of records the table holds. A table that holds records of the other kind cannot change to a type that excludes them: `TYPE RELATION` is refused while the table holds a record that is not an edge, and `TYPE NORMAL` while it holds an edge. The error names the first record that does not fit:

```surql
CREATE note:1;
ALTER TABLE note TYPE RELATION;
```

```surql title="Error output"
'Cannot make `note` TYPE RELATION: it holds note:1, which is not an edge. Delete the record first, or define the table TYPE ANY'
```

`TYPE ANY` holds both kinds of record, so a change to it is always accepted. The same check applies to `DEFINE TABLE OVERWRITE` with a new type. Before SurrealDB 4.0 the change was accepted, and an export of the table then failed to import.

## MIGRATE EXISTING ROWS ... REMOVE UNDECLARED FIELDS

_(since v4.0.0)_

`REMOVE UNDECLARED FIELDS` removes every field that the table does not define from every record of the table. It is a named migration, so it runs once for a given name, in the background, and a record is cleaned the first time it is read.

```surql
DEFINE TABLE person SCHEMALESS;
CREATE person:1 SET name = 'Ada', nickname = 'A';
DEFINE FIELD name ON person TYPE string;
ALTER TABLE person SCHEMAFULL;

ALTER TABLE person MIGRATE EXISTING ROWS AS drop_undeclared
	REMOVE UNDECLARED FIELDS;
SELECT * FROM person;
```

```surql title="Output"
[{ id: person:1, name: 'Ada' }]
```

See [Migrating existing records](/docs/reference/query-language/statements/define/field.md#migrating-existing-records) for migrations that convert the values of one field.

## See also

* [`DEFINE TABLE`](/docs/reference/query-language/statements/define/table.md)

---

Source: https://surrealdb.com/docs/reference/query-language/statements/alter/type

# ALTER TYPE

The ALTER TYPE statement adds values to a union type at any position and renames values, rewriting the records that hold a renamed value.

_(since v4.0.0)_

The `ALTER TYPE` statement changes the values of a union of strings declared with [`DEFINE TYPE`](/docs/reference/query-language/statements/define/type.md), such as `DEFINE TYPE priority AS 'low' | 'medium' | 'high'`. It can add a value at any position in the order, and rename a value. A rename also rewrites the records that hold the old value.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
ALTER TYPE [ IF EXISTS ] @name
[
    ADD VALUE [ IF NOT EXISTS ] @value [ BEFORE @value | AFTER @value ] |
    RENAME VALUE @value TO @value
] ...
```

A statement takes one or more `ADD VALUE` and `RENAME VALUE` clauses, applied in the order they are written. If one clause fails, the statement changes nothing. Without `IF EXISTS`, a statement on a type that does not exist fails with `The type 'name' does not exist`. A type that is not a union of strings is refused with `The type 'name' is not a union of string labels, so it has no values to alter`. To change the checks, default, comment or permissions of a type, define it again with `OVERWRITE`, which checks the values that records already hold. See [Changing a type that is in use](/docs/reference/query-language/statements/define/type.md#changing-a-type-that-is-in-use).

## Adding values

`ADD VALUE` places a new value at the end of the order, or directly before or after an existing value. Adding a value does not change any stored record.

```surql
DEFINE TYPE priority AS 'low' | 'medium' | 'high';

ALTER TYPE priority ADD VALUE 'urgent';
ALTER TYPE priority ADD VALUE 'trivial' BEFORE 'low';
ALTER TYPE priority ADD VALUE 'normal' AFTER 'medium';

enum::values('priority');
```

```surql title="Output"
['trivial', 'low', 'medium', 'normal', 'high', 'urgent']
```

A value that the type already lists is refused, unless the clause has `IF NOT EXISTS`. A position that names a value the type does not list is refused as well.

```surql
-- Setup from the example above
DEFINE TYPE priority AS 'low' | 'medium' | 'high';
ALTER TYPE priority ADD VALUE 'urgent';
ALTER TYPE priority ADD VALUE 'trivial' BEFORE 'low';
ALTER TYPE priority ADD VALUE 'normal' AFTER 'medium';

ALTER TYPE priority ADD VALUE 'urgent';
//- "The type 'priority' already has the value 'urgent'"

ALTER TYPE priority ADD VALUE IF NOT EXISTS 'urgent';
//- NONE

ALTER TYPE priority ADD VALUE 'blocker' AFTER 'critical';
//- "The type 'priority' has no value 'critical'; its values are 'trivial', 'low', 'medium', 'normal', 'high', 'urgent'"
```

## Several changes in one statement

The clauses of one statement apply in order, so a later clause can refer to a value that an earlier one added or renamed.

```surql
-- Setup from the example above
DEFINE TYPE priority AS 'low' | 'medium' | 'high';
ALTER TYPE priority ADD VALUE 'urgent';
ALTER TYPE priority ADD VALUE 'trivial' BEFORE 'low';
ALTER TYPE priority ADD VALUE 'normal' AFTER 'medium';

ALTER TYPE priority
	ADD VALUE 'blocker' AFTER 'urgent'
	RENAME VALUE 'trivial' TO 'minor';
enum::values('priority');
```

```surql title="Output"
['minor', 'low', 'medium', 'normal', 'high', 'urgent', 'blocker']
```

## Renaming values

`RENAME VALUE` changes the spelling of a value and keeps its position. It also rewrites the old value to the new one in every record and index entry of every field whose type names it, including inside an `option`, an `array` or a `set`, so the records keep passing the type check on their next write.

```surql
-- Setup from the example above
DEFINE TYPE priority AS 'low' | 'medium' | 'high';

DEFINE TABLE ticket SCHEMAFULL;
DEFINE FIELD priority ON ticket TYPE priority;
DEFINE FIELD history ON ticket TYPE array<priority> DEFAULT [];
DEFINE INDEX ticket_priority ON ticket FIELDS priority;

CREATE ticket:1 SET priority = 'medium', history = ['low', 'medium'];
CREATE ticket:2 SET priority = 'high';

ALTER TYPE priority RENAME VALUE 'medium' TO 'moderate';
SELECT * FROM ticket ORDER BY id;
```

```surql title="Output"
[
	{ history: ['low', 'moderate'], id: ticket:1, priority: 'moderate' },
	{ history: [], id: ticket:2, priority: 'high' }
]
```

The rewrite is maintenance by the database, not a write by a user. It writes only the records that hold the old value, rewrites a `READONLY` field, does not run the `VALUE` or `DEFAULT` clauses of the fields, and does not trigger any [event](/docs/reference/query-language/statements/define/event.md). A table with a changefeed records each rewritten record as an update.

Renaming a value to one the type already lists is refused. A rename is also refused while a field holds the type in an array inside another array, such as `array<array<priority>>`, because the rewrite does not reach that depth:

```surql
DEFINE FIELD grid ON ticket TYPE option<array<array<priority>>>;
ALTER TYPE priority RENAME VALUE 'low' TO 'lowest';
```

```surql title="Error output"
"the type 'priority' is held by the field 'grid.*.*' on the table 'ticket', whose path a rename does not reach"
```

## `ALTER TYPE` or `ALTER FIELD`

The same values can be written out on each field as a literal, or defined once with `DEFINE TYPE` and named by each field. While the tables are empty, the two forms behave the same. Once they hold records, a change to the values works differently. [`ALTER FIELD`](/docs/reference/query-language/statements/alter/field.md) changes one field at a time, and compares its old definition with the new one. `ALTER TYPE` changes every field that names the type, and rewrites the records it needs to.

Here are the two forms, each with a `priority` field on two tables and a few records. Each one starts in a new database, because the examples above already define a `priority` type and a `ticket` table.

```surql title="A literal on each field"
DEFINE TABLE ticket SCHEMAFULL;
DEFINE FIELD priority ON ticket TYPE 'low' | 'medium' | 'high';
DEFINE TABLE task SCHEMAFULL;
DEFINE FIELD priority ON task TYPE 'low' | 'medium' | 'high';

CREATE ticket:1 SET priority = 'high';
CREATE ticket:2 SET priority = 'medium';
CREATE task:1 SET priority = 'medium';
```

```surql title="A named type"
DEFINE TYPE priority AS 'low' | 'medium' | 'high';
DEFINE TABLE ticket SCHEMAFULL;
DEFINE FIELD priority ON ticket TYPE priority;
DEFINE TABLE task SCHEMAFULL;
DEFINE FIELD priority ON task TYPE priority;

CREATE ticket:1 SET priority = 'high';
CREATE ticket:2 SET priority = 'medium';
CREATE task:1 SET priority = 'medium';
```

Adding a value works with both forms. The new literal accepts every value the old one did, so `ALTER FIELD` needs no migration, but it has to be run once for each field:

```surql
-- Setup from the examples above
DEFINE TABLE ticket SCHEMAFULL;
DEFINE FIELD priority ON ticket TYPE 'low' | 'medium' | 'high';
DEFINE TABLE task SCHEMAFULL;
DEFINE FIELD priority ON task TYPE 'low' | 'medium' | 'high';

CREATE ticket:1 SET priority = 'high';
CREATE ticket:2 SET priority = 'medium';
CREATE task:1 SET priority = 'medium';
DEFINE TYPE priority AS 'low' | 'medium' | 'high';

-- A literal on each field
ALTER FIELD priority ON ticket TYPE 'low' | 'medium' | 'high' | 'urgent';
ALTER FIELD priority ON task TYPE 'low' | 'medium' | 'high' | 'urgent';

-- A named type
ALTER TYPE priority ADD VALUE 'urgent';
```

Renaming a value is where the two forms differ. To `ALTER FIELD`, a rename is a new literal that no longer accepts `'medium'`, so a table with records refuses it until the statement says what those records become:

```surql
-- Setup from the example above
DEFINE TABLE ticket SCHEMAFULL;
DEFINE FIELD priority ON ticket TYPE 'low' | 'medium' | 'high';
DEFINE TABLE task SCHEMAFULL;
DEFINE FIELD priority ON task TYPE 'low' | 'medium' | 'high';

CREATE ticket:1 SET priority = 'high';
CREATE ticket:2 SET priority = 'medium';
CREATE task:1 SET priority = 'medium';

-- A literal on each field
ALTER FIELD priority ON ticket TYPE 'low' | 'normal' | 'high';
//- 'Cannot change field `priority` of table `ticket`: the table is SCHEMAFULL in a database at compatibility level 4 and has rows, and the new definition does not accept every value the old one did: add MIGRATE EXISTING ROWS'

ALTER FIELD priority ON ticket TYPE 'low' | 'normal' | 'high'
    MIGRATE EXISTING ROWS AS medium_to_normal
    USING { medium: 'normal' }[$value] ?? $value FALLBACK 'normal';

SELECT * FROM ticket ORDER BY id;
//- [{ id: ticket:1, priority: 'high' }, { id: ticket:2, priority: 'normal' }]
SELECT * FROM task;
//- [{ id: task:1, priority: 'medium' }]
```

The migration changed `ticket` only, and `task` still holds `'medium'` until its own field is changed in the same way. With a named type, one `RENAME VALUE` rewrites the records of every field that names the type:

```surql
-- Setup from the example above
DEFINE TYPE priority AS 'low' | 'medium' | 'high';
DEFINE TABLE ticket SCHEMAFULL;
DEFINE FIELD priority ON ticket TYPE priority;
DEFINE TABLE task SCHEMAFULL;
DEFINE FIELD priority ON task TYPE priority;

CREATE ticket:1 SET priority = 'high';
CREATE ticket:2 SET priority = 'medium';
CREATE task:1 SET priority = 'medium';

-- A named type
ALTER TYPE priority RENAME VALUE 'medium' TO 'normal';

SELECT * FROM ticket ORDER BY id;
//- [{ id: ticket:1, priority: 'high' }, { id: ticket:2, priority: 'normal' }]
SELECT * FROM task;
//- [{ id: task:1, priority: 'normal' }]
```

Removing a value works the other way around. `ALTER FIELD` with `MIGRATE EXISTING ROWS` can narrow a literal and convert the records that held the removed value. `ALTER TYPE` has no clause to remove a value, and [`DEFINE TYPE ... OVERWRITE`](/docs/reference/query-language/statements/define/type.md#changing-a-type-that-is-in-use) refuses a different list of values while a field names the type:

```surql
-- A named type
DEFINE TYPE OVERWRITE priority AS 'medium' | 'high';
//- "Invalid statement: Cannot change the values of the type 'priority': the field 'priority' on the table 'task' has a type that names it"
```

To remove a value from a named type, define a new type without it, and change each field to the new type with a migration.

| Change | A literal on each field | A named type |
| ------ | ----------------------- | ------------ |
| Add a value | `ALTER FIELD` on each field, without a migration | One `ALTER TYPE ... ADD VALUE` |
| Rename a value | `ALTER FIELD` on each field, with `MIGRATE EXISTING ROWS` | One `ALTER TYPE ... RENAME VALUE`, which rewrites the records |
| Remove a value | `ALTER FIELD` on each field, with `MIGRATE EXISTING ROWS` | A new type, then `ALTER FIELD` on each field with `MIGRATE EXISTING ROWS` |

## See also

* [`ALTER FIELD`](/docs/reference/query-language/statements/alter/field.md)
* [`DEFINE TYPE`](/docs/reference/query-language/statements/define/type.md)
* [Named types](/docs/reference/query-language/language-primitives/data-types/named-types.md)
* [Enum functions](/docs/reference/query-language/functions/database-functions/enum.md)

---

Source: https://surrealdb.com/docs/reference/query-language/statements/alter/user

# ALTER USER

The ALTER USER statement can be used to modify an existing defined database user.

_(since v3.0.5)_

The `ALTER USER` statement can be used to modify an existing defined database [user](/docs/reference/query-language/statements/define/user.md).

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
ALTER USER [ IF EXISTS ] @name
  ON [ ROOT | NAMESPACE | DATABASE ]
  [ PASSWORD @pass | PASSHASH @hash ]
  [ PASSSCRAM @verifier ]
  [ ROLES @role, ... ]
  [ DURATION FOR TOKEN [ @duration | NONE ] ]
  [ DURATION FOR SESSION [ @duration | NONE ] ]
  [ COMMENT @string | DROP COMMENT ]
```

## Example usage

```surql
-- Define a user with viewer role
DEFINE USER billy ON DATABASE PASSWORD "example" ROLES VIEWER;

-- Congrats on your promotion billy,
-- be sure to use this power for good
ALTER USER billy ON DATABASE ROLES EDITOR;
```

From SurrealDB 3.3, changing a user's password with **`ALTER USER … PASSWORD`** regenerates the [SCRAM-SHA-256 verifier material](/docs/reference/query-language/statements/define/user.md#scram-credentials-for-postgres-clients) used by the Postgres wire protocol, in addition to updating the Argon2 hash. **`ALTER USER … PASSHASH`** updates the hash and clears any stored SCRAM verifier.

**`ALTER USER … PASSSCRAM`** stores a precomputed verifier in the [PostgreSQL format](/docs/reference/query-language/statements/define/user.md#importing-a-scram-verifier-with-passscram) and leaves the Argon2 hash as it is. In a statement that also has `PASSWORD` or `PASSHASH`, the `PASSSCRAM` verifier is the one stored.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/begin

# BEGIN

The BEGIN statement starts a single transaction in which run multiple statements can be run, either succeeding as a whole, or failing.

Each statement within SurrealDB is run within its own transaction by default. The `BEGIN` statement can be used to modify this behaviour by running a group of statements inside a single transaction, either succeeding as a whole, or failing. Once all of the statements within a transaction succeed, then all of the data modifications can be made permanent by finalizing the transaction with a [COMMIT](/docs/reference/query-language/statements/commit.md) statement at the end. If any statement within a transaction encounters an error or the transaction is manually cancelled ([CANCEL](/docs/reference/query-language/statements/cancel.md)), then any data modification made within the transaction is rolled back, and will not become a permanent part of the database.

Transactions run under snapshot isolation. Concurrent transactions do not block each other, and when two of them write the same record or the same unique index value, the one that commits second fails with a transaction conflict error and can be retried. See [Transactions](/docs/learn/querying/concepts-and-guides/transactions.md#snapshot-isolation) for the full isolation rules, and [Unique indexes under concurrent writes](/docs/learn/querying/concepts-and-guides/transactions.md#unique-indexes-under-concurrent-writes) for inserting a record exactly once.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
BEGIN [ TRANSACTION ]
	[ ISOLATION LEVEL [ SNAPSHOT | SERIALIZABLE ] ]
	[ READ ONLY [ MAX STALENESS @duration [ STRICT ] ] ];
```

## Example usage

The following query shows example usage of this statement.

```surql
-- Start a new database transaction. Transactions are a way to ensure multiple operations
-- either all succeed or all fail, maintaining data integrity.
BEGIN TRANSACTION;

-- Create a new account with the ID 'one' and set its initial balance to 135605.16
CREATE account:one SET balance = 135605.16;

-- Create another new account with the ID 'two' and set its initial balance to 91031.31
CREATE account:two SET balance = 91031.31;

-- Update the balance of account 'one' by adding 300.00 to the current balance.
-- This could represent a deposit or other form of credit on the balance property.
UPDATE account:one SET balance += 300.00;

-- Update the balance of account 'two' by subtracting 300.00 from the current balance.
-- This could represent a withdrawal or other form of debit on the balance property.
UPDATE account:two SET balance -= 300.00;

-- Finalise the transaction. This will apply the changes to the
-- database. If there was an error during any of the previous steps
-- within the transaction, all changes would be rolled back and the
-- database would remain in its initial state.
COMMIT TRANSACTION;
```

## Returning early from a transaction

While all transactions require a final `COMMIT` or `CANCEL` statement in order to run, an early return can take place via the following:

* An error inside one of the statements inside the transaction,
* A `THROW` statement to return early with an error.

A `RETURN` statement is often used to customise the output of a transaction. From SurrealDB 4.0, a `RETURN` placed directly inside the transaction does not end it: its value is one of the results, and the statements after it still run. To end part of a transaction early, put those statements in a block, where a `RETURN` ends the block. Before SurrealDB 4.0, a `RETURN` ended the transaction early.

An example of the above:

```surql
BEGIN;

CREATE account:one SET balance = 135605.16;
CREATE account:two SET balance = 91031.31, wants_to_send_money = true;

-- Read the field into a parameter before testing it. As of SurrealDB
-- 3.2.x, reading a record field directly inside an IF condition fails
-- with "Specify a database to use".
LET $wants_to_send = account:two.wants_to_send_money;

IF !$wants_to_send {
    THROW "Customer doesn't want to send any money!";
};

LET $first = UPDATE ONLY account:one SET balance += 300.00;
LET $second = UPDATE ONLY account:two SET balance -= 300.00;

RETURN "Money sent! Status:\n" + <string>$first + '\n' +
  <string>$second;
//- 'Money sent! Status:\n{ balance: 135905.16f, id: account:one }\n{ balance: 90731.31f, id: account:two, wants_to_send_money: true }'

COMMIT;
```

## Read-only transactions

_(since v4.0.0)_

`BEGIN READ ONLY` starts a transaction that can only read. Any write inside it fails, and the whole transaction fails with it:

```surql
CREATE note:1;

BEGIN READ ONLY;
SELECT * FROM note;
CREATE note:2;
COMMIT;
```

```surql title="Error output"
"Invalid statement: Cannot run CREATE on a read only transaction"
```

A read-only `BEGIN` returns a description of the snapshot it reads, where a plain `BEGIN` returns `NONE`. `age` is how far the snapshot is behind the current state, and `stale` is whether it is behind at all:

```surql
BEGIN READ ONLY;
```

```surql title="Output"
{ age: 0ns, position: NONE, stale: false }
```

### Reading a recent snapshot with `MAX STALENESS`

`MAX STALENESS` lets the transaction read from a snapshot that the datastore has already published, as long as the snapshot is no older than the duration given, instead of reading the current state. On a datastore that publishes snapshots, this lets reads that can accept slightly older data avoid the work of reading the latest state. The duration can be a literal or a parameter bound before the transaction:

```surql
-- Setup
CREATE order:1, order:2;

BEGIN READ ONLY MAX STALENESS 5s;
SELECT count() FROM order GROUP ALL;
COMMIT;
```

SurrealDS publishes snapshots. A datastore that publishes none, which includes every storage engine of the open-source release, reads the current state, which meets every bound, so the same statement works everywhere. When no published snapshot is recent enough, the datastore reads the current state unless the server sets [`SURREAL_READ_SNAPSHOT_FALLBACK`](/docs/reference/cli/db/environment-variables.md#limits-config) otherwise. Add `STRICT` to make the transaction fail instead of reading the current state in that case. A duration above the server's [`SURREAL_READ_SNAPSHOT_MAX_STALENESS_SECS`](/docs/reference/cli/db/environment-variables.md#limits-config), one hour by default, fails the transaction, and `COMMIT` reports the error:

```surql
BEGIN READ ONLY MAX STALENESS 2h;
COMMIT;
```

```surql title="Error output"
"Cannot COMMIT: The requested MAX STALENESS of 7200s is above the maximum of 3600s this datastore allows"
```

Clients can start the same transaction without writing `BEGIN`: the `begin` RPC method takes a `read_only` option, and the HTTP `/sql` endpoint takes `read_only_max_staleness` and `read_only_strict`.

## Isolation level

_(since v4.0.0)_

Transactions run under snapshot isolation by default, and `ISOLATION LEVEL SNAPSHOT` states this explicitly. `ISOLATION LEVEL SERIALIZABLE` asks for serializable isolation, which also prevents the anomalies that snapshot isolation allows, such as write skew, where two transactions each read what the other changes. The in-memory engine (SurrealMX) and SurrealDS offer serializable isolation, which they provide by adding every read of the transaction to its commit-time conflict check. SurrealKV and TiKV refuse it rather than running the transaction at a weaker level. See [Isolation by storage engine](/docs/learn/querying/concepts-and-guides/transactions.md#isolation-by-storage-engine) for the full table, and [Serializable isolation](/docs/learn/querying/concepts-and-guides/transactions.md#serializable-isolation) for an example of the write skew it prevents.

```surql
-- On the in-memory engine or SurrealDS
BEGIN ISOLATION LEVEL SERIALIZABLE;
```

On another engine, the statements inside the transaction fail with an error that names the levels the datastore offers:

```surql title="Error output"
"The isolation level SERIALIZABLE is not available on this datastore; it offers SNAPSHOT"
```

The two clauses can be combined in either order, as in `BEGIN ISOLATION LEVEL SNAPSHOT READ ONLY`. Combining `SERIALIZABLE` with a `MAX STALENESS` above zero fails with `ISOLATION LEVEL SERIALIZABLE cannot be combined with a MAX STALENESS above zero`.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/break

# BREAK

The BREAK statement can be used to break out of a loop.

The BREAK statement can be used to break out of a loop, such as inside one created by the [FOR statement](/docs/reference/query-language/statements/for.md).

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
BREAK
```

## Example usage

The following queries shows example usage of this statement.

Creating a person for everyone in the array where the number is less than or equal to 5:

```surql
LET $numbers = [1,2,3,4,5,6,7,8,9];

FOR $num IN $numbers {
    IF $num > 5 {
        BREAK;

    } ELSE IF $num < 5 {
        CREATE type::record(
            'person', $num
        ) CONTENT {
            name: "Person number " + <string>$num
        };
    };
};
```

Breaking out of a loop once unwanted data is encountered:

```surql
-- Data retrieved from somewhere which contains many NONE values
LET $weather = [
	{
		city: 'London',
		temperature: 22.2,
		timestamp: 1722565566389
	},
	NONE,
	{
		city: 'London',
		temperature: 20.1,
		timestamp: 1722652002699
	},
    {
        city: 'Phoenix',
        temperature: 45.1,
        timestamp: 1722565642160
    },
    NONE,
    NONE,
    {
        city: 'Phoenix',
        temperature: 45.1,
        timestamp: 1722652070372
    },
];

-- Sort the data to move the NONE values to the end
-- and break once the first NONE is reached
FOR $data IN array::sort::desc($weather) {
    IF $data IS NONE {
        BREAK;
    } ELSE {
        CREATE weather CONTENT $data;
    };
};
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/cancel

# CANCEL

The CANCEL statement can be used to cancel the statements within a transaction, reverting or rolling back any data modification made within the transaction as a whole.

Each statement within SurrealDB is run within its own transaction. If a set of changes need to be made together, then groups of statements can be run together as a single transaction, either succeeding as a whole, or failing without leaving any residual data modifications. While a transaction will fail if any of its statements encounters an error, the `CANCEL` statement can also be used to cancel a transaction manually.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
CANCEL [ TRANSACTION ];
```

## Example usage

The following query shows example usage of this statement.

```surql
BEGIN TRANSACTION;

-- Setup accounts
CREATE account:one SET balance = 135605.16;
CREATE account:two SET balance = 91031.31;

-- Move money
UPDATE account:one SET balance += 300.00;
UPDATE account:two SET balance -= 300.00;

-- Rollback all changes
CANCEL TRANSACTION;
```

`CANCEL` is not used to automatically cancel a transaction based on a condition such as inside an [IF..ELSE](/docs/reference/query-language/statements/if-else.md) block. Instead, a [THROW](/docs/reference/query-language/statements/throw.md) statement is used. THROW can be followed by any value, usually a string containing context behind the error.

> [!WARNING]
> `CANCEL` only takes effect as a top-level statement. Inside a block, such as an `IF` or `FOR` body, a bare `{ }` block or a `DEFINE FUNCTION` body, it is ignored without an error, and the transaction still commits. The same applies to `BEGIN` and `COMMIT`. In the following query both records are created.
>
> ```surql
> BEGIN;
> CREATE a:1;
> IF true { CANCEL };
> CREATE a:2;
> COMMIT;
> ```

```surql
BEGIN TRANSACTION;

-- Setup accounts
CREATE account:one SET balance = 135605.16;
CREATE account:two SET balance = 200.31;

-- Move money
UPDATE account:one SET balance += 300.00;
UPDATE account:two SET balance -= 300.00;

IF account:two.balance < 0 {
    THROW "Not enough funds";
};

COMMIT TRANSACTION;
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/commit

# COMMIT

The COMMIT statement is used to commit the statements within a transaction, ensuring that all data modifications become a permanent part of the database.

Each statement within SurrealDB is run within its own transaction by default. If a set of changes need to be made together, then groups of statements can be run together as a single transaction, either succeeding as a whole, or failing without leaving any residual data modifications. A `COMMIT` statement is used at the end of such a transaction to make the data modifications a permanent part of the database.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
COMMIT [ TRANSACTION ];
```

## Example usage

The following query shows example usage of this statement.

```surql
BEGIN TRANSACTION;

-- Setup accounts
CREATE account:one SET balance = 135605.16;
CREATE account:two SET balance = 91031.31;

-- Move money
UPDATE account:one SET balance += 300.00;
UPDATE account:two SET balance -= 300.00;

-- Finalise all changes
COMMIT TRANSACTION;
```

The following two options can be used at any point if a transaction must be cancelled without commiting the changes:

* [CANCEL](/docs/reference/query-language/statements/cancel.md) to manually cancel the transaction.
* [THROW](/docs/reference/query-language/statements/throw.md) to cancel a transaction with an optional error message. THROW is the only way to cancel a transaction based on a condition, such as inside an [IF..ELSE](/docs/reference/query-language/statements/if-else.md) block.

In addition, a `RETURN` statement can be used to return a customised output from a successful transaction. From SurrealDB 4.0, a `RETURN` placed directly inside the transaction does not end it, so put it last, before `COMMIT`. Before SurrealDB 4.0, a `RETURN` ended the transaction early.

```surql
BEGIN;

CREATE account:one SET balance = 135605.16;
CREATE account:two SET balance = 91031.31, wants_to_send_money = true;

-- Read the field into a parameter before testing it. As of SurrealDB
-- 3.2.x, reading a record field directly inside an IF condition fails
-- with "Specify a database to use".
LET $wants_to_send = account:two.wants_to_send_money;

IF !$wants_to_send {
    THROW "Customer doesn't want to send any money!";
};

LET $first = UPDATE ONLY account:one SET balance += 300.00;
LET $second = UPDATE ONLY account:two SET balance -= 300.00;

RETURN "Money sent! Status:\n" + <string>$first + '\n' + <string>$second;
//- 'Money sent! Status:\n{ balance: 135905.16f, id: account:one }\n{ balance: 90731.31f, id: account:two, wants_to_send_money: true }'

COMMIT;
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/continue

# CONTINUE

The CONTINUE statement can be used to skip an iteration of a loop, like within the FOR statement

The CONTINUE statement can be used to skip an iteration of a loop, like within the [FOR statement](/docs/reference/query-language/statements/for.md).

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
CONTINUE
```

## Example usage

The following queries shows example usage of this statement.

Skipping an iteration of a loop unless a certain condition is met:

```surql
-- Set can_vote to true for every person over 18 years old.
FOR $person IN (SELECT id, age FROM person) {
	IF ($person.age < 18) {
		CONTINUE;
	};

	UPDATE $person.id SET can_vote = true;
};
```

Skipping an iteration of a loop when bad data is encountered:

```surql
-- Data retrieved from somewhere which contains many NONE values
LET $weather = [
	{
		city: 'London',
		temperature: 22.2,
		timestamp: 1722565566389
	},
	NONE,
	{
		city: 'London',
		temperature: 20.1,
		timestamp: 1722652002699
	},
    {
        city: 'Phoenix',
        temperature: 45.1,
        timestamp: 1722565642160
    },
    NONE,
    NONE,
    {
        city: 'Phoenix',
        temperature: 45.1,
        timestamp: 1722652070372
    },
];

FOR $data IN $weather {
    IF $data IS NONE {
        CONTINUE;
    };

	CREATE weather CONTENT $data;
};
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/create

# CREATE

The CREATE statement can be used to add a record to the database if it does not already exist.

The `CREATE` statement can be used to add a record to the database. If the record already exists, the statement will give an error. To compare it with the other statements that write records, see [Writing records that may already exist](/docs/reference/query-language/statements/overview.md#writing-records-that-may-already-exist).

> [!NOTE]
> This statement can not be used to create graph relationships. For that, use the [`RELATE`](/docs/reference/query-language/statements/relate.md) statement.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
CREATE [ ONLY ] @targets
	[ CONTENT @value
	  | SET @field = @value ...
	]
	[ RETURN NONE | RETURN BEFORE | RETURN AFTER | RETURN DIFF
	  | RETURN @statement_param, ... | RETURN VALUE @statement_param ]
	[ TIMEOUT @duration ]
;
```

## Creating a table record

`CREATE` can be used with just a table name, in which case its ID will be generated randomly.

```surql
-- Create a new record
CREATE person;
```

```surql title="Example output"
[
    {
        id: person:2vvgzt6m24s952yiy7x8
    }
]
```

To specify a specific ID for a table instead, use `:` followed by a value.

```surql
CREATE person:one;
```

```surql title="Output"
[
	{
		id: person:one
	}
]
```

The table name and ID together form the full [record ID](/docs/reference/query-language/language-primitives/data-types/record-ids.md) which can be used to query the created data or by using the [`SELECT`](/docs/reference/query-language/statements/select.md) statement. See the [record ID](/docs/reference/query-language/language-primitives/data-types/record-ids.md) page to learn more about what counts as a valid record identifier.

The default random ID can be generated in different ways (such as a ULID) using the [built-in ID generation functions](/docs/reference/query-language/language-primitives/data-types/record-ids.md#types-of-record-ids).

It is also possible to specify the ID of the record you want to create using a string or any of the supported formats for [record IDs](/docs/reference/query-language/language-primitives/data-types/record-ids.md).

```surql
-- Use the type::record() function to provide a record's table and id separately
CREATE type::record("person", "one");
```

## Adding record data

When creating a record, you can specify the record data using the `CONTENT` clause, or the `SET` clause. The `CONTENT` clause is used to specify record data using a SurrealQL object, while the `SET` clause is used to specify record data one field at a time. The `CONTENT` clause is useful when the record data is already in the form of a SurrealQL or JSON object, while the `SET` clause reads well when each field is computed on its own line.

Specifying record data using the `CONTENT` keyword:

```surql
-- Create a new record with a numeric id
CREATE person:100 CONTENT {
	name: 'Tobie',
	company: 'SurrealDB',
	skills: ['Rust', 'Go', 'JavaScript'],
};
```

Specifying the same record data one field at a time using the `SET` clause:

```surql
-- Create a new record with a text id
CREATE person:tobie SET
    name = 'Tobie',
    company = 'SurrealDB',
    skills = ['Rust', 'Go', 'JavaScript'];
```

The above will create a new record with the ID `person:tobie` and the specified data.

```surql title="Output"
[
	{
		"id": "person:tobie",
		"name": "Tobie",
		"company": "SurrealDB",
		"skills": ["Rust", "Go", "JavaScript"]
	}
]
```

## Options and clauses

### Creating multiple records

Multiple records or even multiple record types can be created by separating table names by commas. Every table gets the same field values. To give each record its own content in one statement, use [`INSERT` without `INTO`](/docs/reference/query-language/statements/insert.md#choosing-the-table-with-a-parameter) and give each object a full record ID.

```surql
-- Note: record::tb(id) returns just the table name portion of a record ID.
-- The id is not yet bound while CREATE is still evaluating its fields, so
-- the records are created first and named in a following UPDATE.
CREATE townsperson, cat, dog SET
    created_at = time::now();
UPDATE townsperson, cat, dog SET
    name = "Just a " + record::tb(id);
```

```surql title="Example output"
[
    {
        created_at: d'2024-03-19T03:12:05.079Z',
        id: townsperson:p37ha2lngckp3v8tvf2j,
        name: 'Just a townsperson'
    },
    {
        created_at: d'2024-03-19T03:12:05.080Z',
        id: cat:p1pwbjaq96nhhnuohjtc,
        name: 'Just a cat'
    },
    {
        created_at: d'2024-03-19T03:12:05.080Z',
        id: dog:01vcxgdpuctdk354hzkp,
        name: 'Just a dog'
    }
]
```

The `| |` syntax is another way to create multiple records in a single execution. This syntax can be used in two ways.

One is by including a table name, a `:` (a colon), and then a number. This will create a quantity of records equal to the number after the table name. The records created will have random IDs.

```surql
-- Creates three townperson records with a random ID
CREATE |townsperson:3|;
```

```surql title="Output"
[
	{
		id: townsperson:hzkt0piy3f72xo5dl2jf
	},
	{
		id: townsperson:k0mujrohm8qe2txz5pnz
	},
	{
		id: townsperson:pwumqelrsi1qt0jmihwh
	}
]
```

The other method is by using the `..` range syntax after the `:` instead of a single number. This will create records with specific IDs that span across the range indicated.

```surql
-- Note: 1..4 used to be inclusive until SurrealDB 3.0.0
-- Now creates 1 up to but not including 4
CREATE |townsperson:1..4|;
```

```surql title="Output"
[
	{
		id: townsperson:1
	},
	{
		id: townsperson:2
	},
	{
		id: townsperson:3
	}
]
```

All of these methods can be combined to create multiple records at the same time.

```surql
CREATE dog, |cat:2|, |townsperson:1..4| SET
    created_at = time::now();
```

```surql title="Example output"
[
	{
		created_at: d'2026-11-11T03:53:32.506806Z',
		id: dog:ncmingt3fupr7luywehi
	},
	{
		created_at: d'2026-11-11T03:53:32.506806Z',
		id: cat:z1rsjj0yf7k6641tkcjt
	},
	{
		created_at: d'2026-11-11T03:53:32.506806Z',
		id: cat:yk0dwd6qe3sg3id3x3uz
	},
	{
		created_at: d'2026-11-11T03:53:32.506806Z',
		id: townsperson:1
	},
	{
		created_at: d'2026-11-11T03:53:32.506806Z',
		id: townsperson:2
	},
	{
		created_at: d'2026-11-11T03:53:32.506806Z',
		id: townsperson:3
	}
]
```

### ONLY

When creating a single record, the `ONLY` clause can be used to return the record object on its own instead of inside an array.

```surql
-- Returns an array with a single record inside
CREATE person:tobie SET
    name = 'Tobie',
    company = 'SurrealDB',
    skills = ['Rust', 'Go', 'JavaScript'];
//- [{ company: 'SurrealDB', id: person:tobie, name: 'Tobie', skills: ['Rust', 'Go', 'JavaScript'] }]

-- Returns just a single record
CREATE ONLY person:tobieagain SET
    name = 'Tobie',
    company = 'SurrealDB',
    skills = ['Rust', 'Go', 'JavaScript'];
//- { company: 'SurrealDB', id: person:tobieagain, name: 'Tobie', skills: ['Rust', 'Go', 'JavaScript'] }
```

### Return values

By default, the create statement returns the record once it has been created. To change what is returned, we can use the `RETURN` clause, specifying either `NONE`, `BEFORE`, `AFTER`, `DIFF`, or a comma-separated list of specific fields to return.

`RETURN NONE` can be useful to avoid excess output:

```surql
-- Create 10000 records but don't show any of them
CREATE |person:10000| SET age = 46, username = "john-smith" RETURN NONE;
```

`RETURN DIFF` returns the changeset diff:

```surql
CREATE person SET age = 46, username = "john-smith" RETURN DIFF;
```

```surql title="Output"
[
	[
		{
			op: 'replace',
			path: '',
			value: {
				age: 46,
				id: person:h84x4k5kh2m6cjf1vvza,
				username: 'john-smith'
			}
		}
	]
]
```

`RETURN BEFORE` inside a `CREATE` statement is essentially a synonym for `RETURN NONE`, while `RETURN AFTER` is the default behaviour for create.

```surql
-- Will always return NONE
CREATE person SET age = 46, username = "john-smith" RETURN BEFORE;
```

```surql
-- Return the record after creation
CREATE person SET age = 46, username = "john-smith" RETURN AFTER;
```

You can also return specific fields from a created record, the value of a single field using `VALUE`, as well as ad-hoc fields to modify the output as needed.

```surql
CREATE person
    SET age = 46,
    username = "john-smith",
    interests = ['skiing', 'music']
RETURN
    age,
    interests,
    age + 1 AS age_next_year;

CREATE |person:5|
    SET age = 20
RETURN VALUE age;
```

```surql title="Output"
-------- Query --------

[
	{
		age: 46,
		age_next_year: 47,
		interests: [
			'skiing',
			'music'
		]
	}
]

-------- Query --------

[
	20,
	20,
	20,
	20,
	20
]
```

### Timeout

The `TIMEOUT` clause can be used to specify the maximum time the statement should take to execute. This is useful when you want more control such as controlling compute costs or making sure queries succeed or fail within tight latency boundaries to not have a big query queue forming.

The value for `TIMEOUT` is specified in seconds or milliseconds.

```surql
-- Query attempting to create half a million `person` records
-- Possible output, since the timeout may or may not be exceeded
CREATE |person:500000| SET age = 46, username = "john-smith"
    TIMEOUT 500ms;
//- 'The query was not executed because it exceeded the timeout: 500ms'
```

## Implicit statement behaviour

While a number of definitions need to be in place for a `CREATE` statement to happen, SurrealDB will handle them automatically by default. This behaviour is best seen by starting a new database.

While a connection to SurrealDB via SurrealDB Studio or the [surreal db sql](/docs/reference/cli/db/commands/sql.md) command can include a defined namespace and database, the namespace and database names do not exist upon creation. At this point, they are only held inside the pre-defined [$session](/docs/reference/query-language/language-primitives/parameters.md#session) parameter. This can be seen through the [INFO](/docs/reference/query-language/statements/info.md) statements, which will show no definitions at all inside a new database.

```surql
INFO FOR ROOT;
INFO FOR NS;
INFO FOR DB;
RETURN $session;
```

```surql title="Output"
-------- Query --------

{
	accesses: {},
	namespaces: {},
	nodes: {},
	system: {
		available_parallelism: 0,
		cpu_usage: 0,
		load_average: [
			0,
			0,
			0
		],
		memory_allocated: 0,
		memory_usage: 0,
		physical_cores: 0,
		threads: 0
	},
	users: {}
}

-------- Query --------

{
	accesses: {},
	analyzers: {},
	apis: {},
	configs: {},
	functions: {},
	models: {},
	params: {},
	tables: {},
	users: {}
}

-------- Query --------

{
	analyzers: {},
	functions: {},
	models: {},
	params: {},
	scopes: {},
	tables: {},
	tokens: {},
	users: {}
}

-------- Query --------

{
	ac: NONE,
	db: 'sandbox',
	exp: NONE,
	id: NONE,
	ip: NONE,
	ns: 'sandbox',
	or: NONE,
	rd: NONE,
	tk: NONE
}
```

This is to allow the chance to [define](/docs/reference/query-language/statements/define/database.md) them manually, such as by including a comment.

```surql
DEFINE DATABASE my_database COMMENT "Some important info that I prefer to add manually";
```

However, once the first record is created or inserted, SurrealDB will access the session data to execute a number of definition statements for the namespace, database, and then add a definition for the desired table name in order to allow the operation to proceed.

```surql
-- Three DEFINE statements will happen to allow this operation
CREATE person;

INFO FOR ROOT;
INFO FOR NS;
INFO FOR DB;
```

```surql title="Output"
-------- Query --------

{
	accesses: {},
	namespaces: {
		sandbox: 'DEFINE NAMESPACE sandbox'
	},
	nodes: {},
	system: {
		available_parallelism: 0,
		cpu_usage: 0,
		load_average: [
			0,
			0,
			0
		],
		memory_allocated: 0,
		memory_usage: 0,
		physical_cores: 0,
		threads: 0
	},
	users: {}
}

-------- Query --------

{
	accesses: {},
	databases: {
		sandbox: 'DEFINE DATABASE sandbox'
	},
	users: {}
}

-------- Query 7 --------

{
	accesses: {},
	analyzers: {},
	apis: {},
	configs: {},
	functions: {},
	models: {},
	params: {},
	tables: {
		person: 'DEFINE TABLE person TYPE ANY SCHEMALESS PERMISSIONS NONE'
	},
	users: {}
}
```

To disallow this behaviour, you can [define a database](/docs/reference/query-language/statements/define/database.md) using the `STRICT` keyword. In strict mode, any resource must first be explicitly defined before it can be used.

```surql
CREATE person;

DEFINE DB strict_db STRICT;
USE DB strict_db;

CREATE person;
//- "The table 'person' does not exist"

DEFINE TABLE person;
CREATE person;
```

## Learn more

To learn more about SurrealDB, check out the following resources:
- [Getting started guide](/docs)
- [Select statement](/docs/reference/query-language/statements/select.md)
- [Update statement](/docs/reference/query-language/statements/update.md)
- [Insert statement](/docs/reference/query-language/statements/insert.md)
- [Delete statement](/docs/reference/query-language/statements/delete.md)
- [Relate statement](/docs/reference/query-language/statements/relate.md)

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/access

# DEFINE ACCESS

Defining an access method allows SurrealDB to grant access to resources using different kinds of credentials.

Defining an access method allows SurrealDB to grant access to resources using different kinds of credentials.

## Requirements

- You must be authenticated as a [system user](/docs/learn/security/authentication/users.md#system-users) at the same level or higher than the level on which access is defined.

## Statement syntax

```syntax title="SurrealQL Syntax"
DEFINE ACCESS [ OVERWRITE | IF NOT EXISTS ] @name
  ON [ ROOT | NAMESPACE | DATABASE ]
  TYPE [
    JWT [ ALGORITHM @algorithm KEY @key | URL @url ]
    | RECORD
      [ SIGNUP @expression ]
      [ SIGNIN @expression ]
      [ WITH JWT
        [ ALGORITHM @algorithm KEY @key | URL @url ]
        [ WITH ISSUER KEY @key ]
      ]
      [ WITH REFRESH ]
    | BEARER FOR [ USER | RECORD ]
  [ AUTHENTICATE @expression ]
  [ CONTEXT @expression ]
  [ DURATION
    [ FOR GRANT @duration ]
    [ FOR TOKEN @duration ]
    [ FOR SESSION @duration ]
  ]
  [ COMMENT @string ]
```

## JSON Web Token (JWT) access

A JWT access method allows accessing SurrealDB with a token signed by a trusted issuer. The contents of the token will be trusted by SurrealDB as long as it has been signed with a trusted credential.

Learn more about [JWT access method in the documentation](/docs/reference/query-language/statements/define/access/jwt.md).

## Record access

A record access method allows accessing SurrealDB as a [record user](/docs/learn/security/authentication/users.md#record-users). Record users allow SurrealDB to operate as a web database by offering mechanisms to define custom signin and signup logic as well as custom table and field permissions.

Learn more about [record access method in the documentation](/docs/reference/query-language/statements/define/access/record.md).

## Bearer access

A bearer access method allows generating bearer grants with an associated key that can be used to access SurrealDB as a specific [system user](/docs/learn/security/authentication/users.md#system-users) or [record user](/docs/learn/security/authentication/users.md#record-users). Bearer grants allow other systems and software to authenticate with SurrealDB using a secure and unique credential that can be audited and revoked at any time.

Learn more about [bearer access method in the documentation](/docs/reference/query-language/statements/define/access/bearer.md).

## Duration

The duration clause specifies the duration of the token returned after successful authentication with the access method as well as the duration of the session established both using the access method and the aforementioned token. A session established with the token also ends when the token expires, if that comes first. The difference between these concepts is explained in the [expiration documentation](/docs/learn/security/authentication/users.md#expiration).

```surql
-- Create a RECORD access method for accounts
-- On successful authentication, a token expiring after 15 minutes will be returned
-- The session that signed in expires after 12 hours
-- A session established later with the token ends when the token expires
DEFINE ACCESS account ON DATABASE TYPE RECORD
	SIGNUP ( CREATE user SET email = $email, pass = crypto::argon2::generate($pass) )
	SIGNIN ( SELECT * FROM user WHERE email = $email
	  AND crypto::argon2::compare(pass, $pass) )
	DURATION FOR TOKEN 15m, FOR SESSION 12h
;
```

## With `AUTHENTICATE` clause

The authenticate clause can be used to change the record identifier returned by the `SIGNIN` and `SIGNUP` clauses or replace the identifier provided in the token when authenticating `WITH JWT`. In the context of [`DEFINE ACCESS ... TYPE RECORD`](/docs/reference/query-language/statements/define/access/record.md), the `AUTHENTICATE` clause is always executed across signin, signup and token authentication.

When used in a [`DEFINE ACCESS ... TYPE JWT`](/docs/reference/query-language/statements/define/access/jwt.md), the `AUTHENTICATE` clause is used to validate the token claims and can be used to log or stop authentication attempts.

In both cases, the clause expects nothing to be returned and will otherwise fail with a generic error. The `THROW` statement can be called to return a custom error to the end user.

### Privileges inside the clause

`SIGNIN`, `SIGNUP` and `AUTHENTICATE` clauses are evaluated with a session scoped to the level the access method is defined on, and with the Editor role. An access method defined `ON DATABASE` evaluates its clauses as a Database Editor, one defined `ON NAMESPACE` as a Namespace Editor, and one defined `ON ROOT` as a Root Editor.

The clause therefore reaches only the namespace or database that owns the access method. A statement inside it that targets another namespace fails, whatever role the user who defined the access method holds.

The Editor role is a system role, so table and field `PERMISSIONS` clauses do not apply to lookups made inside these clauses. A `SELECT` against a record table behaves the same whether or not that table restricts record users.

## With `CONTEXT` clause

_(since v3.3.0)_

The `CONTEXT` clause attaches a value to the session at authentication time, and permission expressions read it back as `$session.data`. It is evaluated once, after `AUTHENTICATE`, with `$auth` already bound.

```surql
DEFINE ACCESS account ON DATABASE TYPE RECORD
    SIGNIN { RETURN SELECT * FROM user WHERE email = $email }
    CONTEXT { RETURN { tier: $auth.tier, teams: $auth.teams } }
    DURATION FOR SESSION 12h;
```

`CONTEXT` keeps whatever it returns by storing it in `$session.data`, which holds the value in the shape the clause produced it, objects and arrays included.

That is the difference from `AUTHENTICATE`, which yields an identity that is reduced to a record link before being bound to `$auth`. So a projection assembled there arrives as the record id alone, and any extra fields built alongside it are dropped. `CONTEXT` is thus used when you prefer to keep these fields.

The main use for `CONTEXT` is in permissions. A predicate that needs per-account authorisation otherwise queries a table for every record it filters, and that cost scales with the size of the table it queries. Reading the same facts from `$session.data` filters against a value already on the session instead:

```surql
DEFINE TABLE invoice SCHEMAFULL
    PERMISSIONS FOR select WHERE team IN $session.data.teams;
```

`session` is a protected parameter name, so a client cannot shadow `$session.data` with `LET` or with an SDK `set` call. That is what makes the value safe to authorise against.

`CONTEXT` is also available on [`ALTER ACCESS`](/docs/reference/query-language/statements/alter/access.md), and an access method without the clause behaves exactly as it did before.

> [!NOTE]
> The value is computed when the session authenticates, so it is a snapshot rather than a live view. A change written after authentication is not reflected until the session authenticates again. Put facts that change within a session's lifetime in the permission predicate itself, and keep `CONTEXT` for the ones that hold for as long as the session does.

## Using `IF NOT EXISTS` clause

The `IF NOT EXISTS` clause can be used to define an access method only if it does not already exist. If the access method already exists, the `DEFINE ACCESS` statement will return an error.

```surql
-- Create an ACCESS if it does not already exist
DEFINE ACCESS IF NOT EXISTS example ON NAMESPACE TYPE BEARER FOR USER;
```

## Using `OVERWRITE` clause

The `OVERWRITE` clause can be used to define an access method and overwrite an existing one if it already exists. You should use the `OVERWRITE` clause when you want to modify an existing access method definition. If the access method already exists, the `DEFINE ACCESS` statement will overwrite the existing access method definition with the new one.

```surql
-- Create an ACCESS and overwrite if it already exists
DEFINE ACCESS OVERWRITE example ON NAMESPACE TYPE BEARER FOR USER;
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/access/bearer

# BEARER

A bearer access method allows accessing SurrealDB using a bearer key.

A bearer access method allows generating bearer grants with an associated key that can be used to access SurrealDB as a specific [system user](/docs/learn/security/authentication/users.md#system-users) or [record user](/docs/learn/security/authentication/users.md#record-users). Bearer grants allow other systems and software to authenticate with SurrealDB using a secure and unique credential that can be [audited](/docs/reference/query-language/statements/access.md#show) and [revoked](/docs/reference/query-language/statements/access.md#revoke) at any time.

Allowing access to SurrealDB using a bearer access method requires creating grants associated with that access method. This can be done using the [`GRANT`](/docs/reference/query-language/statements/access.md#grant) clause of the [`ACCESS`](/docs/reference/query-language/statements/access.md) statement.

After creating a grant for a subject (i.e. a [system user](/docs/learn/security/authentication/users.md#system-users) or a [record user](/docs/learn/security/authentication/users.md#record-users)) with a bearer access method, a bearer key will be returned. This bearer key can be used to sign in as the subject of the grant without using its password or any other credentials. As with other credentials in SurrealDB, signing in with a bearer key will return a JWT, which can be used to perform authenticated operations or establish a persistent [authenticated session](/docs/learn/security/authentication/users.md). This makes bearer keys most suitable for automations and other service-to-service authentication use cases that require interacting with SurrealDB in an authenticated context by providing stronger security guarantees than passwords and removing the complexity of having to work with JWT directly.

## Requirements

- You must be authenticated as a [root, namespace or database user](/docs/reference/query-language/statements/define/user.md) before you can define a bearer access method.

## Statement syntax

```syntax title="SurrealQL Syntax"
DEFINE ACCESS [ OVERWRITE | IF NOT EXISTS ] @name
  ON [ NAMESPACE | DATABASE ]
  TYPE BEARER FOR [ USER | RECORD ]
  [ AUTHENTICATE @expression ]
  [ DURATION
    [ FOR GRANT @duration ]
    [ FOR TOKEN @duration ]
    [ FOR SESSION @duration ]
  ]
```

## `FOR USER`

Defining a bearer access method `FOR USER` will ensure that grants can only be created with a [system user](/docs/learn/security/authentication/users.md#system-users) as its subject. This application is useful for integrations that require administering SurrealDB at the `ROOT`, `NAMESPACE` or `DATABASE` level with the roles with which the user has been defined with [`DEFINE USER`](/docs/reference/query-language/statements/define/user.md).

From SurrealDB 4.0, a token issued from such a grant acts as the user with the roles the user holds when the token is used. Removing the user, changing its roles, or revoking the grant takes effect on the next request.

### Example

```surql
DEFINE ACCESS api ON DATABASE TYPE BEARER FOR USER
	DURATION FOR GRANT 30d, FOR TOKEN 15m, FOR SESSION 12h;
```

In this example, grants created with this bearer access method will be valid for 30 days. After signing in with any of those grants, SurrealDB will return a token that will be valid for 15 minutes. This token can be used to establish an authenticated SurrealDB session valid for 12 hours. Grants created with this access method will only allow a system user as its subject.

```surql
-- Define system user that access will be granted to
DEFINE USER automation ON DATABASE PASSWORD 'secret' ROLES VIEWER;
-- Define bearer access method to generate API keys for system users
DEFINE ACCESS api ON DATABASE TYPE BEARER FOR USER
	DURATION FOR GRANT 10d;
-- Generate bearer grant to be used by a specific automation
ACCESS api GRANT FOR USER automation;
```

```surql title="Example output"
{
	ac: 'api',
	creation: d'2025-10-07T04:52:36.157Z',
	expiration: d'2025-10-17T04:52:36.157Z',
	grant: {
		id: 'W9gi9FVexSLP',
		key: 'surreal-bearer-W9gi9FVexSLP-WFmLPW6GyFyj1gJMdEY22YzA'
	},
	id: 'W9gi9FVexSLP',
	revocation: NONE,
	subject: {
		user: 'automation'
	},
	type: 'bearer'
}
```

The key value returned in the grant object is the bearer key, which can be used to sign in as the `automation` user without using its password.

Here are some examples on how to do that using the [JavaScript SDK](/docs/reference/javascript.md) or a raw [HTTP request](/docs/reference/protocols/http-protocol.md).

#### JavaScript SDK

```js
const db = new Surreal();
db.connect('ws://localhost:8000/rpc', {
	namespace: 'main',
	database: 'main',
});

db.signin({
	namespace: 'main',
	database: 'main',

	// Provide the name of the access method
	access: 'api',

	// Provide the bearer key in the "key" variable
	variables: {
    		key: 'surreal-bearer-BNb2pS0GmaJz-5eTfQ5uEu8jbRb3oblqVMAt8',
	}
});
```

#### HTTP request

```bash
curl -X POST \
	-H "Accept: application/json" \
	-d '{"NS":"main", "DB":"main", "AC":"api", "key":"surreal-bearer-BNb2pS0GmaJz-5eTfQ5uEu8jbRb3oblqVMAt8"}' \
	http://localhost:8000/signin
```

## `FOR RECORD`

Defining a bearer access method `FOR RECORD` will ensure that grants can only be created with a [record user](/docs/learn/security/authentication/users.md#record-users) as its subject. This application is useful for integrations that require accessing only some data in a specific SurrealDB database and in accordance with existing `PERMISSIONS` clauses. Bearer access can only be defined `FOR RECORD` if a database is selected and using `ON DATABASE`.

```surql
-- Create record representing a user
CREATE user:1 CONTENT { name: "tobie" };
-- Define bearer access method to generate API keys for record users
DEFINE ACCESS api ON DATABASE TYPE BEARER FOR RECORD
	DURATION FOR GRANT 10d;
-- Generate bearer grant to be used by a specific automation belonging to the user
ACCESS api GRANT FOR RECORD user:1;
```

```surql title="Example output"
-- Query 1
[
        {
                id: user:1,
                name: 'tobie'
        }
]
-- Query 2
NONE
-- Query 3
{
	ac: 'api',
	creation: d'2025-10-07T04:54:26.258986Z',
	expiration: d'2025-10-17T04:54:26.258987Z',
	grant: {
		id: 'jeGA4jfNmnoD',
		key: 'surreal-bearer-jeGA4jfNmnoD-X2xYQ1IILzB47DttrNpMBquN'
	},
	id: 'jeGA4jfNmnoD',
	revocation: NONE,
	subject: {
		record: user:1
	},
	type: 'bearer'
};
```

The key value returned in the grant object is the bearer key, which can be used to sign in as the `user:1` record in SurrealDB.

Here are some examples on how to do that using the JavaScript SDK or a raw HTTP request.

### JavaScript SDK

```js
const db = new Surreal();
db.connect('ws://localhost:8000/rpc', {
	namespace: 'main',
	database: 'main',
});

db.signin({
	namespace: 'main',
	database: 'main',

	// Provide the name of the access method
	access: 'api',

	// Provide the bearer key in the "key" variable
	variables: {
    		key: 'surreal-bearer-NJ2I2d7OXxN9-Oa5LqF36IzfURpo6Bhxy9WMF',
	}
});
```

### HTTP request

```bash
curl -X POST \
	-H "Accept: application/json" \
	-d '{"NS":"main", "DB":"main", "AC":"api", "key":"surreal-bearer-NJ2I2d7OXxN9-Oa5LqF36IzfURpo6Bhxy9WMF"}' \
	http://localhost:8000/signin
```

## Using `IF NOT EXISTS` clause

The `IF NOT EXISTS` clause can be used to define an access method of type BEARER only if it does not already exist. You should use the `IF NOT EXISTS` clause when defining an access method in SurrealDB if you want to ensure that the access method is only created if it does not already exist. If the access method already exists, the `DEFINE ACCESS` statement will return an error.

It's particularly useful when you want to safely attempt to define an access method without manually checking its existence first.

```surql
-- Create a BEARER access method for the example database if it does not already exist
DEFINE ACCESS IF NOT EXISTS example ON DATABASE TYPE BEARER FOR USER;
```

## Using `OVERWRITE` clause

The `OVERWRITE` clause can be used to define an access method of type BEARER and overwrite an existing one if it already exists. You should use the `OVERWRITE` clause when you want to modify an existing access method definition. If the access method already exists, the `DEFINE ACCESS` statement will overwrite the existing access method definition with the new one.

```surql
-- Create a BEARER access method for the example database and overwrite if it already exists
DEFINE ACCESS OVERWRITE example ON DATABASE TYPE BEARER FOR USER;
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/access/jwt

# JWT

A JWT access method lets SurrealDB accept tokens from a trusted issuer, such as an OpenID Connect (OIDC) or OAuth 2.0 provider, verified with a shared secret, a public key or a JWKS URL.

A JWT access method allows accessing SurrealDB with a token signed by a trusted issuer. The contents of the token will be trusted by SurrealDB as long as it has been signed with a trusted credential.

SurrealDB can work with third-party authentication providers such as OpenID Connect providers, OAuth providers and other trusted parties providing JWT (JSON Web Tokens, also referred to in this page as “tokens”). For example, your provider may issue your client (e.g. a user or a service) a JWT once it has authenticated. By using the `DEFINE ACCESS ... TYPE JWT` statement, you can set the public key or shared secret that will be used to verify the authenticity of the token.

This verification is performed automatically by SurrealDB when provided with a JWT through any of its interfaces (i.e. the [HTTP REST API](/docs/reference/protocols/http-protocol.md) through the “Authorization” header or [any of the SDKs](/docs/languages.md) through the “Authenticate” methods) before trusting the claims contained in the token and allowing SurrealQL queries to access the values of those claims.

This statement and `DEFINE ACCESS ... TYPE RECORD ... WITH JWT` replaced `DEFINE TOKEN` in SurrealDB 2.0, and SurrealDB 3.0 removed `DEFINE TOKEN`.

Bear in mind that table and field permissions only apply to [record users](/docs/learn/security/authentication/users.md#record-users), which must use tokens that are verified by a `RECORD` access method. Access provided by namespace and database tokens defined in a `JWT` access method is equivalent to access from [system users](/docs/learn/security/authentication/users.md#system-users), which is above fine-grained permissions. When application users will be the ones directly authenticating with JWT, defining a `RECORD` access method `WITH JWT` is most likely the right choice.

## Requirements

- You must be authenticated as a [system user](/docs/learn/security/authentication/users.md#system-users) at the same level or higher than the level to which you want to provide JWT access.
- [You must select a namespace or database](/docs/reference/query-language/statements/use.md) before you can define a JWT access method.

## Statement syntax

```syntax title="SurrealQL Syntax"
DEFINE ACCESS [ OVERWRITE | IF NOT EXISTS ] @name
  ON [ ROOT | NAMESPACE | DATABASE ]
  TYPE JWT [ ALGORITHM @algorithm KEY @key | URL @url ]
  [ AUDIENCE @audience, .. ]
  [ AUTHENTICATE @expression ]
  [ DURATION FOR SESSION @duration ]
```

## Verification types

When defining a token, its type describes the cryptographic algorithm or specification that will be used to verify the token. This can be an HMAC algorithm, a public-key cryptography algorithm or a remote JWKS object containing all the required information to verify the token. When not specified, the type is defined as the `HS256` HMAC cryptographic algorithm.

### Hash-based message authentication code (HMAC)

With HMAC algorithms (`HS256`,`HS384`,`HS512`) the value of the defined token will be the secret used both to sign (by the issuer of the token) and verify (by SurrealDB) the token. Anyone with access to this secret will be able to issue tokens with arbitrary claims which will be trusted by SurrealDB.

The following example shows the definition of a token using an HMAC algorithm.

```surql
-- Specify the namespace and database for the token
USE NS abcum DB app_vitalsense;

-- Set the name of the token
DEFINE ACCESS token_name
  -- Use this token provider for database authentication
  ON DATABASE
  -- Specify the type of access being defined
  TYPE JWT
  -- Specify the cryptographic signature algorithm used to verify the token
  ALGORITHM HS512
  -- Specify the symmetric key used to sign and verify the authenticity of the token
  KEY "sNSYneezcr8kqphfOC6NwwraUHJCVAt0XjsRSNmssBaBRh3WyMa9TRfq8ST7fsU2H2kGiOpU4GbAF1bCiXmM1b3JGgleBzz7rsrz6VvYEM4q3CLkcO8CMBIlhwhzWmy8"
;
```

### Public-key cryptography

With public-key cryptography algorithms (`EDDSA`, `ES256`, `ES384`, `ES512`, `PS256`, `PS384`, `PS512`, `RS256`, `RS384`, `RS512`) the value of the defined token will be the public key used to verify the signature of the token. This value is not secret and should be provided by the issuer of the tokens. Tokens will be signed using the private key, known only to the issuer. The public key value should be provided to SurrealDB including its header and footer. Any whitespace will be trimmed.

The following example shows the definition of a token using a public-key cryptography algorithm.

```surql
-- Specify the namespace and database for the token
USE NS abcum DB app_vitalsense;

-- Set the name of the token
DEFINE ACCESS token_name
  -- Use this token provider for database authentication
  ON DATABASE
  -- Specify the type of access being defined
  TYPE JWT
  -- Specify the cryptographic signature algorithm used to verify the token
  ALGORITHM RS256
  -- Specify the public key used to verify the authenticity of the token
  KEY "-----BEGIN PUBLIC KEY-----
MUO52Me9HEB4ZyU+7xmDpnixzA/CUE7kyUuE0b7t38oCh+sQouREqIjLwgHhFdhh3cQAwr6GH07D
ThioYrZL8xATJ3Youyj8C45QnZcGUif5PkpWXDi0HJSoMFekbW6Pr4xuqIqb2LGxGDVJcLZwJ2AS
Gtu2UAfPXbBD3ffiad393M22g1iHM80YaNi+xgswG7qtXE4lR/Lt4s0MeKKX7stdWI1VIsoB+y3i
r/OWUvJPjjDNbAsyy8tQmxydv+FUnLEP9TNT4AhN4DXcJ+XsDtW7OWt4EdSVDeKpGbIMvIrh1Pe+
Nilj8UHNyNDHa2AjK3seMo6CMvaIQJKj5o4xGFblFGwvvPD03SbuQLs1FdRjsZCeWLdYeQ3JDHE9
sFG7DCXlpMJcaYT1mf4XHJ0gPekNLQyewTY3Vxf7FgV3GCNjV20kcDFgJA2+iVW2wSrb+txD1ycE
kbi8jh0pedWwE40VQWaTh/8eAvX7IHWya/AEro25mq+m6vktNZLbvLphhp586kJK3Tdt3YjpkPre
M3nkFWOWurIyKbtIV9JemfwCgt89sNV45dTlnEDEZFFGnIgDnWgx3CUo4XmhICEQU8+tklw9jJYx
iCTjhbIDEBHySSSc/pQ4ftHQmhToTlQeOdEy4LYiaEIgl1X+hzRH1hBYvWlNKe4EY1nMCKcjgt0=
-----END PUBLIC KEY-----"
;
```

### JSON web key set (JWKS)

With JWKS, a set of JWK (JSON Web Key) objects will be dynamically fetched from a remote location and used to verify tokens following the [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517) specification. When defining a JWKS token verification method, its value should contain a valid URL that is reachable by SurrealDB and allowed by the configured network [capabilities](/docs/learn/security/authorization/capabilities.md). This URL should point to a valid JWKS object (as described in [Section 5 of RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517#section-5)) in the form of a JSON document. This is the recommended method to integrate with authentication providers that support JWKS. Providers like [Google](https://developers.google.com/identity/openid-connect/openid-connect#discovery), [AWS Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html#amazon-cognito-user-pools-using-tokens-manually-inspect), [Azure Active Directory](https://azure.github.io/azure-workload-identity/docs/installation/self-managed-clusters/oidc-issuer/jwks.html), [Auth0](https://auth0.com/docs/secure/tokens/json-web-tokens/json-web-key-sets), [Keycloak](https://documentation.cloud-iam.com/how-to-guides/configure-remote-jkws.html) or [OneLogin](https://developers.onelogin.com/authentication/tools/jwt) provide JWKS endpoints to verify tokens issued by their services.

> [!NOTE: Before you start]
> JWKS downloads need the [network capability](/docs/learn/security/authorization/capabilities.md#network). For a public issuer, allow the JWKS hostname (for example `--allow-net example.com`). If that hostname resolves to a private or special-use address (common for in-cluster issuers), also allow the matching IP or CIDR. See [Network capabilities](/docs/learn/security/authorization/capabilities.md#network) for more details.

The following example shows the definition of a token using a JWKS.

```surql
-- Specify the namespace and database for the token
USE NS abcum DB app_vitalsense;

-- Set the name of the token
DEFINE ACCESS token_name
  -- Use this token provider for database authentication
  ON DATABASE
  -- Specify the type of access being defined
  TYPE JWT
  -- Specify the URL where the JWKS object can be found
  URL "https://example.com/.well-known/jwks.json"
;
```

Validating tokens generated by third-party authentication providers using JWKS ensures that keys can be revoked directly from the third-party service and will no longer be accepted by SurrealDB after the local cache for those keys expires. Likewise, it ensures that token verification will not break if keys are rotated, as any new keys will be automatically fetched from the authentication provider if a JWT is received containing a new key identifier in its `kid` header.

To avoid performing requests to the remote URL for each token that is verified, SurrealDB caches every JWKS object that it pulls for a period of 12 hours. The cache can be purged earlier (e.g. in the event a key is compromised) by restarting the SurrealDB server. If a JWT is received containing a reference to a new key identifier in its `kid` header, the JWKS object will be fetched again and updated in the cache if the key identifier is found in the remote JWKS object; this operation will only be performed once every 5 minutes to prevent malicious actors from abusing this process to perform denial of service.

The cache period, the time between fetches for an unknown key identifier, and the time a fetch may take before it fails (1 second by default) are set on the server with [`SURREAL_JWKS_CACHE_EXPIRATION_SECONDS`, `SURREAL_JWKS_CACHE_COOLDOWN_SECONDS` and `SURREAL_JWKS_REMOTE_TIMEOUT_MILLISECONDS`](/docs/reference/cli/db/environment-variables.md#security-config).

## Using tokens

The `DEFINE ACCESS ... TYPE JWT` statement lets you specify the amount of permission granting authority you want to give to a token issuer. You are able to specify if the provider can grant namespace or database access to token holders. For this to work, the JWT issued to be used with SurrealDB must contain claims to specify which namespace or database the token bearer is authorised to act on.

The following claims should be added to the JWT payload by the issuer of the token:

- `exp`: The token expiration Unix time. The token will not be valid after.
- `ac`: The name of the access method used to verify the token.
- `ns`: The namespace that the token is issued for.
- `db`: The database that the token is issued for.

The names of these claims can be in all lowercase (i.e. `ac`) or all uppercase (i.e. `AC`), and can be optionally prefaced with the `https://surrealdb.com` namespace (e.g. `https://surrealdb.com/ac`) in order to separate claims directed to SurrealDB from claims directed to other services. When using a namespace, the claim name can also be used without abbreviation, such as in `https://surrealdb.com/access`, `https://surrealdb.com/database`...

The following optional claim is also processed by SurrealDB:

- `nbf`: The token acceptance Unix time. The token will not be valid before.

The expected claims depend on the level at which the token was defined:

- For tokens defined `ON ROOT`: `exp`, `ac`.
- For tokens defined `ON NAMESPACE`: `exp`, `ac`, `ns`.
- For tokens defined `ON DATABASE`: `exp`, `ac`, `ns`, `db`.

> [!NOTE]
> An `id` claim is **not** required for `TYPE JWT`. That claim identifies a [record user](/docs/learn/security/authentication/users.md#record-users) and belongs to [`DEFINE ACCESS ... TYPE RECORD ... WITH JWT`](/docs/reference/query-language/statements/define/access/record.md#with-json-web-token). A `TYPE JWT` token without `id` authenticates as a [system user](/docs/learn/security/authentication/users.md#system-users) session.

SurrealDB reads these claims from the token itself, and nothing else can supply them. The `surreal-auth-ns` and `surreal-auth-db` HTTP headers apply to username and password authentication only, not to a token. For an identity provider whose tokens cannot carry custom claims, either have your backend issue SurrealDB tokens that include them, or let the client sign in through a [record access method that verifies the provider's token](/docs/reference/query-language/statements/define/access/record.md#signing-in-with-another-providers-token) and issues a SurrealDB token in return.

For tokens defined for [system users](/docs/learn/security/authentication/users.md#system-users), the optional `rl` claim containing an array of capitalized [system user roles](/docs/reference/query-language/statements/define/user.md#roles) (e.g. `["Viewer", "Editor", "Owner"]`) can be provided. Doing so will apply the access policy for those roles to any action made using the token. By default, sessions established with tokens without the `rl` claim will only have the `Viewer` role.

When calling any of the SurrealDB interfaces using a JWT, SurrealQL queries will gain access to the claims in the token through the `$token` variable. For example, if the token contains custom claims such as “name” or “email”, the values of those claims will be accessible through `$token.name` and `$token.email`.

The signature of the token is verified with method defined when creating the token. If the signature of the token is invalid, calls to SurrealDB interfaces using that token will fail.

### Root

Root tokens can be used to select, create, update, and delete on all tables in all databases of all namespaces, as well as to define and remove namespaces and databases from the SurrealDB instance.

```surql
-- Set the name of the token
DEFINE ACCESS token_name
  -- Use this token provider for root authentication
  ON ROOT
  -- Specify the type of access being defined
  TYPE JWT
  -- Specify the cryptographic signature algorithm used to verify the token
  ALGORITHM HS512
  -- Specify the symmetric key used to sign and verify the authenticity of the token
  KEY "sNSYneezcr8kqphfOC6NwwraUHJCVAt0XjsRSNmssBaBRh3WyMa9TRfq8ST7fsU2H2kGiOpU4GbAF1bCiXmM1b3JGgleBzz7rsrz6VvYEM4q3CLkcO8CMBIlhwhzWmy8"
;
```
The root token payload should at least include the following claims when used to authenticate with SurrealDB.

```json title="JWT Payload"
{
  "exp": 2147483647,
  "ac": "token_name",
}
```

### Namespace

Namespace tokens can be used to select, create, update, and delete on all tables in all databases, as well as to define and remove databases and tables from the namespace.

```surql
-- Specify the namespace for the token
USE NS abcum;

-- Set the name of the token
DEFINE ACCESS token_name
  -- Use this token provider for namespace authentication
  ON NAMESPACE
  -- Specify the type of access being defined
  TYPE JWT
  -- Specify the cryptographic signature algorithm used to verify the token
  ALGORITHM HS512
  -- Specify the symmetric key used to sign and verify the authenticity of the token
  KEY "sNSYneezcr8kqphfOC6NwwraUHJCVAt0XjsRSNmssBaBRh3WyMa9TRfq8ST7fsU2H2kGiOpU4GbAF1bCiXmM1b3JGgleBzz7rsrz6VvYEM4q3CLkcO8CMBIlhwhzWmy8"
;
```
The namespace token payload should at least include the following claims when used to authenticate with SurrealDB.

```json title="JWT Payload"
{
  "exp": 2147483647,
  "ac": "token_name",
  "ns": "abcum"
}
```

### Database

Database tokens can be used to select, create, update, and delete on all tables in a specific database, as well as to define and remove tables from the database.

```surql
-- Specify the namespace and database for the token
USE NS abcum DB app_vitalsense;

-- Set the name of the token
DEFINE ACCESS token_name
  -- Use this token provider for database authentication
  ON DATABASE
  -- Specify the type of access being defined
  TYPE JWT
  -- Specify the cryptographic signature algorithm used to verify the token
  ALGORITHM HS512
  -- Specify the symmetric key used to sign and verify the authenticity of the token
  KEY "sNSYneezcr8kqphfOC6NwwraUHJCVAt0XjsRSNmssBaBRh3WyMa9TRfq8ST7fsU2H2kGiOpU4GbAF1bCiXmM1b3JGgleBzz7rsrz6VvYEM4q3CLkcO8CMBIlhwhzWmy8"
;
```

The database token payload should at least include the following claims when used to authenticate with SurrealDB.

```json title="JWT Payload"
{
  "exp": 2147483647,
  "ac": "token_name",
  "ns": "abcum",
  "db": "app_vitalsense"
}
```

## With `AUTHENTICATE` clause

The `AUTHENTICATE` clause allows you to define a custom expression that will be executed when the token is verified. This expression will be executed in the context of the token, allowing you to perform additional checks on the token claims before the token is accepted. If the expression returns any value or throws any error, the token will be rejected.

### Example: JWT user authentication with issuer and audience check

This example sets up additional token verification logic for a system user on a database using JSON Web Tokens (JWT) to authenticate. In this example, the HS512 algorithm is used to sign the token. The `AUTHENTICATE` block contains conditions to verify the token's validity: it checks that the issuer (`iss`) of the token is "surrealdb-test" and throws an error if it is not. Similarly, it checks that the audience of the token (defined in the `aud` claim, which can be provided either as an array of strings or a single string) includes "surrealdb-test" and throws an error if it does not. If both checks pass, the token is considered valid. The session duration is set to 2 hours.

```surql
DEFINE ACCESS user ON DATABASE TYPE JWT
ALGORITHM HS512 KEY "sNSYneezcr8kqphfOC6NwwraUHJCVAt0XjsRSNmssBaBRh3WyMa9TRfq8ST7fsU2H2kGiOpU4GbAF1bCiXmM1b3JGgleBzz7rsrz6VvYEM4q3CLkcO8CMBIlhwhzWmy8"
AUTHENTICATE {
  IF $token.iss != "surrealdb-test" { THROW "Invalid token issuer" };
  IF type::is_array($token.aud) {
    IF "surrealdb-test" NOT IN $token.aud { THROW "Invalid token audience" }
  } ELSE {
    IF $token.aud IS NOT "surrealdb-test" { THROW "Invalid token audience" }
  };
}
DURATION FOR SESSION 2h;
```

## Audience validation

_(since v3.3.0)_

The `AUDIENCE` clause lists the values accepted for a token's `aud` claim. A token verified against the access method must carry an `aud` claim that intersects the list, and is rejected otherwise.

```surql
DEFINE ACCESS token_name ON DATABASE TYPE JWT
  ALGORITHM HS512 KEY "sNSYneezcr8kqphfOC6NwwraUHJCVAt0XjsRSNmssBaBRh3WyMa9TRfq8ST7fsqu"
  AUDIENCE "surrealdb-api";
```

Several values can be listed, which suits a token issued for more than one service, or a migration between audience names.

```surql
DEFINE ACCESS token_name ON DATABASE TYPE JWT
  ALGORITHM HS512 KEY "sNSYneezcr8kqphfOC6NwwraUHJCVAt0XjsRSNmssBaBRh3WyMa9TRfq8ST7fsqu"
  AUDIENCE "surrealdb-api", "surrealdb-internal";
```

The clause works the same way with a remote JWKS object, where it sits before the `WITH ISSUER` clause.

```surql
DEFINE ACCESS token_name ON DATABASE TYPE JWT
  URL "https://example.com/.well-known/jwks.json"
  AUDIENCE "surrealdb-api";
```

Where the clause is omitted the `aud` claim is not checked, which is the behaviour of an access method defined without it.

> [!IMPORTANT]
> An issuer that serves more than one application typically mints tokens with a distinct `aud` value per application. Without `AUDIENCE`, a token minted for a different application by the same issuer verifies successfully here, because the signature is valid. Setting the clause confines an access method to the tokens actually intended for it.

Audience values are configuration rather than secrets, so unlike a key they are shown in full by [`INFO`](/docs/reference/query-language/statements/info.md).

```surql title="Output"
DEFINE ACCESS token_name ON DATABASE TYPE JWT
  ALGORITHM HS512 KEY '[REDACTED]'
  AUDIENCE 'surrealdb-api'
  WITH ISSUER KEY '[REDACTED]'
  DURATION FOR TOKEN 1h, FOR SESSION NONE
```

## Using `IF NOT EXISTS` clause

The `IF NOT EXISTS` clause can be used to define an access method of type JWT only if it does not already exist. You should use the `IF NOT EXISTS` clause when defining an access method in SurrealDB if you want to ensure that the access method is only created if it does not already exist. If the access method already exists, the `DEFINE ACCESS` statement will return an error.

It's particularly useful when you want to safely attempt to define an access method without manually checking its existence first.

```surql
-- Create a JWT access method for the example database if it does not already exist
DEFINE ACCESS IF NOT EXISTS example ON DATABASE TYPE JWT ALGORITHM HS512 KEY
"sNSYneezcr8kqphfOC6NwwraUHJCVAt0XjsRSNmssBaBRh3WyMa9TRfq8ST7fsU2H2kGiOpU4GbAF1bCiXmM1b3JGgleBzz7rsrz6VvYEM4q3CLkcO8CMBIlhwhzWmy8";
```

## Using `OVERWRITE` clause

The `OVERWRITE` clause can be used to define an access method of type JWT and overwrite an existing one if it already exists. You should use the `OVERWRITE` clause when you want to modify an existing access method definition. If the access method already exists, the `DEFINE ACCESS` statement will overwrite the existing access method definition with the new one.

```surql
-- Create a JWT access method for the example database and overwrite it if it already exists
DEFINE ACCESS OVERWRITE example ON DATABASE TYPE JWT ALGORITHM HS512 KEY 'secret';
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/access/record

# RECORD

A record access method allows accessing SurrealDB as a record user.

A record access method allows accessing SurrealDB as a [record user](/docs/learn/security/authentication/users.md#record-users).

Record users allow SurrealDB to operate as a web database by offering mechanisms to define custom signin and signup logic as well as custom table and field permissions.

This statement replaced `DEFINE SCOPE` in SurrealDB 2.0, and SurrealDB 3.0 removed `DEFINE SCOPE`. The [1.x to 2.x upgrade guide](/docs/operate/upgrading/1x-to-2x.md) covers moving a scope to a record access method.

## Requirements

- You must be authenticated as a [root, namespace or database user](/docs/reference/query-language/statements/define/user.md) before you can define a record access method.
- [You must select your namespace and database](/docs/reference/query-language/statements/use.md) before you can define a record access method.

## Statement syntax

```syntax title="SurrealQL Syntax"
DEFINE ACCESS [ OVERWRITE | IF NOT EXISTS ] @name
  ON DATABASE TYPE RECORD
    [ SIGNUP @expression ]
    [ SIGNIN @expression ]
    [ WITH JWT
      [ ALGORITHM @algorithm KEY @key | URL @url ]
      [ AUDIENCE @audience, .. ]
      [ WITH ISSUER KEY @key ]
    ]
    [ WITH REFRESH ]
  [ AUTHENTICATE @expression ]
  [ DURATION
    [ FOR TOKEN @duration ]
    [ FOR SESSION @duration ]
  ]
```

## Example usage

Below shows how you can define record access using the `DEFINE ACCESS ... TYPE RECORD` statement.

```surql
-- One account per email address
DEFINE INDEX unique_email ON user FIELDS email UNIQUE;

DEFINE ACCESS account ON DATABASE TYPE RECORD
	SIGNUP ( CREATE user SET email = $email, pass = crypto::argon2::generate($pass) )
	SIGNIN ( SELECT * FROM user WHERE email = $email
	  AND crypto::argon2::compare(pass, $pass) )
	DURATION FOR TOKEN 15m, FOR SESSION 12h
;
```

Without the `UNIQUE` index, two sign-ups with the same email address would create two users, and `SIGNIN` would then match both. With it, the second sign-up fails.

The client sends the password to SurrealDB as the `$pass` parameter, and `crypto::argon2::generate` hashes it on the server. Anyone who can read the connection can therefore read the password unless the connection is encrypted, so serve SurrealDB over HTTPS and WSS as described in [Encryption in transit](/docs/learn/security/best-practices/security-best-practices.md#encryption-in-transit). Hashing the password on the client does not replace this: the hash then works as the password, and anyone who reads it on the connection can sign in with it.

### Refusing a sign-up with `THROW`

`SIGNUP` and `SIGNIN` can take a block instead of a single expression, so they can check a condition before they create or return the user. A [`THROW`](/docs/reference/query-language/statements/throw.md) inside the block stops the attempt, and the client receives the message as part of the error.

The access method below only accepts a sign-up that has an unused invite code. It marks the code as used in the same attempt, so a second sign-up with the same code fails.

```surql
DEFINE TABLE invite SCHEMAFULL;
DEFINE FIELD code ON invite TYPE string;
DEFINE FIELD used ON invite TYPE bool DEFAULT false;
CREATE invite:one SET code = "WELCOME-42";

DEFINE ACCESS account ON DATABASE TYPE RECORD
	SIGNUP {
		LET $invite = (
			SELECT * FROM ONLY invite
			WHERE code = $invite_code AND used = false
			LIMIT 1
		);
		IF $invite IS NONE {
			THROW "This invite code is not valid";
		};
		UPDATE $invite.id SET used = true;
		CREATE user SET email = $email, pass = crypto::argon2::generate($pass);
	}
	SIGNIN ( SELECT * FROM user WHERE email = $email AND crypto::argon2::compare(pass, $pass) );
```

A sign-up with the parameters `email`, `pass` and `invite_code` succeeds and returns a token when the code is `WELCOME-42`. With any other code, or with the same code a second time, it fails with this error:

```text title="Error output"
An error occurred: This invite code is not valid
```

The same pattern works in `SIGNIN`, for example to refuse a user whose account is disabled. The [`AUTHENTICATE` clause](#with-authenticate-clause) runs after both of them and can also refuse a session.

### Password reset

A record access method has no built-in password reset, but the `SIGNIN` clause can accept a one-time reset token as well as a password. The reset works in two steps:

1. **Your backend creates the token.** When a user asks for a reset, a backend service signed in as a [system user](/docs/learn/security/authentication/users.md#system-users) stores a random token with an expiry time, and sends the user a link that contains it. SurrealDB does not send email, so this step belongs to the application.
2. **The user signs in with the token.** The client signs in with `reset_token` and the new password. `SIGNIN` checks the token, deletes it so that it works only once, and saves the new password. The client receives a token for the session, as with a normal sign-in.

```surql
DEFINE TABLE user SCHEMAFULL PERMISSIONS FOR select, update WHERE id = $auth;
DEFINE FIELD email ON user TYPE string;
DEFINE FIELD pass ON user TYPE string;
DEFINE INDEX unique_email ON user FIELDS email UNIQUE;

-- Record users have no access to this table
DEFINE TABLE password_reset SCHEMAFULL PERMISSIONS NONE;
DEFINE FIELD user ON password_reset TYPE record<user>;
DEFINE FIELD token ON password_reset TYPE string;
DEFINE FIELD expires_at ON password_reset TYPE datetime;
DEFINE INDEX unique_token ON password_reset FIELDS token UNIQUE;

DEFINE ACCESS account ON DATABASE TYPE RECORD
	SIGNUP ( CREATE user SET email = $email, pass = crypto::argon2::generate($pass) )
	SIGNIN {
		IF $reset_token {
			LET $reset = (
				SELECT * FROM ONLY password_reset
				WHERE token = $reset_token AND expires_at > time::now()
				LIMIT 1
			);
			IF $reset IS NONE {
				THROW "This reset link is not valid or has expired";
			};
			DELETE $reset.id;
			RETURN UPDATE ONLY $reset.user SET pass = crypto::argon2::generate($pass);
		};
		RETURN SELECT * FROM user WHERE email = $email AND crypto::argon2::compare(pass, $pass);
	}
	DURATION FOR TOKEN 15m, FOR SESSION 12h;
```

The backend creates the token with a statement like the one below, then puts the returned `token` in the link it sends. If no user has the email address, the statement fails because `user` must be a record, and the backend can reply to the request in the same way in both cases, so that the reply does not show which addresses have an account.

```surql
-- Setup from the example above
DEFINE TABLE user SCHEMAFULL PERMISSIONS FOR select, update WHERE id = $auth;
DEFINE FIELD email ON user TYPE string;
DEFINE FIELD pass ON user TYPE string;
DEFINE INDEX unique_email ON user FIELDS email UNIQUE;
DEFINE TABLE password_reset SCHEMAFULL PERMISSIONS NONE;
DEFINE FIELD user ON password_reset TYPE record<user>;
DEFINE FIELD token ON password_reset TYPE string;
DEFINE FIELD expires_at ON password_reset TYPE datetime;
DEFINE INDEX unique_token ON password_reset FIELDS token UNIQUE;

-- Setup
CREATE user SET email = 'ann@example.com', pass = crypto::argon2::generate('secret');
LET $email = 'ann@example.com';

CREATE password_reset SET
	user = (SELECT VALUE id FROM ONLY user WHERE email = $email LIMIT 1),
	token = rand::string(40),
	expires_at = time::now() + 30m
RETURN token;
```

The client then signs in with the parameters `reset_token` and `pass`. A token that is wrong, already used or expired fails with this error:

```text title="Error output"
An error occurred: This reset link is not valid or has expired
```

After the reset, the old password no longer signs in, and the new password signs in with `email` and `pass` as usual.

### Signing in with another provider's token

A token from another identity provider can only be used with SurrealDB directly if it carries the `ns`, `db` and `ac` claims, as [`DEFINE ACCESS ... TYPE JWT`](/docs/reference/query-language/statements/define/access/jwt.md#using-tokens) describes. When a provider cannot add those claims, a `SIGNIN` clause can verify the provider's token instead. It sends the token to the provider's API with [`http::get`](/docs/reference/query-language/functions/database-functions/http.md#httpget), finds or creates the matching user, and SurrealDB returns its own token for the session.

The example below does this with an OpenStreetMap access token. The server must be allowed to reach the provider, here with `--allow-net api.openstreetmap.org`:

```surql
DEFINE ACCESS osm ON DATABASE TYPE RECORD
	SIGNIN {
		-- Fails with an error if OpenStreetMap does not accept the token
		LET $me = http::get(
			"https://api.openstreetmap.org/api/0.6/user/details.json",
			{ Authorization: "Bearer " + $osm_token }
		);
		RETURN UPSERT ONLY type::record("user", $me.user.id) MERGE { name: $me.user.display_name };
	};
```

The client signs in with the parameters `ns`, `db`, `ac` set to `osm`, and `osm_token`, and receives a SurrealDB token for the user. A token that the provider refuses makes `http::get` fail, so the sign-in fails too.

### With JSON web token

Successful authentication with a record access method results in SurrealDB generating a JSON Web Token (JWT or, in the context of SurrealDB, just "token") that can be used until its expiration to authenticate as the record user without the need of providing any additional credentials. These tokens can also be issued by third parties and trusted by SurrealDB in order to allow for the authentication process to take place outside of SurrealDB, while the resulting access claims can be provided to SurrealDB inside of a token that it can trust. This feature is provided by the `WITH JWT` clause, which behaves similarly to [the JWT access method](/docs/reference/query-language/statements/define/access/jwt.md), including the [`AUDIENCE`](/docs/reference/query-language/statements/define/access/jwt.md#audience-validation) clause for restricting which `aud` claim values are accepted.

Since the origin of the claims in the JWT is verified, those claims can be used within SurrealQL in order to provide table and field authorization through an external authenticator using OpenID Connect, OAuth or simply acting as a trusted issuer of a JWT. This can be done by using table permissions to allow or disallow access depending on the values of the claims in the verified token. For example, these claims can be compared with the records in a table to only return those matching certain criteria.

Bear in mind that table and field permissions only apply to [record users](/docs/learn/security/authentication/users.md#record-users), which must use tokens that are verified by a `RECORD` access method. Access provided by namespace and database tokens defined in a `JWT` access method is equivalent to access from [system users](/docs/learn/security/authentication/users.md#system-users), which is above fine-grained permissions. When application users will be the ones directly authenticating with JWT, defining a `RECORD` access method `WITH JWT` is most likely the right choice.

Reference [the JWT access method](/docs/reference/query-language/statements/define/access/jwt.md) documentation for additional information about how JWT tokens can be used in SurrealDB, including verification through [JWKS](/docs/reference/query-language/statements/define/access/jwt.md#json-web-key-set-jwks).

The following example shows how record access with a token can be used to grant authorization either by verifying that the `id` claim in the token (which is used to populate the [`$auth`](/docs/reference/query-language/language-primitives/parameters.md#auth) reserved parameter) matches the record that is being queried from the `user` table or if the `privileged` claim is set to `true` in the token:

```surql
-- Specify the namespace and database for the token
USE NS abcum DB app_vitalsense;

DEFINE ACCESS token_name ON DATABASE TYPE RECORD WITH JWT
ALGORITHM RS256 KEY "-----BEGIN PUBLIC KEY-----
MUO52Me9HEB4ZyU+7xmDpnixzA/CUE7kyUuE0b7t38oCh+sQouREqIjLwgHhFdhh3cQAwr6GH07D
ThioYrZL8xATJ3Youyj8C45QnZcGUif5PkpWXDi0HJSoMFekbW6Pr4xuqIqb2LGxGDVJcLZwJ2AS
Gtu2UAfPXbBD3ffiad393M22g1iHM80YaNi+xgswG7qtXE4lR/Lt4s0MeKKX7stdWI1VIsoB+y3i
r/OWUvJPjjDNbAsyy8tQmxydv+FUnLEP9TNT4AhN4DXcJ+XsDtW7OWt4EdSVDeKpGbIMvIrh1Pe+
Nilj8UHNyNDHa2AjK3seMo6CMvaIQJKj5o4xGFblFGwvvPD03SbuQLs1FdRjsZCeWLdYeQ3JDHE9
sFG7DCXlpMJcaYT1mf4XHJ0gPekNLQyewTY3Vxf7FgV3GCNjV20kcDFgJA2+iVW2wSrb+txD1ycE
kbi8jh0pedWwE40VQWaTh/8eAvX7IHWya/AEro25mq+m6vktNZLbvLphhp586kJK3Tdt3YjpkPre
M3nkFWOWurIyKbtIV9JemfwCgt89sNV45dTlnEDEZFFGnIgDnWgx3CUo4XmhICEQU8+tklw9jJYx
iCTjhbIDEBHySSSc/pQ4ftHQmhToTlQeOdEy4LYiaEIgl1X+hzRH1hBYvWlNKe4EY1nMCKcjgt0=
-----END PUBLIC KEY-----";

DEFINE TABLE user SCHEMAFULL
  -- Authorized users can select, update, delete and create user records
  PERMISSIONS FOR select, update, delete, create
  -- The access method must be "users"
  WHERE $access = "users"
  -- The record of the user being queried must match the one identified in the token
  -- Only matching records will be changed or returned
  AND id = $auth.id
  -- Allow privileged tokens to query any user
  OR $token.privileged = true
;
```

You may also use permissions clauses to perform additional verification on other JWT claims that may be required or recommended by the provider of the token, such as verifying that the `iss` claim matches a specific principal using `$token.iss`. However, this kind of logic may be better suited for the [`AUTHENTICATE`](#with-authenticate-clause) clause, which is only executed when the token is validated before an authenticated session is established instead of in every query and for each record.

The token payload should at least include the following claims when used to authenticate as a record user in SurrealDB.

```json title="JWT Payload"
{
  "exp": 2147483647,
  "ns": "abcum",
  "db": "app_vitalsense",
  "ac": "users",
  "id": "user:1"
}
```

> [!IMPORTANT]
> For `TYPE RECORD ... WITH JWT`, the `id` claim must identify the record user, unless an [`AUTHENTICATE`](#with-authenticate-clause) clause resolves that record from other claims (for example an email address). This differs from [`TYPE JWT`](/docs/reference/query-language/statements/define/access/jwt.md#using-tokens), where `id` is not required and the session is a system user.

When the `id` claim is present in the token, the fields of the record matching the identifier specified will be accessible through the `$auth` reserved parameter. For example, if the value of the `id` claim is `user:73q1bl039y6k8z80v55d`, and user records have fields such as “name” or “email”, then `$auth.name` and `$auth.email` can be used to access those values for the `user:73q1bl039y6k8z80v55d` record specifically, without them being present in the JWT.

#### With issuer

When explicitly defining a way to verify tokens for record access, it is also possible to customise how these tokens are issued by SurrealDB. This allows specifying the algorithm and the signing key, which otherwise default to the HS512 algorithm with a randomly generated 128-character alphanumeric key. Configuring a record access method to sign tokens with specific signing credentials allows third party services to trust tokens issued by SurrealDB by trusting those signing credentials. In this way, an external service may rely on the signup and signin logic that has been implemented for record users in SurrealDB for its own authentication.

Currently, the algorithm for the issuer and the verifier are required to match. For this reason, the issuer algorithm can be omitted if it has already been defined in the `WITH JWT` clause. Likewise, an issuer does not need to be explicitly defined in the case where a key to verify JWT using a symmetric algorithm has already been defined in the `WITH JWT` clause, as the same key will also be used to sign the tokens.

The following is an example of defining a record access method that can issue tokens with an asymmetric key pair:

```surql
DEFINE ACCESS token_name ON DATABASE TYPE RECORD WITH JWT
ALGORITHM RS256
  KEY "-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu1SU1LfVLPHCozMxH2Mo
4lgOEePzNm0tRgeLezV6ffAt0gunVTLw7onLRnrq0/IzW7yWR7QkrmBL7jTKEn5u
+qKhbwKfBstIs+bMY2Zkp18gnTxKLxoS2tFczGkPLPgizskuemMghRniWaoLcyeh
kd3qqGElvW/VDL5AaWTg0nLVkjRo9z+40RQzuVaE8AkAFmxZzow3x+VJYKdjykkJ
0iT9wCS0DRTXu269V264Vf/3jvredZiKRkgwlL9xNAwxXFg0x/XFw005UWVRIkdg
cKWTjpBP2dPwVZ4WWC+9aGVd+Gyn1o0CLelf4rEjGoXbAAEgAqeGUxrcIlbjXfbc
mwIDAQAB
-----END PUBLIC KEY-----"
  WITH ISSUER KEY "-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC7VJTUt9Us8cKj
MzEfYyjiWA4R4/M2bS1GB4t7NXp98C3SC6dVMvDuictGeurT8jNbvJZHtCSuYEvu
NMoSfm76oqFvAp8Gy0iz5sxjZmSnXyCdPEovGhLa0VzMaQ8s+CLOyS56YyCFGeJZ
qgtzJ6GR3eqoYSW9b9UMvkBpZODSctWSNGj3P7jRFDO5VoTwCQAWbFnOjDfH5Ulg
p2PKSQnSJP3AJLQNFNe7br1XbrhV//eO+t51mIpGSDCUv3E0DDFcWDTH9cXDTTlR
ZVEiR2BwpZOOkE/Z0/BVnhZYL71oZV34bKfWjQIt6V/isSMahdsAASACp4ZTGtwi
VuNd9tybAgMBAAECggEBAKTmjaS6tkK8BlPXClTQ2vpz/N6uxDeS35mXpqasqskV
laAidgg/sWqpjXDbXr93otIMLlWsM+X0CqMDgSXKejLS2jx4GDjI1ZTXg++0AMJ8
sJ74pWzVDOfmCEQ/7wXs3+cbnXhKriO8Z036q92Qc1+N87SI38nkGa0ABH9CN83H
mQqt4fB7UdHzuIRe/me2PGhIq5ZBzj6h3BpoPGzEP+x3l9YmK8t/1cN0pqI+dQwY
dgfGjackLu/2qH80MCF7IyQaseZUOJyKrCLtSD/Iixv/hzDEUPfOCjFDgTpzf3cw
ta8+oE4wHCo1iI1/4TlPkwmXx4qSXtmw4aQPz7IDQvECgYEA8KNThCO2gsC2I9PQ
DM/8Cw0O983WCDY+oi+7JPiNAJwv5DYBqEZB1QYdj06YD16XlC/HAZMsMku1na2T
N0driwenQQWzoev3g2S7gRDoS/FCJSI3jJ+kjgtaA7Qmzlgk1TxODN+G1H91HW7t
0l7VnL27IWyYo2qRRK3jzxqUiPUCgYEAx0oQs2reBQGMVZnApD1jeq7n4MvNLcPv
t8b/eU9iUv6Y4Mj0Suo/AU8lYZXm8ubbqAlwz2VSVunD2tOplHyMUrtCtObAfVDU
AhCndKaA9gApgfb3xw1IKbuQ1u4IF1FJl3VtumfQn//LiH1B3rXhcdyo3/vIttEk
48RakUKClU8CgYEAzV7W3COOlDDcQd935DdtKBFRAPRPAlspQUnzMi5eSHMD/ISL
DY5IiQHbIH83D4bvXq0X7qQoSBSNP7Dvv3HYuqMhf0DaegrlBuJllFVVq9qPVRnK
xt1Il2HgxOBvbhOT+9in1BzA+YJ99UzC85O0Qz06A+CmtHEy4aZ2kj5hHjECgYEA
mNS4+A8Fkss8Js1RieK2LniBxMgmYml3pfVLKGnzmng7H2+cwPLhPIzIuwytXywh
2bzbsYEfYx3EoEVgMEpPhoarQnYPukrJO4gwE2o5Te6T5mJSZGlQJQj9q4ZB2Dfz
et6INsK0oG8XVGXSpQvQh3RUYekCZQkBBFcpqWpbIEsCgYAnM3DQf3FJoSnXaMhr
VBIovic5l0xFkEHskAjFTevO86Fsz1C2aSeRKSqGFoOQ0tmJzBEs1R6KqnHInicD
TQrKhArgLXX4v3CddjfTRJkFWDbE/CkvKZNOrcf1nhaGCPspRJj2KUkj1Fhl9Cnc
dn/RsYEONbwQSjIfMPkvxF+8HQ==
-----END PRIVATE KEY-----"
;
```

The issuer is implicitly defined when using a symmetric algorithm in `WITH JWT`:

```surql
DEFINE ACCESS token_name ON DATABASE TYPE RECORD WITH JWT
-- Symmetric algorithm with a symmetric key
-- The same key is used to sign and verify
ALGORITHM HS512 KEY "secret";
-- The following clause is implicit:
-- WITH ISSUER ALGORITHM HS512 KEY "secret"
```

### With refresh token

> [!NOTE]
> Before SurrealDB 3.0.0, the `WITH REFRESH` clause was experimental and required `--allow-experimental bearer_access`, refresh tokens were only returned by the [HTTP REST API](/docs/reference/protocols/http-protocol.md), and the response carried `token` and `refresh` as two top-level fields. From 3.0.0 refresh tokens are also returned by the [RPC](/docs/reference/protocols/rpc-protocol.md) `signin` and `signup` methods, and the token is an object holding `access` and `refresh`.

Defining a record access method `WITH REFRESH` will result in an additional [bearer key](/docs/reference/query-language/statements/define/access/bearer.md) for the record user being returned after successful authentication with the access method. This bearer key is intended to be used as a "refresh token", which is a concept commonly found in standards such as [OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc6749#section-1.5).

Unlike authentication tokens (i.e. JWT), refresh tokens (i.e. bearer keys) feature randomly generated opaque strings that contain no authentication information by themselves, but rather a pointer to an access grant that is stored in the datastore. Also unlike authentication tokens, bearer keys such as refresh tokens can be [audited](/docs/reference/query-language/statements/access.md#show) and [revoked](/docs/reference/query-language/statements/access.md#revoke) using the [`ACCESS`](/docs/reference/query-language/statements/access.md) statement. Refresh tokens are automatically revoked and replaced by a new refresh token whenever used to obtain an authentication token, reducing the time window for exploiting a compromised refresh token. These additional security guarantees allow refresh tokens to be longer-lived than authentication tokens, which in turn encourages making the original authentication tokens as short-lived as technically possible.

By default, refresh tokens will expire after 30 days. However, their duration can be configured using the `DURATION FOR GRANT` clause, which will accept any duration. If set to `NONE`, refresh tokens will never expire. It is strongly recommended to set some expiration for refresh tokens to minimize the potential impact of credential stealing attacks.

When a refresh token is exchanged for a new token, the access method's `AUTHENTICATE` clause runs again, and the record it returns is the record of the new session. An access method without an `AUTHENTICATE` clause accepts a refresh token only while the record it was issued for still exists.

Because refresh tokens can be used to indefinitely keep a user authenticated with SurrealDB as long as they are exchanged for a new fresh token before they expire, [special care](/docs/learn/security/best-practices/security-best-practices.md#token-storage) should be taken when storing and applications using them should be suitably protected from attacks.

Like other bearer keys, all refresh tokens are stored in the datastore even after they are expired or revoked. This means that using refresh tokens will have a space cost in addition to the performance cost of retrieving and verifying them against the datastore. Refresh tokens are intended to be used only to obtain a new authentication token after the existing one expires and applications should only use them when necessary, such as after receiving a [token expiration error](/docs/learn/security/best-practices/troubleshooting.md#token-expired-error). For certain high volume applications, you may want to regularly [purge](/docs/reference/query-language/statements/access.md#purge) expired refresh tokens to minimize the space used by inactive refresh tokens.

For more information on how to manage existing refresh tokens, see the [`ACCESS`](/docs/reference/query-language/statements/access.md) statement.

#### Example: Signing in with a refresh token

Define a record access method `WITH REFRESH`:

```surql
DEFINE ACCESS user ON DATABASE TYPE RECORD
	SIGNUP ( CREATE user SET email = $email, pass = crypto::argon2::generate($pass) )
	SIGNIN ( SELECT * FROM user WHERE email = $email
	  AND crypto::argon2::compare(pass, $pass) )
	WITH REFRESH
	DURATION FOR GRANT 15d, FOR TOKEN 1m, FOR SESSION 12h
;
```

Sign up with a new user or sign in with an existing user via the [HTTP REST API](/docs/reference/protocols/http-protocol.md). The RPC `signup` and `signin` methods return the same `access` and `refresh` pair as their result:

```bash
curl -X POST \
	-H "Accept: application/json" \
	-d '{"NS":"main", "DB":"main", "AC":"user", "name":"John Doe", "email":"john.doe@example.com", "pass":"VerySecurePassword!"}' \
	http://localhost:8000/signup
```

```json title="Example output"
{
	"code":200,
	"details":"Authentication succeeded",
	"token":{
		"access":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE3OTAyMjQ0MjksIm5iZiI6MTc5MDIyNDQyOSwiZXhwIjoxNzkwMjI0NDg5LCJpc3MiOiJTdXJyZWFsREIiLCJqdGkiOiJiYjNjZTkxNS1mM2JhLTRlYmUtYmI5My0zYTFmMmI3YzdkYzciLCJOUyI6Im1haW4iLCJEQiI6Im1haW4iLCJBQyI6InVzZXIiLCJJRCI6InVzZXI6bW01YzAxY3Zqd3Y1MGlrOXBxNXMifQ.KVQa-NXE6b8NUfneEaLXsygJ2ULYlidEfeaWmgODkAshROfF2WZ1HiVusSnwO1K62Ddjz_j5EcodA-9Xh-fGCA",
		"refresh":"surreal-refresh-zFX72BPE76gW-wQfRzW6o4IXC25T7T8JySiF9"
	}
}
```

Sign in with the refresh token to obtain a new token and refresh token:

```bash
curl -X POST \
	-H "Accept: application/json" \
	-d '{"NS":"main", "DB":"main", "AC":"user", "refresh":"surreal-refresh-zFX72BPE76gW-wQfRzW6o4IXC25T7T8JySiF9"}' \
	http://localhost:8000/signin
```

```json title="Example output"
{
	"code":200,
	"details":"Authentication succeeded",
	"token":{
		"access":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE3OTAyMjQ0MjksIm5iZiI6MTc5MDIyNDQyOSwiZXhwIjoxNzkwMjI0NDg5LCJpc3MiOiJTdXJyZWFsREIiLCJqdGkiOiIyNzY5MzJmOC03YzQyLTRjY2EtYTFiZi03NjAyN2Y3Nzg5NDYiLCJOUyI6Im1haW4iLCJEQiI6Im1haW4iLCJBQyI6InVzZXIiLCJJRCI6InVzZXI6bW01YzAxY3Zqd3Y1MGlrOXBxNXMifQ.M9GrqbMQ5mBAtxxTj_ekFcv5MH8XZSiW9j9qI_yzfA-rF6VWUmaAdxyBf97lh3KRrvy_604Dsrt6J2GrICayzQ",
		"refresh":"surreal-refresh-r4VS1wTbWIcL-bSGEkssOg9XKdFELgxjiF6cb"
	}
}
```

### With `AUTHENTICATE` clause

In the context of `DEFINE ACCESS ... TYPE RECORD`, the authenticate clause can be used to change the record identifier returned by the `SIGNIN` and `SIGNUP` clauses or replace the identifier provided in the token when authenticating `WITH JWT`.

This clause can also be used to log or stop authentication attempts from record users, as it is always executed across signin, signup, token authentication and the exchange of a refresh token.

Unlike the [`PERMISSIONS`](/docs/reference/query-language/statements/define/table.md#defining-permissions) clause, the `AUTHENTICATE` clause is executed only at the time of authentication, resulting in increased performance for queries that only need to be validated at that point.

On the other hand, permissions queries are executed in every query and for each record, ensuring that any authorization conditions are verified at the time of the query. The `AUTHENTICATE` clause is a good fit for validating specific conditions that are not expected to change during the lifetime of the session such as the presence of any required token claims.

#### Example: External authentication providers

Replacing the record identifier that will be used to establish the session is especially useful in scenarios where the token used to authenticate the session does not contain one. This is common when using an external authentication provider, which may only have knowledge of generic user identifiers such as an email address or UUID.

In the below example, we check if the session may already be tied to an existing user by using the `$auth` reserved parameter, which contains the record identifier of the authenticated user. If `$auth` is set and `record::exists($auth)` returns `true`, the token already contained the `id` of a record that exists in the database. The clause reads the record without checking the user's permissions, so this works even when record users cannot select from the `user` table. Testing `$auth.id` is not enough, because it gives the record ID from the token whether or not the record exists. If the token has no `id`, or the record does not exist, we can check if the token contains a different claim that we can rely on to uniquely identify users. In this case we check for an email address. If the `email` claim is present in the token, we try to retrieve the user from the `user` table by their email address. If none of the queries return a record, the `AUTHENTICATE` clause will fail with a generic error. You can also choose to `THROW` a custom error as shown in the next example.

```surql
DEFINE ACCESS user ON DATABASE TYPE RECORD
    WITH JWT ALGORITHM HS512 KEY 'secret'
    AUTHENTICATE {
        IF $auth AND record::exists($auth) {
            RETURN $auth;
        } ELSE IF $token.email {
            RETURN SELECT * FROM user WHERE email = $token.email;
        };
    }
;
```

#### Example: Failing authentication

Because the `AUTHENTICATE` clause is always executed across signin, signup and token authentication, it is in a unique position to centralise logic after user credentials are deemed valid, but before the user is completely authenticated.

Below, we show an example of validating if a user is enabled. If this is not the case, we can `THROW` an error stating why the user cannot authenticate, stopping the authentication attempt with a custom message. You can also choose to not return anything, which results in a generic authentication error. If the user is enabled, we can `RETURN` the record identifier, which confirms that authentication is successful and specifies that the record user which will be authenticated in the session is the same that was already authenticated.

```surql
DEFINE ACCESS user ON DATABASE TYPE RECORD
    SIGNUP ( CREATE user SET email = $email,
      pass = crypto::argon2::generate($pass), enabled = true )
    SIGNIN ( SELECT * FROM user WHERE email = $email
      AND crypto::argon2::compare(pass, $pass) )
    AUTHENTICATE {
        IF !$auth.enabled {
            THROW "This user is not enabled";
        };

        RETURN $auth;
    }
;
```

#### Example: Auditing and revoking tokens

In addition to what is shown in the previous example, the `AUTHENTICATE` clause can also be used to create records and access the claims found in the token itself using the `$token` reserved parameter. These features can be combined to log authentication attempts and stop authentication from completing if some conditions are met.

Below, we show a proof of concept example that uses the fact that tokens issued by SurrealDB have the standard `jti` claim, which contains a randomly generated unique identifier for the token. This value can be used to uniquely identify each token that is issued by SurrealDB for the purposes of auditing and revocation.

In this example, we create a new record in the `token` table for each token that SurrealDB issues after a successful `SIGNIN` and `SIGNUP`. This record is identified by the value in the `jti`(JWT ID) claim. Every time that a token is used to authenticate, we check if the record in the `token` table with identifier matching the `jti`(JWT ID) claim has been revoked and, if so, we fail authentication with a custom message. Otherwise, we log the time that the token was used to successfully authenticate in the `audit` table and continue authentication without changes.

```surql
DEFINE ACCESS user ON DATABASE TYPE RECORD
    SIGNUP ( CREATE user SET email = $email, pass = crypto::argon2::generate($pass) )
    SIGNIN ( SELECT * FROM user WHERE email = $email
      AND crypto::argon2::compare(pass, $pass) )
    AUTHENTICATE {
        IF type::record("token", $token.jti).revoked = true {
            THROW "This token has been revoked";
        };
        INSERT INTO token { id: $token.jti, exp: $token.exp, revoked: false };
        CREATE audit CONTENT { token: $token.jti, time: time::now() };
        RETURN $auth;
    }
    DURATION FOR TOKEN 30d, FOR SESSION 1h
;
```

## Token and session duration

_(since v3.2.0)_

Record-access authentication tokens are issued to end users and may be passed to third parties, so they **must** expire. As a result, `DURATION FOR TOKEN NONE` is rejected on `DEFINE ACCESS` and `ALTER ACCESS` for `TYPE RECORD` access methods, including when `NONE` would be the result of clearing the duration with `ALTER ACCESS … DURATION FOR TOKEN NONE`.

For record access, be sure to use a finite `DURATION FOR TOKEN` (for example `15m` or `1h`) and keep session duration separate via `FOR SESSION`.

## Using `IF NOT EXISTS` clause

The `IF NOT EXISTS` clause can be used to define an access method of type RECORD only if it does not already exist. You should use the `IF NOT EXISTS` clause when defining an access method in SurrealDB if you want to ensure that the access method is only created if it does not already exist. If the access method already exists, the `DEFINE ACCESS` statement will return an error.

It's particularly useful when you want to safely attempt to define an access method without manually checking its existence first.

```surql
-- Create a RECORD access method for the example database if it does not already exist
DEFINE ACCESS IF NOT EXISTS example ON DATABASE TYPE RECORD;
```

## Using `OVERWRITE` clause

The `OVERWRITE` clause can be used to define an access method of type RECORD and overwrite an existing one if it already exists. You should use the `OVERWRITE` clause when you want to modify an existing access method definition. If the access method already exists, the `DEFINE ACCESS` statement will overwrite the existing access method definition with the new one.

```surql
-- Create a RECORD access method for the example database and overwrite if it already exists
DEFINE ACCESS OVERWRITE example ON DATABASE TYPE RECORD;
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/analyzer

# DEFINE ANALYZER

In the context of a database, an analyzer plays a crucial role in text processing and searching. It is defined by its name, a set of tokenizers, and a collection of filters.

> [!NOTE]
> Before SurrealDB version 3.0.0, the `FULLTEXT ANALYZER` clause used the syntax `SEARCH ANALYZER`.

In the context of a database, an analyzer processes text so that it can be searched. It is defined by its name, a set of tokenizers, and a collection of filters.

The output of an analyzer can be experimented with by using the [`search::analyze()`](/docs/reference/query-language/functions/database-functions/search.md#searchanalyze) function.

## Requirements
- You must be authenticated as a root, namespace, or database user before you can use the `DEFINE ANALYZER` statement.
- [You must select your namespace and database](/docs/reference/query-language/statements/use.md) before you can use the `DEFINE ANALYZER` statement.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
DEFINE ANALYZER [ OVERWRITE | IF NOT EXISTS ] @name [ FUNCTION 
  @function ] [ TOKENIZERS @tokenizers ] [ FILTERS @filters ] [ 
  COMMENT @string ]
```

## The `FUNCTION` clause

The `FUNCTION` clause runs a preprocessing step on the initial input before tokenizers and filters run. The reference must be a **function path** (not a call - omit parentheses), and the function must take and return a `string`.

You can use either:

* a [`fn::`](/docs/reference/query-language/statements/define/function.md) user-defined function defined with `DEFINE FUNCTION`, or
* an [`ext::`](/docs/reference/query-language/statements/define/extension.md) function from a SurrealDB [extension](/docs/learn/extensions/plugins/overview.md) defined with `DEFINE EXTENSION` (requires the [`surrealism` experimental capability](/docs/reference/cli/db/commands/start.md#experimental-capabilities)).

```surql
DEFINE FUNCTION fn::backwardsify($input: string) -> string {
    $input.split('').fold('', |$a, $b| $b + $a);
};

DEFINE ANALYZER backwards FUNCTION fn::backwardsify TOKENIZERS blank;

search::analyze("backwards", "I like SurrealDB");
```

```surql title="Output"
[
	'BDlaerruS',
	'ekil',
	'I'
]
```

A SurrealDB extension function works the same way once the extension is defined. Unlike other stored definitions, an analyzer that calls `ext::` can still be read by SurrealDB 3.x:

```surql notest
DEFINE ANALYZER custom FUNCTION ext::demo::alter_string TOKENIZERS class;
```

## Tokenizers

Tokenizers are responsible for breaking down a given text into individual tokens based on a set of instructions. There are a couple of tokenizers that can be used while defining an analyzer as seen below:

### `blank`

The blank tokenizer breaks down a text into tokens by creating a new token each time it encounters a space, tab, or newline character. It's a straightforward way to split text into words or chunks based on whitespace.

```surql
DEFINE ANALYZER example_blank TOKENIZERS blank;
search::analyze("example_blank", "hello world");
```

```surql title="Output"
[
	'hello',
	'world'
]
```

### `camel`

The camel tokenizer is used for identifying and creating tokens when the next character in the text is uppercase. This is particularly useful for processing camelCase or PascalCase text, common in programming, to split them into meaningful words.

```surql
DEFINE ANALYZER example_camel TOKENIZERS camel;
search::analyze("example_camel", "helloWorld");
```

```surql title="Output"
[
	'hello',
	'World'
]
```

### `class`

The class tokenizer segments text into tokens by detecting changes (digit, letter, punctuation, blank) in the Unicode class of characters. It creates a new token when the character class changes, distinguishing between digits, letters, punctuation, and blanks. This allows for flexible tokenization based on character types.

```surql
DEFINE ANALYZER example_class TOKENIZERS class;
search::analyze("example_class", "123abc!XYZ");
```

```surql title="Output"
[
	'123',
	'abc',
	'!',
	'XYZ'
]
```

### `punct`

The punct tokenizer generates tokens by breaking the text whenever a punctuation character is encountered. It's suitable for tokenizing sentences or breaking text into smaller units based on punctuation marks.

```surql
DEFINE ANALYZER example_punct TOKENIZERS punct;
search::analyze("example_punct", "Hello, World!");
```

```surql title="Output"
[
	'Hello',
	',',
	' World',
	'!'
]
```

### `segment(language)` {#segmentlanguage}

_(since v3.3.0)_

The segment tokenizer splits text into words using a morphological dictionary, for languages the tokenizers above cannot split correctly.

Those tokenizers decide every boundary from the characters around it, which works for languages that separate words with spaces or case changes. Chinese and Japanese write a whole clause with no separator at all, so `blank`, `class`, `camel` and `punct` all reduce one to a single token. Korean does use spaces, but attaches grammatical particles to the word they follow, so `한국어를` ("Korean" + object marker) stays whole and a search for `한국어` never matches it.

`segment` takes one of `chinese`, `japanese` or `korean`:

```surql
DEFINE ANALYZER example_korean TOKENIZERS blank,segment(korean);
search::analyze("example_korean", "한국어를 배우고 있습니다");
```

```surql title="Output"
[
	'한국어',
	'를',
	'배우',
	'고',
	'있',
	'습니다'
]
```

The noun `한국어` ("Korean") is now its own token, so it matches independently of the particle attached to it.

Korean written with Hanja is handled as well as Hangul, which matters for older newspapers, legal text and academic writing. The Hanja words are in the dictionary, and a Hangul particle attached to a Hanja stem separates from it:

```surql
-- Setup from the example above
DEFINE ANALYZER example_korean TOKENIZERS blank,segment(korean);

DEFINE ANALYZER example_plain TOKENIZERS blank,class;
search::analyze("example_plain", "政府는 昨日 臨時國務會議를 召集하고");
search::analyze("example_korean", "政府는 昨日 臨時國務會議를 召集하고");
```

```surql title="Output"
[
	'政府는',
	'昨日',
	'臨時國務會議를',
	'召集하고'
]

[
	'政府',
	'는',
	'昨日',
	'臨時',
	'國務',
	'會議',
	'를',
	'召集',
	'하',
	'고'
]
```

`政府` and `會議` separate from the particles that follow them, and `臨時國務會議` separates into the three words it is built from, so each is searchable on its own.

The dictionary covers modern standard Korean. Archaic Hangul written with the old jamo, including the arae-a (`ㆍ`) still used for Jeju, has no entries and is returned whole:

```surql
-- Setup from the example above
DEFINE ANALYZER example_korean TOKENIZERS blank,segment(korean);

search::analyze("example_korean", "ᄒᆞᆫ");
```

```surql title="Output"
[
	'ᄒᆞᆫ'
]
```

Such text is not separated into words, though a boundary between an archaic sequence and a modern syllable is still found, because the two are written with different Unicode blocks:

```surql
-- Setup from the example above
DEFINE ANALYZER example_korean TOKENIZERS blank,segment(korean);

search::analyze("example_korean", "한ᄒᆞᆫ글");
```

```surql title="Output"
[
	'한',
	'ᄒᆞᆫ글'
]
```

A longer sentence shows how much is at stake. Without `segment`, the space-separated tokenizers keep every word joined to the particle that follows it:

```surql
DEFINE ANALYZER example_spaces TOKENIZERS blank,class;
search::analyze("example_spaces", "서울에서 부산까지 기차를 타고 갑니다");
```

```surql title="Output"
[
	'서울에서',
	'부산까지',
	'기차를',
	'타고',
	'갑니다'
]
```

Neither `서울` nor `부산` is a token, so neither city can be searched for. `segment(korean)` separates each noun from its particle:

```surql
-- Setup from the example above
DEFINE ANALYZER example_korean TOKENIZERS blank,segment(korean);

search::analyze("example_korean", "서울에서 부산까지 기차를 타고 갑니다");
```

```surql title="Output"
[
	'서울',
	'에서',
	'부산',
	'까지',
	'기차',
	'를',
	'타',
	'고',
	'갑니다'
]
```

Japanese (with the small exception of spaced kana-only text for children or language learners) and Chinese need no other tokenizer, since there are no spaces to split on first:

```surql
DEFINE ANALYZER example_japanese TOKENIZERS segment(japanese);
search::analyze("example_japanese", "東京都に住んでいます");
```

```surql title="Output"
[
	'東京',
	'都',
	'に',
	'住ん',
	'で',
	'い',
	'ます'
]
```

Longer text separates in the same way, including place names written as compounds:

```surql
-- Setup from the example above
DEFINE ANALYZER example_japanese TOKENIZERS segment(japanese);

search::analyze("example_japanese", "京都駅から大阪駅まで電車で行きます");
```

```surql title="Output"
[
	'京都',
	'駅',
	'から',
	'大阪',
	'駅',
	'まで',
	'電車',
	'で',
	'行き',
	'ます'
]
```

`京都駅` separates into the city and the station, so a search for `京都` reaches this text.

One dictionary is used per language, but the search over it is the same for all three, so Japanese and Korean separate along the same joins. The sentence above and its Korean translation come apart morpheme for morpheme:

```surql
DEFINE ANALYZER example_korean TOKENIZERS blank,segment(korean);
search::analyze("example_korean", "도쿄도에 살고 있습니다");
```

```surql title="Output"
[
	'도쿄',
	'도',
	'에',
	'살',
	'고',
	'있',
	'습니다'
]
```

| Japanese | Korean | |
| --- | --- | --- |
| `東京` | `도쿄` | Tokyo |
| `都` | `도` | metropolis |
| `に` | `에` | location |
| `住ん` | `살` | live |
| `で` | `고` | joins the two verbs |
| `い` | `있` | continuing state |
| `ます` | `습니다` | polite ending |

Both languages attach grammatical endings to a stem, and the segmenter separates each ending into a token of its own. That is why a search for the stem alone finds either sentence.

The Japanese dictionary is modern, so older kana is not separated reliably. The kana iteration mark `ゝ`, which stands for a repeat of the kana before it, has no entry of its own and breaks the word it sits in:

```surql
-- Setup from the example above
DEFINE ANALYZER example_japanese TOKENIZERS segment(japanese);

search::analyze("example_japanese", "こころ");
search::analyze("example_japanese", "こゝろ");
```

```surql title="Output"
[
	'こころ'
]

[
	'こ',
	'ゝ',
	'ろ'
]
```

Both spell the same word. Pre-1946 spellings, the obsolete kana `ゐ` and `ゑ`, and hentaigana vary in the same way: each is returned whole where nothing matches it, and broken into single kana where the pieces happen to match something else. The kanji iteration mark `々` is not affected, because words written with it, such as `人々` and `時々`, are entries in their own right.

**Simplified**

```surql
DEFINE ANALYZER example_chinese TOKENIZERS segment(chinese);
search::analyze("example_chinese", "我喜欢数据库");
```

```surql title="Output"
[
	'我',
	'喜欢',
	'数据库'
]
```

**Traditional**

```surql
DEFINE ANALYZER example_chinese TOKENIZERS segment(chinese);
search::analyze("example_chinese", "我喜歡數據庫");
```

```surql title="Output"
[
	'我',
	'喜歡',
	'數據庫'
]
```

The dictionary holds both writings, so either segments correctly on its own.

Japanese text read with `segment(chinese)` partly works, which can be misleading. Characters Japanese shares with Chinese are found, and Japanese-only forms fall out as single characters because no dictionary entry contains them. Chinese writes ice as `冰` in both Simplified and Traditional, where Japanese writes `氷`:

```surql
-- Setup from the example above
DEFINE ANALYZER example_chinese TOKENIZERS segment(chinese);

search::analyze("example_chinese", "冰水");
search::analyze("example_chinese", "氷水");
```

```surql title="Output"
[
	'冰水'
]

[
	'氷',
	'水'
]
```

Both mean iced water, and `氷水` is a single word to `segment(japanese)`.

Over a longer phrase the effect is uneven, which is what makes it hard to notice. Here the words Chinese shares are recovered and the ones holding a Japanese-only character are not:

```surql
-- Setup from the examples above
DEFINE ANALYZER example_japanese TOKENIZERS segment(japanese);
DEFINE ANALYZER example_chinese TOKENIZERS segment(chinese);

search::analyze("example_japanese", "北海道氷河時代地図");
search::analyze("example_chinese", "北海道氷河時代地図");
```

```surql title="Output"
[
	'北海道',
	'氷河',
	'時代',
	'地図'
]

[
	'北海道',
	'氷',
	'河',
	'時代',
	'地',
	'図'
]
```

`北海道` and `時代` are written the same way in both languages and survive. `氷河` and `地図` do not, because Chinese writes those characters as `冰` and `圖`, so neither compound is in the dictionary and each falls apart. Half the phrase is still searchable, which is why the wrong dictionary can pass a quick check. Use the dictionary for the language the text is written in.

Chinese has no counterpart to that hiragana exception, and the reason is the reverse of what it suggests. Japanese marks its word boundaries by changing script: kanji write the content words and hiragana the grammar around them, so the switch from one to the other often shows where a word ends. Text written only in hiragana loses that and has to be spaced instead. Chinese never had it, because everything is written in one script, so there is nothing to take away. A Chinese reader separates the words by knowing them, which is the same thing the dictionary does here. Text for learners therefore annotates the characters rather than spacing them: zhuyin in Taiwan, pinyin in mainland China. Pinyin is written word by word, so `blank` already separates it and `segment` has nothing to add. Where both are available, the two agree on ordinary prose: `我在图书馆学习数据库设计` segments into the same six words that pinyin writes as `Wǒ zài túshūguǎn xuéxí shùjùkù shèjì`.

They part company on the names of things. Pinyin writes the parts of a proper name separately, while the dictionary holds the whole name as one entry:

| | `segment(chinese)` | pinyin |
| --- | --- | --- |
| `北京大学` | `北京大学` | `Běijīng Dàxué` |
| `中华人民共和国` | `中华人民共和国` | `Zhōnghuá Rénmín Gònghéguó` |

A search for `北京` therefore does not reach a document containing `北京大学`. Index the shorter name as well where both should match. Zhuyin is not in the dictionary, so a run of it is returned whole:

```surql
-- Setup from the example above
DEFINE ANALYZER example_chinese TOKENIZERS segment(chinese);

search::analyze("example_chinese", "ㄋㄧˇㄏㄠˇ");
```

```surql title="Output"
[
	'ㄋㄧˇㄏㄠˇ'
]
```

Text stored as zhuyin is therefore not searchable a word at a time. Spacing it does not recover the words either, because zhuyin is written one group per syllable while a word may be several syllables long. `数据库` is one word of three:

```surql
-- Setup from the example above
DEFINE ANALYZER example_chinese TOKENIZERS segment(chinese);

search::analyze("example_chinese", "ㄕㄨˋ ㄐㄩˋ ㄎㄨˋ");
```

```surql title="Output"
[
	'ㄕㄨˋ',
	'ㄐㄩˋ',
	'ㄎㄨˋ'
]
```

Word boundaries are decided by the dictionary rather than by character count, so words of one, two and three characters separate from each other in the same sentence:

**Simplified**

```surql
-- Setup from the example above
DEFINE ANALYZER example_chinese TOKENIZERS segment(chinese);

search::analyze("example_chinese", "我在图书馆学习数据库设计");
```

```surql title="Output"
[
	'我',
	'在',
	'图书馆',
	'学习',
	'数据库',
	'设计'
]
```

**Traditional**

```surql
-- Setup from the example above
DEFINE ANALYZER example_chinese TOKENIZERS segment(chinese);

search::analyze("example_chinese", "我在圖書館學習數據庫設計");
```

```surql title="Output"
[
	'我',
	'在',
	'圖書館',
	'學習',
	'數據庫',
	'設計'
]
```

An analyzer may declare at most one `segment`. It runs after the other tokenizers, splitting the pieces they produced, so combining it with `blank` or `class` is useful for text that mixes scripts.

#### Dictionaries

Each language is segmented with its own dictionary. A dictionary holds the words of one language rather than the characters of one script, which matters because Han characters are used to write several languages. `segment(chinese)` knows Chinese words, not Han characters in general, so text in another language that borrows the script is read as though it were Chinese.

Historical Vietnamese, written in Chữ Nôm, shows what that produces. Characters borrowed from Chinese are found, because they are Chinese words, while characters invented for Vietnamese have no entries and run together:

```surql
-- Setup from the example above
DEFINE ANALYZER example_chinese TOKENIZERS segment(chinese);

search::analyze("example_chinese", "越南");
search::analyze("example_chinese", "𠬠𠊛");
```

```surql title="Output"
[
	'越南'
]

[
	'𠬠𠊛'
]
```

The first is found as the Chinese word for Vietnam. The second is two Vietnamese words, `một người` ("one person"), returned as a single token. Spacing would not recover them either: Vietnamese separates syllables rather than words, so `blank` would give syllables in the same way it does for pinyin.

A dictionary covers the character forms it was built from. The Chinese dictionary holds both Simplified and Traditional writings, so each segments correctly, but it treats them as separate words rather than folding one into the other:

```surql
-- Setup from the example above
DEFINE ANALYZER example_chinese TOKENIZERS segment(chinese);

search::analyze("example_chinese", "一样");
search::analyze("example_chinese", "一樣");
```

```surql title="Output"
[
	'一样'
]

[
	'一樣'
]
```

Both are the same word, and both produce a single token, but the tokens differ. Mixing the two writings in one piece of text is safe as long as each word is written consistently, because every word is looked up in the form it appears in. A word that mixes them internally matches nothing and falls back to single characters:

```surql
-- Setup from the example above
DEFINE ANALYZER example_chinese TOKENIZERS segment(chinese);

search::analyze("example_chinese", "数據库");
```

```surql title="Output"
[
	'数',
	'據',
	'库'
]
```

`数据库` and `數據庫` are both in the dictionary; the half-converted `数據库` is not. This matters where text has been through an unreliable converter, because the result still reads correctly and only the tokens show the problem. A document indexed in Traditional characters is therefore not matched by a Simplified query, or the reverse. Where a collection mixes the two, convert to one form before indexing and convert queries the same way. The same applies to Japanese text written with older character forms.

**The released binaries carry all three**, so `segment` works with nothing on disk and no configuration. That covers the downloads from [install.surrealdb.com](https://install.surrealdb.com), the Homebrew formula and the official Docker images, which package those same binaries. The dictionaries are the reason those downloads are substantially larger than they would otherwise be.

**Replacing them from disk** is for the cases the shipped dictionaries do not cover: a custom or updated dictionary, or a build made without them. Set `SURREAL_SEGMENT_DICTIONARY_PATH` to a directory holding one subdirectory per language. The names are fixed, and each is the language it serves rather than the dictionary behind it: `korean`, `japanese`, `chinese`. Only the languages you use need to be present:

**Bash**

```bash
# /opt/surreal/dicts needs a subdirectory only for the languages it replaces;
# the rest keep using the dictionaries built into the binary
SURREAL_SEGMENT_DICTIONARY_PATH="/opt/surreal/dicts" \
  surreal db start --user root --pass secret
```

**PowerShell**

```powershell
$env:SURREAL_SEGMENT_DICTIONARY_PATH = "C:\surreal\dicts"
surreal db start --user root --pass secret
```

The directory overrides the built-in dictionary for each language it carries, and leaves the rest alone. A directory holding only `korean` therefore replaces Korean while Japanese and Chinese keep using the dictionaries in the binary.

Only an absent dictionary falls back that way. A dictionary that is present but cannot be read, and a directory named by `SURREAL_SEGMENT_DICTIONARY_PATH` that is not there at all, are errors rather than a silent fall back to the built-in one, so a misconfigured path is reported instead of quietly segmenting with something other than what you named.

Not every build embeds the dictionaries. Builds from source do not unless the `cjk` feature is enabled, and neither does the WebAssembly package, which could not carry them. If the dictionary for a language can be found neither way, the `DEFINE ANALYZER` statement naming it fails, rather than being accepted and silently indexing unsegmented text.

## Filters

Filters take on the task of transforming these tokens for further processing and analysis.

### `ascii`

The ascii filter is responsible for processing tokens by replacing or removing diacritical marks (accents and special characters) from the text. It helps standardize text by converting accented characters to their basic ASCII equivalents, making it more suitable for various text analysis tasks.

```surql
DEFINE ANALYZER example_ascii TOKENIZERS class FILTERS ascii;
search::analyze("example_ascii", "résumé café");
```

```surql title="Output"
[
	'resume',
	'cafe'
]
```

### `lowercase`

The lowercase filter converts tokens to lowercase, ensuring that text is consistently in lowercase format. This is often used to make text case-insensitive for search and analysis purposes.

```surql
DEFINE ANALYZER example_lowercase TOKENIZERS class FILTERS lowercase;
search::analyze("example_lowercase", "Hello World");
```

```surql title="Output"
[
	'hello',
	'world'
]
```

### `uppercase`

The uppercase filter converts tokens to uppercase, ensuring text consistency in uppercase format. It can be useful when case-insensitivity is required for specific analysis or search operations.

For example, if you had the text **"Hello World"**, the uppercase filter would create two tokens, **["HELLO", "WORLD"]**. Below is an example of how to use the uppercase filter:

```surql
DEFINE ANALYZER example_uppercase TOKENIZERS class FILTERS uppercase;
search::analyze("example_uppercase", "Hello World");
```

```surql title="Output"
[
	'HELLO',
	'WORLD'
]
```

### `edgengram(min,max)`

The edgengram filter is used to create tokens that represent prefixes of terms. It generates a sequence of tokens that gradually build up a term, which can be useful for autocomplete or searching based on partial words. It accepts two parameters `min` and `max` which define the minimum and maximum amount of characters in the prefix. A `max` above 64 is treated as 64, and a `min` of 0 as 1.

For example, if you had the text **"apple banana"**, the edgengram filter would create six tokens, **["a", "ap", "app", "b", "ba", "ban"]**. Below is an example of how to use the edgengram filter:

```surql
DEFINE ANALYZER example_edgengram TOKENIZERS class FILTERS
  edgengram(1,3);
search::analyze("example_edgengram", "apple banana");
```

```text
[
	'a',
	'ap',
	'app',
	'b',
	'ba',
	'ban'
]
```

### `mapper(path)` {#mapperpath}

The mapping filter is designed to enable lemmatization within SurrealDB.

Lemmatization is the process of reducing words to their base or dictionary form. The mapper mechanism allows users to specify a custom dictionary file that maps terms to their base forms. This dictionary file is then used by SurrealDB’s analyzer to standardize terms as they are indexed, improving search consistency.

This is particularly useful for handling irregular verbs and other terms that the default "snowball" filter cannot handle. Lemmatization files are easy to put together and to find online, making it possible to customise full-text search for smaller languages.

#### Filesystem allowlist

A `DEFINE ANALYZER` statement with `mapper('<path>')` opens the dictionary file on the **host filesystem** when the analyzer is defined. Access is gated by [`SURREAL_FILE_ALLOWLIST`](/docs/reference/cli/db/environment-variables.md#file-config), without which no paths are permitted. Set one or more directories before using `mapper()`:

**Bash**

```bash
# Colon-separated directories
SURREAL_FILE_ALLOWLIST="/var/surreal/dicts:/opt/wordlists" surreal db start --user root --pass secret
```

**PowerShell**

```powershell
# Semicolon-separated directories
$env:SURREAL_FILE_ALLOWLIST = "C:\dicts;D:\wordlists"
surreal db start --user root --pass secret
```

The path in `mapper()` must resolve to a file **under** an allowed directory. Paths outside the allowlist are rejected at `DEFINE ANALYZER` time.

> [!NOTE]
> This allowlist is for analyzer dictionary files only. The experimental [files](/docs/learn/schema-management/files/buckets.md) feature uses [`SURREAL_BUCKET_FOLDER_ALLOWLIST`](/docs/reference/cli/db/environment-variables.md#file-config) instead.

How does the mapper work?

Configuration: In the SQL statement below, the mapper parameter is specified within the analyzer definition. This parameter points to the file that contains the term mappings for lemmatization.

```surql
DEFINE ANALYZER lemme_english TOKENIZERS blank,class FILTERS
  lowercase,mapper( '../tests/data/lemmatization-en.txt' );

RETURN [
    search::analyze("lemme_english", "He drove and swam"),
];
```

```surql title="Output"
[
	[
		'he',
		'drive',
		'and',
		'swim'
	]
]
```

Dictionary File Structure: The file specified in the mapper parameter must follow this format:

- Each line contains a pair of terms separated by a tab.
- The first term represents the canonical (base form) of the word.
- The second term is the form to be mapped to this base form.

Example file format:

```text
drive	driven
drive	drives
drive	driving
drive	drove
swim	swam
swim	swimming
swim	swims
swim	swum
```

Usage: When this analyzer is applied to a text, any word that matches the mapped term in the dictionary file will be replaced by its base form before indexing. This helps ensure consistency in search results by consolidating different forms of a word to a single, standardized entry.

By using this custom dictionary-based mapper, you can control how irregular forms and other variations of terms are indexed, making search behaviour more predictable and comprehensive.

The following example shows how lemmatization can be used to generate a list of words and their respective frequencies. Other notable functionalities in the example are the [`string::is_alpha()`](/docs/reference/query-language/functions/database-functions/string.md#stringis_alpha) function inside [`array::filter()`](/docs/reference/query-language/functions/database-functions/array.md#arrayfilter) to remove all non-alphabetic strings, the [`type::record()`](/docs/reference/query-language/functions/database-functions/type.md#typerecord) function to construct a record ID from two strings, and an [`UPSERT`](/docs/reference/query-language/statements/upsert.md) statement to create a record if one does not exist, or update it otherwise.

```surql
DEFINE ANALYZER lemme_english TOKENIZERS blank,class FILTERS
  lowercase,mapper( '../tests/data/lemmatization-en.txt' );

LET $text = "The Wheel of Time turns,
  and Ages come and pass,
  leaving memories that become legend. Legend fades to myth,
  and even myth is long forgotten when the Age that gave it birth comes again. In one Age,
  called the Third Age by some,
  an Age yet to come,
  an Age long past,
  a wind rose in the Mountains of Mist. The wind was not the beginning. There are neither beginnings nor endings to the turning of the Wheel of Time. But it was a beginning.";

LET $words = search::analyze("lemme_english", $text)
    .filter(|$c| $c.is_alpha());
FOR $word IN $words {
    UPSERT type::record("word", $word) SET frequency += 1;
};

SELECT * FROM word WHERE frequency >=3 ORDER BY frequency DESC;
```

```surql title="Output"
[
	{
		frequency: 8,
		id: word:the
	},
	{
		frequency: 6,
		id: word:age
	},
	{
		frequency: 4,
		id: word:a
	},
	{
		frequency: 4,
		id: word:be
	},
	{
		frequency: 4,
		id: word:of
	},
	{
		frequency: 3,
		id: word:and
	},
	{
		frequency: 3,
		id: word:come
	},
	{
		frequency: 3,
		id: word:to
	}
]
```

A mapper can also be used for ad-hoc filtering, as long as the file referenced contains two single words separated by a tab. Take the following file for example:

```title="error_filter.txt"
NOT_FOUND	File_not_found
NOT_FOUND	Datei_nicht_gefunden
NOT_FOUND	Fichier_non_trouvé
TIMEOUT	Timed_out
TIMEOUT	Délai_expiré
TIMEOUT	Zeitüberschreitung
```

An analyzer that uses a single mapper filter can then use this lemmatizer to unify multilingual error messages into a single output.

```surql
DEFINE ANALYZER error_filter FILTERS mapper('error_filter.txt');

LET $messages = 
	["File not found", "Datei nicht gefunden", "Zeitüberschreitung"]
	.map(|$word| $word.replace(' ', '_'))
	.join(' ');
search::analyze("error_filter", $messages);
```

```surql title="Output"
[
	'NOT_FOUND',
	'NOT_FOUND',
	'TIMEOUT'
]
```

Example using the same mapper to search for errors in multiple languages:

```surql
DEFINE ANALYZER error_filter FILTERS mapper('error_filter.txt');
DEFINE INDEX OVERWRITE errors
  ON TABLE error FIELDS message FULLTEXT ANALYZER error_filter;

FOR $message IN ["File not found",
  "Datei nicht gefunden",
  "Zeitüberschreitung"] {
	CREATE error SET message = $message.replace(' ',
	  '_'),
	  at = time::now();
};

SELECT * FROM error WHERE message @@ "NOT_FOUND";
```

```surql title="Output"
[
	{
		at: d'2024-11-13T03:56:12.039252Z',
		id: error:acbc044syhnx54wzs3n9,
		message: 'File_not_found'
	},
	{
		at: d'2024-11-13T03:56:12.043643Z',
		id: error:5ifxic9s750x24ts4zof,
		message: 'Datei_nicht_gefunden'
	}
]
```

### `ngram(min,max)`

The ngram filter is used to create a sequence of 'n' tokens from a given sample of text or speech. These items can be syllables, letters, words or base pairs according to the application. It accepts two parameters `min` and `max` which indicates that you want to create n-grams starting from min to size of max. A `max` above 64 is treated as 64, and a `min` of 0 as 1.

```surql
DEFINE ANALYZER example_ngram TOKENIZERS class FILTERS ngram(1,3);
search::analyze("example_ngram", "apple banana");
```

```surql title="Output"
[
	'a',
	'ap',
	'app',
	'p',
	'pp',
	'ppl',
	'p',
	'pl',
	'ple',
	'l',
	'le',
	'e',
	'b',
	'ba',
	'ban',
	'a',
	'an',
	'ana',
	'n',
	'na',
	'nan',
	'a',
	'an',
	'ana',
	'n',
	'na',
	'a'
]
```

When a full-text query is analyzed with an `ngram` filter, each word of the query is matched as follows:

- a word with a length from `min` to `max` matches as itself;
- a word longer than `max` matches a record only when the record holds every n-gram of length `max` in the word;
- a word shorter than `min` matches nothing.

With `ngram(2,2)`, a record holding `abcdefgh` matches the query `'abc'`, because it holds both `ab` and `bc`, and does not match `'abcx'`, because it does not hold `cx`:

```surql
DEFINE ANALYZER ng TOKENIZERS blank FILTERS lowercase, ngram(2,2);
DEFINE INDEX iq ON q FIELDS body FULLTEXT ANALYZER ng BM25;
CREATE q:1 SET body = 'abcdefgh';
CREATE q:2 SET body = 'xbcdyz';
SELECT id FROM q WHERE body @1@ 'abc';
```

```surql title="Output"
[{ id: q:1 }]
```

### `snowball(language)`

The snowball filter applies Snowball stemming to tokens, reducing them to their root form and converts the case to lowercase. The following supported languages can be passed as a parameter in snowball: Arabic, Danish, Dutch, English, French, German, Greek, Hungarian, Italian, Norwegian, Portuguese, Romanian, Russian, Spanish, Swedish, Tamil, Turkish.

```surql
DEFINE ANALYZER english_snowball TOKENIZERS class FILTERS
  snowball(english);
DEFINE ANALYZER german_snowball TOKENIZERS class FILTERS
  snowball(german);

RETURN [
    search::analyze("english_snowball",
      "Looking at some running cats"),
    search::analyze("german_snowball",
      "Sollen wir was trinken gehen?")
];
```

```surql title="Output"
[
	[
		'look',
		'at',
		'some',
		'run',
		'cat'
	],
	[
		'soll',
		'wir',
		'was',
		'trink',
		'geh',
		'?'
	]
]
```

## Using `IF NOT EXISTS` clause

The `IF NOT EXISTS` clause can be used to define an analyzer only if it does not already exist. You should use the `IF NOT EXISTS` clause when defining an analyzer in SurrealDB if you want to ensure that the analyzer is only created if it does not already exist. If the analyzer already exists, the statement does nothing and returns `NONE`, even when the new definition is different. Without the clause, defining an analyzer that already exists returns an error.

It's particularly useful when you want to safely attempt to define an analyzer without manually checking its existence first.

On the other hand, you should not use the `IF NOT EXISTS` clause when you want to ensure that the analyzer definition is updated regardless of whether it already exists. In such cases, you might prefer using the `OVERWRITE` clause, which allows you to define an analyzer and overwrite an existing one if it already exists, ensuring that the latest version of the analyzer definition is always in use.

```surql
-- Create an ANALYZER if it does not already exist
DEFINE ANALYZER IF NOT EXISTS example TOKENIZERS blank;
```

## Using `OVERWRITE` clause

The `OVERWRITE` clause can be used to create an analyzer and overwrite an existing one if it already exists. You should use the `OVERWRITE` clause when you want to modify an existing analyzer definition. If the analyzer already exists, the `DEFINE ANALYZER` statement will overwrite the existing analyzer definition with the new one.

```surql
-- Create an ANALYZER and overwrite if it already exists
DEFINE ANALYZER OVERWRITE example TOKENIZERS blank;
```

Changing an analyzer does not rebuild the indexes that use it. Records that were already indexed keep the tokens from the old analyzer, while new writes and queries use the new one, so a search can match or miss records that it should not. After changing an analyzer, run [`REBUILD INDEX`](/docs/reference/query-language/statements/rebuild.md) on each index that uses it, such as `REBUILD INDEX ft_body ON article`. From SurrealDB 4.0, defining the index again with `DEFINE INDEX OVERWRITE` and an unchanged definition keeps the existing index and its tokens, so `REBUILD INDEX` is the statement to use.

## More examples

Examples on application of analyzers to indexes can be found in the documentation on [`DEFINE INDEX`](/docs/reference/query-language/statements/define/indexes.md) statement

This example creates an analyzer that tokenizes text based on the class of characters and then applies the lowercase filter to the tokens.

```surql
-- Creates a simple analyzer removing diacritics marks
DEFINE ANALYZER ascii TOKENIZERS class FILTERS lowercase,ascii;
```

This example creates an analyzer specifically designed for processing English texts.

```surql
-- Creates an analyzer suitable for English text
DEFINE ANALYZER english TOKENIZERS class FILTERS snowball(english);
```

This example creates an analyzer specifically designed for auto-completion tasks.

```surql
-- Creates an analyzer suitable for auto-completion.
DEFINE ANALYZER autocomplete FILTERS lowercase,edgengram(2,10);
```

This example creates an analyzer specifically designed for source code analysis.

```surql
-- Creates an analyzer suitable for source code analysis.
DEFINE ANALYZER code TOKENIZERS class,camel FILTERS lowercase,ascii;
```

## Removing analyzers

[`REMOVE ANALYZER`](/docs/reference/query-language/statements/remove.md) fails while any full-text index still references the analyzer. Remove or redefine those indexes first, then remove the analyzer. `REMOVE ANALYZER IF EXISTS` does not bypass this check when the analyzer is still in use.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/api

# DEFINE API

A DEFINE API statement can be used to set endpoints with custom middleware and permissions.

_(since v3.0.0)_

The `DEFINE API` statements allows a custom endpoint to be created. Each endpoint created by a `DEFINE API` statement is located at the `/api/:namespace/:database/:endpoint_name` path. For example, an endpoint for the path `get_users` for the namespace `my_namespace` and database `my_database` will have the path `/api/my_namespace/my_database/get_users`.

The response is an object with a combination of the following properties:
* `status` - A valid HTTP status code.
* `body` - Any value.
* `headers` - An object of valid header key value pairs. The value of each pair must be a string.
* `context` - An object.

The handler runs to completion and the response goes back in one piece, so an endpoint cannot stream. It cannot send server-sent events, hold the connection open, or pass on the changes of a [live query](/docs/reference/query-language/statements/live-select.md). A client that needs changes as they happen starts a live query itself, which needs arbitrary queries to be allowed for that user: see [Arbitrary queries](/docs/learn/security/authorization/capabilities.md#arbitrary-queries).

A defined API has access to a preset parameter called [`$request`](/docs/reference/query-language/language-primitives/parameters.md#request) which contains the request sent by the caller of the endpoint. The $request parameter may contain values at the following fields: `body`, `headers`, `params`, `method`, `query`, and `context`.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
DEFINE API [ OVERWRITE | IF NOT EXISTS ] @endpoint
    [ FOR @HTTP_method, .. ]
    [ MIDDLEWARE @function, .. ]
    [ THEN { @value } ]
    [ PERMISSIONS [ NONE | FULL | @expression ] ]
    [ SECURITY DEFINER | SECURITY INVOKER ]
    [ COMMENT @string ]
```

`DEFINE API` is often used in conjunction with a [capabilities flag](/docs/learn/security/authorization/capabilities.md) or [environment variable](/docs/reference/cli/db/environment-variables.md) to disable arbitrary queries, thereby forcing record and anonymous users to interact with the database via API endpoints alone.

## Quick example

```surql title="Defining an API endpoint"
DEFINE API "/test"
    FOR get, post 
        MIDDLEWARE
            api::timeout(1s)
        THEN {
            {
                status: 200,
                body: {
                    request: $request.body,
                    response: "The server works"
                },
                headers: {
                    'last-modified': <string>time::now(),
                    'expires': <string>(time::now() + 4d)
                }
            };
        };
```

An API endpoint can be tested using the [`api::invoke` function](/docs/reference/query-language/functions/database-functions/api.md), which takes either the path as a single string or the path along with a request body. It can also be tested via [CURL or other means by directly using the endpoint](/docs/reference/protocols/http-protocol.md) along with the namespace and database in the headers.

```surql
api::invoke("/test");

api::invoke("/test", {
    body: {
       hi: "please",
        give: "me",
        the: "information"
    }
});
```

```surql title="Example output"
-------- Query --------

{
	body: {
		request: NONE,
		response: 'The server works'
	},
	headers: {
		expires: '2026-10-18T04:51:11.128290Z',
		"last-modified": '2026-10-14T04:51:11.127573Z',
		"x-surreal-request-id": 'a93b6dcd-adc8-422a-8009-83edcedcbc39'
	},
	request_id: 'a93b6dcd-adc8-422a-8009-83edcedcbc39',
	status: 200
}

-------- Query --------

{
	body: {
		request: {
			give: 'me',
			hi: 'please',
			the: 'information'
		},
		response: 'The server works'
	},
	headers: {
		expires: '2026-10-18T04:51:11.129009Z',
		"last-modified": '2026-10-14T04:51:11.129008Z',
		"x-surreal-request-id": '2aae59a3-aa51-4aa3-bf50-a161332369bc'
	},
	request_id: '2aae59a3-aa51-4aa3-bf50-a161332369bc',
	status: 200
}
```

Each HTTP method may appear in at most one `FOR` clause on a `DEFINE API` statement. Overlapping methods - including duplicates inside a comma-separated list - are rejected at define time with a clear error instead of silently routing to only the first matching action.

```surql
DEFINE API "/foo"
  FOR get THEN $x
  FOR get THEN $y;
//- "The method 'get' is defined in more than one FOR clause on api '/foo'"
```

## API paths

The path of a `DEFINE API` statement can be static, such as `"/test"`, dynamic, or the remainder of a URL.

A dynamic path uses a `:` (colon) followed by a name, which will match on anything passed in at that section of a path.

```surql
DEFINE API OVERWRITE "/test/:anything_goes" FOR get THEN {
    RETURN {
        body: {
            some: "data"
        }
    }
};

api::invoke("/test/this_matches");
api::invoke("/test/same_here");
api::invoke("/test/but/this/wont/match");
```

The first two `api::invoke` calls return the body with a status of `200`. The third returns the response below with a status of `404`, as `:anything_goes` only applies to a single path segment.

```surql title="Example output"
{
	body: 'Not found',
	headers: {},
	request_id: '5dbef2f3-f643-4995-8545-fff364f78a96',
	status: 404
}
```

To match on the remainder of a URL, change the `:` (colon) to a `*` (star).

```surql
DEFINE API OVERWRITE "/test/*anything_goes" FOR get THEN {
    RETURN {
        body: {
            some: "data"
        }
    }
};

api::invoke("/test/this_matches");
api::invoke("/test/same_here");
api::invoke("/test/works/with/multiple/paths/now");
```

All three `api::invoke` calls now return the body with a status of `200`, such as the following.

```surql title="Example output"
{
	body: {
		some: 'data'
	},
	headers: {
		"x-surreal-request-id": 'ed05a73c-05e0-4b46-8ee9-19cab2098fa0'
	},
	request_id: 'ed05a73c-05e0-4b46-8ee9-19cab2098fa0',
	status: 200
}
```

### Typed segments and route order

A dynamic segment can name a type after its name, such as `:id<number>`. The segment then matches only a value that converts to the type, and `$request.params.id` holds the converted value: `/items/789` matches `"/items/:id<number>"` with `id` set to `789`, and `/items/abc` does not match it.

When more than one path matches a request, the most specific path runs. Each segment of a path adds to its score, and a fixed segment adds the most, then a typed dynamic segment, then an untyped dynamic segment, and a `*` remainder adds the least. The path with the highest score runs. With the following three definitions, `/users/me` runs the first, `/users/42` the second, and `/users/42/posts` the third:

```surql
DEFINE API "/users/me" FOR get THEN { { body: 'me' } };
DEFINE API "/users/:id<number>" FOR get THEN { { body: $request.params.id } };
DEFINE API "/users/*rest" FOR get THEN { { body: 'rest' } };
```

## Permissions

The `PERMISSIONS` clause decides who may call an endpoint, and can differ for each method. When it is left out, it is `PERMISSIONS FULL`, so anyone who can reach the server can call the endpoint, including a client that has not signed in, whether or not [guest access](/docs/learn/security/authorization/capabilities.md#guest-access) is allowed.

By default, the body runs without table and field permission checks, like the body of an [event](/docs/reference/query-language/statements/define/event.md#events-and-permissions), so it can read and write records that the caller cannot reach directly. This is the `SECURITY DEFINER` mode, which can be written out or left out. Inside the body, `$auth` is still the caller: a record user's record ID, or `NONE` for a client that has not signed in. In the example below, a record user cannot select from `secret_note`, but can read it through the endpoint, while a client without credentials is refused:

```surql
DEFINE TABLE secret_note PERMISSIONS NONE;

DEFINE API "/notes"
	FOR get
		PERMISSIONS WHERE $auth != NONE
		THEN {
			{ status: 200, body: <string> (SELECT VALUE text FROM secret_note) }
		};
```

> [!WARNING]
> Because the body of a `SECURITY DEFINER` endpoint is not limited by table permissions, the endpoint returns whatever its body selects to everyone its `PERMISSIONS` clause lets in. Set `PERMISSIONS` on every endpoint that reads or writes data, and check `$auth` in the body where different callers should see different records.

A `SECURITY DEFINER` endpoint is the opposite of a [defined function](/docs/reference/query-language/statements/define/function.md#permissions), whose body runs with the caller's permissions. A `SECURITY INVOKER` endpoint behaves like a function.

### Running the body with the caller's permissions

_(since v4.0.0)_

With `SECURITY INVOKER`, the body runs with the permissions of the caller, so its queries return the same records and fields that the caller gets from a direct query. The clause applies to the whole endpoint: every method, its `FOR any` handler and its middleware. The body never has more access than the user who defined the endpoint.

Both checks apply, one after the other. The endpoint's `PERMISSIONS` clause decides whether the caller may call the endpoint at all, and a caller it refuses gets a `403` before the body runs. Table and field permissions then limit what the body reads and writes. An endpoint with `PERMISSIONS FULL` therefore returns an empty array to a caller who cannot select from the table, and a table that allows the caller does not open an endpoint whose `PERMISSIONS` refuse them.

The endpoint below is the same as the one above, with `SECURITY INVOKER` added. A record user who calls it gets an empty array, because `secret_note` has `PERMISSIONS NONE`, while the `SECURITY DEFINER` endpoint above returns every note to the same user.

```surql
DEFINE API "/my-notes"
	FOR get
		PERMISSIONS WHERE $auth != NONE
		THEN {
			{ status: 200, body: <string> (SELECT VALUE text FROM secret_note) }
		}
	SECURITY INVOKER;
```

```text title="Output for a record user"
[]
```

`INFO FOR DB` and exports show `SECURITY INVOKER` after the methods of the definition, before any `COMMENT`, and leave the clause out for a `SECURITY DEFINER` endpoint. `DEFINE API OVERWRITE` without the clause returns the endpoint to `SECURITY DEFINER`. To change only the mode, use [`ALTER API`](/docs/reference/query-language/statements/alter/api.md), which keeps the current mode when the clause is left out:

```surql
-- Setup from the example above
DEFINE API "/my-notes"
	FOR get
		PERMISSIONS WHERE $auth != NONE
		THEN {
			{ status: 200, body: <string> (SELECT VALUE text FROM secret_note) }
		}
	SECURITY INVOKER;

ALTER API "/my-notes" SECURITY DEFINER;
```

## When a handler fails

_(since v4.0.0)_

A handler that fails answers with an error response, usually a `500`, and keeps none of what it wrote. Its records, its index entries and the writes of any events it set off are rolled back, while the rest of the transaction it ran in carries on. The same applies to each middleware call together with the part of the chain that it called.

```surql
DEFINE INDEX unique_v ON t FIELDS v UNIQUE;
CREATE t:0 SET v = 0;

DEFINE API "/two" FOR post THEN {
	INSERT INTO t [{ id: 1, v: 1 }, { id: 2, v: 0 }];
	{ status: 200 }
};

api::invoke("/two", { method: "post" }).status;
//- 500

SELECT id, v FROM t;
//- [{ id: t:0, v: 0 }]
```

The second record breaks the unique index, so the handler fails. Before 4.0, the response was the same but the first record stayed in the table, and so did the second one, which the index did not list.

## Custom middleware

Custom middleware can be used in addition to the functions listed above.

A custom middleware function is defined in the same way as any other [user-defined function](/docs/reference/query-language/statements/define/function.md).

Each such function automatically receives two arguments:

* An object that will contain the user request.
* A function (a closure) that can be called to get the current state of the response to be returned.

The parameter names `$req` for the first and `$next` for the second are commonly used, though the actual parameter names are of no consequence.

The output of such a function must be an `object`. This is used to pass the response on to the next middleware function, or on to the actual response if there is no middleware left to call.

```surql
DEFINE FUNCTION fn::middleware_function($req: object,
  $next: function) -> object {};
```

These functions can take additional arguments on top of the required two.

```surql
DEFINE FUNCTION fn::middleware_function($req: object,
  $next: function,
  $some_string: string) -> object {};
```

### Custom middleware examples

Here is an example of an API endpoint without any middleware.

```surql
DEFINE API "/custom_response"
    FOR get
        THEN {
            {
                status: 200,
                body: {
                    num: 1
                }
            };
        };
```

Calling `api::invoke("/custom_response")` will return the following.

```surql title="Example output"
{
	body: {
		num: 1
	},
	headers: {
		"x-surreal-request-id": '90ecf16c-d3d5-4a06-825f-c54c5af5afbf'
	},
	request_id: '90ecf16c-d3d5-4a06-825f-c54c5af5afbf',
	status: 200
}
```

The next example adds a middleware function that does the following:

* Calls the `$next` closure on the `$req` object. This will return the value after `THEN`: the original return value.
* Returns an object in which the `num` field inside `body` is increased by one.

```surql
DEFINE FUNCTION fn::increment_num($req: object,
  $next: function) -> object {
    LET $res = $next($req);
    $res + { body: { num: $res.body.num + 1 } }
};

DEFINE API "/custom_response"
    FOR get
        MIDDLEWARE
            fn::increment_num()
        THEN {
            {
                status: 200,
                body: {
                    num: 1
                }
            };
        };
```

Calling `api::invoke("/custom_response")` will now return a modified output in which `num` is equal to 2.

```surql title="Example output"
{
	body: {
		num: 2
	},
	headers: {
		"x-surreal-request-id": 'a4fa9a57-f1ac-4eb1-8433-cce37a19a5e0'
	},
	request_id: 'a4fa9a57-f1ac-4eb1-8433-cce37a19a5e0',
	status: 200
}
```

Here is an example of the same endpoint with an extra custom middleware function which adds an `x-called-at` header to the response to show when the API endpoint was called.

```surql
DEFINE FUNCTION fn::start_timer($req: object,
  $next: function,
  $called_at: datetime) -> object {
    LET $res = $next($req);
    $res + { headers: { "x-called-at": <string>$called_at } }
};

DEFINE FUNCTION fn::increment_num($req: object,
  $next: function) -> object {
    LET $res = $next($req);
    $res + { body: { num: $res.body.num + 1 } }
};

DEFINE API "/custom_response"
    FOR get
        MIDDLEWARE
            fn::start_timer(time::now()),
            fn::increment_num()
        THEN {
            {
                status: 200,
                body: {
                    num: 1
                }
            };
        };

api::invoke("/custom_response");
```

The output will look something like this.

```surql title="Example output"
{
	body: {
		num: 2
	},
	headers: {
		"x-called-at": '2026-10-14T04:51:23.959554Z',
		"x-surreal-request-id": 'ba447d57-24e6-4cf4-9e8b-68076b040980'
	},
	request_id: 'ba447d57-24e6-4cf4-9e8b-68076b040980',
	status: 200
}
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/bucket

# DEFINE BUCKET

The DEFINE BUCKET statement defines a named file bucket backed by memory, a local folder, or Amazon S3, S3-compatible, Google Cloud Storage or Azure Blob Storage object storage, with permissions.

_(since v3.0.0)_

The `DEFINE BUCKET` statement lets you create a bucket that can hold files.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
DEFINE BUCKET [ OVERWRITE | IF NOT EXISTS ] @name
  [ ON [ ROOT | NAMESPACE | DATABASE ] ]
  BACKEND @string
  [ READONLY ]
  [ PERMISSIONS @expression ]
  [ COMMENT @string ]
```

## Example usage

A bucket backend can be set as "memory" for non-persistent in-memory storage, as "file:/" followed by the path for storage on disk, or as an object storage URL for Amazon S3, an S3-compatible service, Google Cloud Storage or Azure Blob Storage.

### Memory backend

The simplest way to experiment with a bucket for files is by using the memory backend:

```surql
DEFINE BUCKET my_bucket BACKEND "memory";
```

Once this is defined, `my_bucket` can be accessed by using a file pointer: a path prefixed by an `f`.

```surql
-- Setup from the example above
DEFINE BUCKET my_bucket BACKEND "memory";

-- Create a file by adding some content
f"my_bucket:/my_book.txt".put("Once there were four children whose names were Peter, Susan, Edmund, and Lucy.");
-- Copy it to a new file name
f"my_bucket:/my_book.txt".copy("lion_witch_wardrobe.txt");
-- Read the file as bytes
f"my_bucket:/lion_witch_wardrobe.txt".get();
-- Cast the bytes to a string
<string>f"my_bucket:/lion_witch_wardrobe.txt".get();
```

```surql title="Output"
-------- Query --------

b"4F6E6365207468657265207765726520666F7572206368696C6472656E2077686F7365206E616D657320776572652050657465722C20537573616E2C2045646D756E642C20616E64204C7563792E"

-------- Query --------

'Once there were four children whose names were Peter, Susan, Edmund, and Lucy.'
```

### File backend

A file backend can be chosen for a bucket by typing `"file:"` and then the rest of the path, if necessary.

```surql
DEFINE BUCKET my_bucket BACKEND "file:/some_directory";
```

A check will then be made to see if the `SURREAL_BUCKET_FOLDER_ALLOWLIST` environment variable contains the path, without which the following error will be generated.

```surql
'File access denied: /some_directory'
```

The following command can be used to start running an instance in which a bucket with a file backend can be defined.

```bash
# Unix
SURREAL_BUCKET_FOLDER_ALLOWLIST="/" surreal db start --user root --pass secret

# Windows (PowerShell)
$env:SURREAL_BUCKET_FOLDER_ALLOWLIST = "/" 
surreal db start --user root --pass secret
```

A `file:` bucket cannot store a [content type](/docs/reference/query-language/functions/database-functions/file.md#content-types). From SurrealDB 4.0, a write that names one fails, rather than storing the file without it.

A file key must stay inside the bucket's folder. A key with a `.` or `..` segment, an empty segment such as `//`, or a trailing `/` is refused, and so is a key that leaves the folder through a symbolic link.

```surql
-- Setup from the example above
DEFINE BUCKET my_bucket BACKEND "file:/some_directory";

f"my_bucket:/../notes.txt".put("text");
//- "Operation for bucket `my_bucket` failed: object key '/../notes.txt' contains a path-traversal segment"

f"my_bucket:/drafts//notes.txt".put("text");
//- "Operation for bucket `my_bucket` failed: object key '/drafts//notes.txt' contains an empty segment or a trailing separator"
```

### Cloud object storage backends

_(since v3.3.0)_

A bucket can keep its files in Amazon S3 or an S3-compatible service (such as MinIO, Backblaze B2, Wasabi or Cloudflare R2), in Google Cloud Storage, or in Azure Blob Storage. The scheme of the `BACKEND` URL selects the service:

| Scheme | Service |
| --- | --- |
| `s3://`, `s3+https://` | Amazon S3, or an S3-compatible service reached over HTTPS |
| `s3+http://` | An S3-compatible service reached over plain HTTP, such as a local MinIO |
| `gs://`, `gcs://` | Google Cloud Storage |
| `az://`, `azure://` | Azure Blob Storage |

These backends exist in native builds of SurrealDB only. A WebAssembly build of the engine has the memory backend alone, so a cloud or `file:` URL fails there as an unsupported backend. The memory and file backends are unchanged.

`DEFINE BUCKET` checks the URL when it runs, so a malformed URL or an unknown scheme is an error at that point. No request reaches the service until a file operation runs, so a wrong key or a missing bucket shows up there instead.

> [!NOTE]
> The `BACKEND` URL is stored with the bucket definition exactly as written. `INFO FOR DB` and an [export](/docs/reference/cli/db/commands/export.md#passwords-and-credentials-in-an-export) show it with the credentials replaced by `[REDACTED]`: the password in `user:password@host`, the user name in `user@host`, and the value of each query parameter whose name contains `secret`, `token`, `key`, `sig`, `pass`, `cred` or `auth`, or starts with `x-amz-` or `x-goog-`. An imported bucket therefore needs its credentials again. Where the server can take credentials from its environment or from an instance role, leave them out of the URL.

#### Amazon S3 and S3-compatible services

```text title="URL format"
s3:/<bucket>[?<parameters>]
s3://[<access_key>:<secret_key>@]<endpoint>[:<port>]/<bucket>[?<parameters>]
```

The bucket name is the first path segment. The host, when present, is a custom endpoint for an S3-compatible service, and requests to it use path-style addressing. With no host, requests go to the AWS endpoint for the region, unless the server's environment sets `AWS_ENDPOINT`. Because the host is always an endpoint, `s3://my-bucket` names an endpoint and no bucket, and fails; for AWS S3 itself, write `s3:/my-bucket`.

| Parameter | Description |
| --- | --- |
| `region` | The region, used to sign requests and, with no host, to choose the AWS endpoint. Defaults to `us-east-1`. The `AWS_REGION` and `AWS_DEFAULT_REGION` environment variables are not consulted. |
| `prefix` | A key prefix inside the bucket. Every file in the SurrealDB bucket is stored under it. |
| `access_key`, `secret_key` | Credentials, as an alternative to `<access_key>:<secret_key>@` before the host. Both must be given. |

Credentials in the URL take precedence. Without them, the standard AWS credential sources apply: the `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and `AWS_SESSION_TOKEN` environment variables, a web identity token (`AWS_WEB_IDENTITY_TOKEN_FILE` with `AWS_ROLE_ARN`), an ECS task role or EKS pod identity, or an EC2 instance profile. The shared credentials file (`~/.aws/credentials`) is not read.

```surql
-- AWS S3, with credentials from the environment or an instance role
DEFINE BUCKET invoices
	BACKEND "s3:/acme-invoices?region=eu-west-2&prefix=surrealdb/invoices";

-- MinIO running locally over plain HTTP, with credentials before the host
DEFINE BUCKET uploads
	BACKEND "s3+http://surrealdb:strongPassword@localhost:9000/uploads";
```

#### Google Cloud Storage

```text title="URL format"
gs://<bucket>[?<parameters>]
```

The bucket name is the host. `gcs://` is an alias for `gs://`.

| Parameter | Description |
| --- | --- |
| `prefix` | A key prefix inside the bucket. |
| `service_account` | The path to a service account key file (JSON) on the server. |
| `service_account_key` | A service account key, as inline JSON. It cannot be combined with `service_account`. |
| `anonymous` | Send unsigned requests, for a publicly readable bucket. The flag is on when present with no value, `true` or `1`. |

Without `service_account` or `service_account_key`, the standard Google Cloud credential sources apply: the `GOOGLE_SERVICE_ACCOUNT`, `GOOGLE_SERVICE_ACCOUNT_KEY` or `GOOGLE_APPLICATION_CREDENTIALS` environment variables, the application default credentials written by `gcloud auth application-default login`, or the metadata server on Google Cloud compute.

```surql
DEFINE BUCKET reports
	BACKEND "gs://acme-reports?prefix=surrealdb&service_account=/etc/surrealdb/gcs-service-account.json";
```

#### Azure Blob Storage

```text title="URL format"
az://<account>/<container>[?<parameters>]
```

The storage account name is the host and the container name is the first path segment. `azure://` is an alias for `az://`.

| Parameter | Description |
| --- | --- |
| `prefix` | A key prefix inside the container. |
| `access_key` | The storage account access key. |
| `sas_token` | A shared access signature (SAS) token. |
| `anonymous` | Send unsigned requests, for a container that allows public read access. The flag is on when present with no value, `true` or `1`. |
| `use_emulator` | Connect to the Azurite emulator at `http://127.0.0.1:10000`, or at the `AZURITE_BLOB_STORAGE_URL` environment variable when set. The flag is on when present with no value, `true` or `1`. |

Without `access_key` or `sas_token`, the standard Azure credential sources apply: the `AZURE_STORAGE_ACCOUNT_KEY` environment variable, a service principal or workload identity configured through the `AZURE_*` environment variables, or a managed identity.

```surql
DEFINE BUCKET media BACKEND "az://acmemedia/uploads?prefix=surrealdb";
```

> [!NOTE]
> Query parameter values are percent-decoded, so a value containing `+` or `&` has to encode it as `%2B` or `%26`. AWS secret keys and Azure account keys often contain `+`, and a SAS token is itself a query string, so percent-encode the whole token as one value. Credentials written before the host are not decoded at all, so an S3 secret key containing `/` belongs in the `secret_key` parameter instead.

### Global backend

The global bucket is one store for the whole server, set with the [`SURREAL_GLOBAL_BUCKET`](/docs/reference/cli/db/environment-variables.md) environment variable, which accepts the same URLs as `BACKEND`. A bucket uses part of it through a `global://` backend followed by a path. The bucket serves the objects under that path, and SurrealDB adds no prefix of its own:

```surql
-- The whole global bucket
DEFINE BUCKET everything BACKEND "global://";

-- Only the objects under /app/uploads in the global bucket
DEFINE BUCKET uploads BACKEND "global://app/uploads";
```

Buckets whose paths overlap see the same objects. With the two buckets above, `f"uploads:/a.txt"` and `f"everything:/app/uploads/a.txt"` are the same file.

The global bucket holds the files of every namespace and database, so only a root user can give a bucket a `global://` backend, on `DEFINE BUCKET` and on `ALTER BUCKET`. A namespace or database user gets the error ``Only a root user can give a bucket a `global://` backend``. A path that contains `.` or `..` as a segment, a backslash or a control character is refused.

When `SURREAL_GLOBAL_BUCKET_ENFORCED` is `true`, `global://` is the only backend a bucket can have. Namespace and database users then cannot define buckets at all, so a root user defines them.

#### Buckets defined without a backend

Before SurrealDB 4.0, a `DEFINE BUCKET` statement could leave out `BACKEND`, and the bucket then used the global bucket under an automatic prefix. The prefix is made from the internal identifiers of the namespace and the database, which are numbers rather than their names, followed by the name of the bucket. From SurrealDB 4.0, `BACKEND` is required, and a statement without it fails:

```surql
DEFINE BUCKET my_bucket;
```

```surql title="Error output"
'DEFINE BUCKET needs a BACKEND, such as BACKEND "global://" for the global bucket'
```

A bucket that an earlier release defined this way keeps its files. SurrealDB serves it from the same prefix as before, and `INFO FOR DB` shows that prefix as an explicit `global://` path:

```surql
INFO FOR DB.buckets;
```

```surql title="Example output"
{ my_bucket: "DEFINE BUCKET my_bucket BACKEND 'global://1/0/my_bucket' PERMISSIONS FULL" }
``` An [import](/docs/reference/cli/db/commands/import.md) of an older export that contains such a bucket also still works, and the bucket uses the prefix of the namespace and database it is imported into.

## Setting permissions on buckets

By default, the permissions on a bucket will be set to FULL unless otherwise specified.

```surql
DEFINE BUCKET my_bucket BACKEND "memory";
INFO FOR DB;
```

```surql title="Output"
{
  accesses: {},
  analyzers: {},
  apis: {},
  buckets: {
    my_bucket: "DEFINE BUCKET my_bucket BACKEND 'memory' PERMISSIONS FULL"
  },
  configs: {},
  functions: {},
  models: {},
  modules: {},
  params: {},
  sequences: {},
  tables: {},
  users: {}
}
```

You can set permissions on buckets to control who can perform operations on the files stored in them using the `PERMISSIONS` clause. In the clause three additional variables are available:
- `$action`: The action to be executed (`put`, `get`, `head`, `delete`, `copy`, `rename`, `exists`, `list`, `presign_get`, `presign_put`)
- `$file`: The [file pointer](/docs/reference/query-language/language-primitives/data-types/files.md) of the file to be accessed
- `$target`: The target [file pointer](/docs/reference/query-language/language-primitives/data-types/files.md) in copy/rename operations

```surql
-- Set permissions for the bucket
DEFINE BUCKET admin_bucket BACKEND "memory"
  PERMISSIONS WHERE $auth.admin = true
```

A bucket's `PERMISSIONS` clause reads records without checking the caller's permissions, in the same way as a [table permission clause](/docs/reference/query-language/statements/define/table.md#defining-permissions). In the example above, `$auth.admin` resolves even when the record user may not select their own record.

Record users and guests can never list the files in a bucket, whatever its `PERMISSIONS` clause allows. For them, [`file::list()`](/docs/reference/query-language/functions/database-functions/file.md) fails with an error such as ``"You don't have permission to list this file in the `my_bucket` bucket"``.

### Permissions for presigned URLs

_(since v4.0.0)_

[`file::presign_get`](/docs/reference/query-language/functions/database-functions/file.md#filepresign_get) and [`file::presign_put`](/docs/reference/query-language/functions/database-functions/file.md#filepresign_put) check the clause with `$action` set to `presign_get` or `presign_put`, which are separate from `get` and `put`. A clause that allows `get` therefore does not allow a URL to be created. The clause runs once, when the URL is created, and not when the URL is used, so a URL keeps working until it expires even if the clause changes. See [Presigned URLs](/docs/learn/schema-management/files/presigned-urls.md).

For these two actions, the clause can also read the options of the URL:

| Variable | Action | Value |
| --- | --- | --- |
| `$expires` | `presign_get`, `presign_put` | How long the URL works, as a `duration` |
| `$max_size` | `presign_put` | The largest upload the URL accepts, in bytes. It is always a number: a URL created without `max_size` has the server's maximum. |
| `$overwrite` | `presign_put` | Whether the upload can replace an existing file |
| `$content_type` | `presign_put` | The media type the upload must send, or `NONE` |

The clause below lets each record user upload to and download from a folder named after their own record ID, through short-lived URLs only, with uploads of PNG and JPEG images up to 5 MiB that cannot replace an existing file.

```surql
DEFINE BUCKET avatars BACKEND "memory"
  PERMISSIONS WHERE
       ($action IN ["get", "put"] AND $file.key().starts_with("/u/" + <string>$auth.id + "/"))
    OR ($action = "presign_get"
        AND $file.key().starts_with("/u/" + <string>$auth.id + "/")
        AND $expires <= 15m)
    OR ($action = "presign_put"
        AND $file.key().starts_with("/u/" + <string>$auth.id + "/")
        AND $expires <= 5m
        AND $max_size <= 5242880
        AND $overwrite = false
        AND $content_type IN ["image/png", "image/jpeg"]);
```

`$content_type IN [...]` is `false` when `$content_type` is `NONE`, so the clause above also refuses an upload URL that names no type.

> [!WARNING]
> A bucket with `PERMISSIONS FULL`, which is the default, allows any user who can run a query on the database to create presigned URLs for it. The server limits each URL to `SURREAL_BUCKET_PRESIGN_MAX_TTL` and `SURREAL_BUCKET_PRESIGN_MAX_SIZE`, but use a `PERMISSIONS` clause on any bucket that record users can reach. On a server started with `--allow-guests`, `PERMISSIONS FULL` also lets anyone read and write the bucket through the [`/bucket` HTTP route](/docs/reference/protocols/http-protocol.md#bucket) without credentials.

## Root and namespace buckets

_(since v4.0.0)_

A bucket belongs to a database unless the statement says otherwise. `ON ROOT` defines a bucket at the root, and `ON NAMESPACE` defines one in the namespace in use. `ON DATABASE` is the default and can be left out.

A file pointer reaches the buckets at the level of the session that uses it: the database's buckets when a database is selected, otherwise the namespace's buckets when a namespace is selected, and otherwise the root's buckets. A file pointer cannot reach a bucket at another level, so a session with a database selected cannot use a root bucket, even when a bucket of the same name exists at the root.

```surql
-- In a root session with no namespace selected
DEFINE BUCKET shared ON ROOT BACKEND "memory";
f"shared:/a.txt".put("root");
<string> f"shared:/a.txt".get();
```

```surql title="Output"
'root'
```

`INFO FOR ROOT` and `INFO FOR NS` list the buckets of their level under `buckets`, in the same way as `INFO FOR DB`:

```surql
INFO FOR ROOT.buckets;
```

```surql title="Output"
{ shared: "DEFINE BUCKET shared ON ROOT BACKEND 'memory' PERMISSIONS FULL" }
```

[`ALTER BUCKET`](/docs/reference/query-language/statements/alter/bucket.md) and [`REMOVE BUCKET`](/docs/reference/query-language/statements/remove.md) take the same `ON` clause, and without it they change or remove a database bucket.

A root or namespace bucket follows these rules:

- Guests and record users can never use a bucket above the database level, whatever its `PERMISSIONS` clause allows. A system user with a role at the bucket's level or above is judged by that role and the `PERMISSIONS` clause, as for a database bucket.
- [Presigned URLs](#permissions-for-presigned-urls) can be created only for database buckets, because a signature belongs to one namespace and database.
- A root bucket over the [global bucket](#global-backend), such as `DEFINE BUCKET cloud ON ROOT BACKEND "global://"`, gives a root session access to the whole global bucket.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/config

# DEFINE CONFIG

This statement allows you to set external configurations on the database, either for API middleware and permissions, or for how the database's tables and functions are exposed via the GraphQL API.

The `DEFINE CONFIG` statement allows you to set external configurations on your database. It can be used to configure API middleware and permissions, or to configure how the database's tables and functions are exposed via the GraphQL API.

## Requirements

- You **must** be authenticated as a **root**, **namespace**, or **database** user before you can use the `DEFINE CONFIG GRAPHQL` statement.
- You **must** select your **namespace** and **database** before you can use the `DEFINE CONFIG GRAPHQL` statement.
- You **must** define at least one table in your database for the GraphQL API to function.
- You **must** have started the SurrealDB instance with GraphQL enabled.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
DEFINE CONFIG [ OVERWRITE | IF NOT EXISTS ]
  ( API
      [ MIDDLEWARE @function(...), ... ]
      PERMISSIONS [ NONE | FULL | @expression ]
  | GRAPHQL
      TABLES [ AUTO | NONE | INCLUDE @table,
        ... | EXCLUDE @table,
        ... ]
      FUNCTIONS [ AUTO | NONE | INCLUDE @function,
        ... | EXCLUDE @function,
        ... ]
      [ DEPTH @integer ]
      [ COMPLEXITY @integer ]
      [ INTROSPECTION NONE ]
  | DEFAULT
      NAMESPACE @namespace
      DATABASE @database
  )
```

## DEFINE CONFIG API

The `DEFINE CONFIG API` statement can be used to set middleware and permissions in order to alter the behaviour of the database for guest and [record users](/docs/reference/query-language/statements/define/access/record.md). This middleware can be used in cases such as rate limiting on the query language and setting how many resources a client can read or alter at a time.

`DEFINE CONFIG API` is often used in conjunction with a [flag](/docs/learn/security/authorization/capabilities.md) or [environment variable](/docs/reference/cli/db/environment-variables.md) to disable arbitrary queries, thereby forcing record and anonymous users to interact with the database via API endpoints alone.

The following is an example of a `DEFINE CONFIG` statement that includes a timeout and a single header in the responses of all API endpoints.

```surql
DEFINE CONFIG API
    MIDDLEWARE 
        api::timeout(10s),
        api::res::headers({
            'Access-Control-Allow-Origin': '*'
        });
```

To set the actual API endpoints and their middleware, a `DEFINE API` statement is used for each endpoint. For more details and examples, see the pages for [`DEFINE API`](/docs/reference/query-language/statements/define/api.md) and [API functions](/docs/reference/query-language/functions/database-functions/api.md).

The behaviour of API endpoints can be tested using the `api::invoke` method, or through a regular HTTP call to the endpoint that [includes the namespace and database name](/docs/reference/protocols/http-protocol.md#custom).

This next example uses `DEFINE CONFIG` to set a single response header, followed by two endpoints that return different output.

```surql
DEFINE CONFIG API
    MIDDLEWARE 
        api::res::headers({
            'Access-Control-Allow-Origin': '*'
        });

DEFINE API "/test" FOR get THEN {};
DEFINE API "/test2" FOR get THEN {
    {
        body: {
            some: "data"
        }
    }
};

api::invoke("/test");
api::invoke("/test2");
```

The query shows that the endpoints return a combination of the `DEFINE CONFIG` middleware and the response object set in the `DEFINE API` statements.

```surql title="Example output"
-------- Query --------

{
	body: NONE,
	headers: {
		"access-control-allow-origin": '*',
		"x-surreal-request-id": '6db5a2ca-70d6-40a0-ac92-c96283786469'
	},
	request_id: '6db5a2ca-70d6-40a0-ac92-c96283786469',
	status: 200
}

-------- Query --------

{
	body: {
		some: 'data'
	},
	headers: {
		"access-control-allow-origin": '*',
		"x-surreal-request-id": 'd8096c89-2c84-42ca-9420-26f1bae72e1b'
	},
	request_id: 'd8096c89-2c84-42ca-9420-26f1bae72e1b',
	status: 200
}
```

Note that the middleware and permissions inside individual `DEFINE API` statements will override the middleware in a `DEFINE CONFIG API` statement. In the following example, the default `10s` timeout is set to a single microsecond for the `"/test"` endpoint, giving the intended query no time to complete.

```surql
-- Setup
CREATE |person:10000| RETURN NONE;

DEFINE CONFIG API
    MIDDLEWARE 
        api::timeout(10s),
        api::res::headers({
            'Access-Control-Allow-Origin': '*'
        });

DEFINE API OVERWRITE "/test"
    FOR get 
        MIDDLEWARE
            api::timeout(1µs)
        THEN {
            RETURN {
                status: 200,
                body: { 
                    data: (SELECT * FROM person),
                    however: "This will probably never return because
                      the timeout is 1 microsecond"
                }
            };
        };

api::invoke("/test");
```

```surql title="Possible output"
{
	body: 'The query was not executed because it exceeded the timeout: 1µs',
	headers: {
		"access-control-allow-origin": '*',
		"x-surreal-request-id": 'aa81ce70-bc03-4a4f-a631-19b753707905'
	},
	request_id: 'aa81ce70-bc03-4a4f-a631-19b753707905',
	status: 500
}
```

## DEFINE CONFIG DEFAULT

The `DEFINE CONFIG DEFAULT` statement sets the namespace and database that a connection selects when it asks for the defaults instead of naming a pair itself. The configuration is stored at the root level, so you must be authenticated as a root user to define it.

```surql
DEFINE CONFIG DEFAULT NAMESPACE my_namespace DATABASE my_database;
```

A client asks for these defaults by sending a `USE` with neither a namespace nor a database - the SDK methods `use_defaults()` in [Rust](/docs/reference/rust/methods/use-defaults.md) and the equivalent in the other SDKs. The defaults only fill in what is missing: a session that already selected a namespace, from a token for example, keeps that selection.

## DEFINE CONFIG GRAPHQL

The configuration set using `DEFINE CONFIG GRAPHQL` is required to enable GraphQL functionality in your database, and specifies which tables and functions should be included or excluded from the GraphQL schema.

The GraphQL configuration defined using this statement dictates how clients interact with your database through GraphQL queries and mutations.

### Important notes

- The `DEFINE CONFIG GRAPHQL` statement **must** be executed before any GraphQL queries can be made.
- If you attempt to use the GraphQL API without defining the configuration, you will receive a `NotConfigured` error.
- If no tables are defined in the database, you will receive an error stating "No tables found in database" when attempting to use the GraphQL API.

### Example usage

```surql
-- Define GraphQL configuration
DEFINE CONFIG GRAPHQL AUTO;
```

The above statement will automatically include all tables and functions in the GraphQL schema, and show up in the database as `DEFINE CONFIG GRAPHQL TABLES AUTO FUNCTIONS AUTO`.

### `TABLES` configuration

The `TABLES` clause in the `DEFINE CONFIG GRAPHQL` statement specifies how tables are exposed via GraphQL. There are four options for the `TABLES` configuration:

- `AUTO`: Automatically include all tables in the GraphQL schema.
- `NONE`: Do not include any tables in the GraphQL schema.
- `INCLUDE`: Specify a list of tables to include in the GraphQL schema.
- `EXCLUDE`: Specify a list of tables to exclude from the GraphQL schema.

#### `AUTO`

When you specify `TABLES AUTO`, all tables in the database are automatically included in the GraphQL schema.

```surql
DEFINE CONFIG GRAPHQL TABLES AUTO;
```

#### `NONE`

When you specify `TABLES NONE`, no tables are included in the GraphQL schema.

```surql
DEFINE CONFIG GRAPHQL TABLES NONE;
```

#### `INCLUDE`

You can specify a list of tables to include in the GraphQL schema using the `INCLUDE` clause. The list of tables is specified as a comma-separated list without brackets.

```surql
DEFINE CONFIG GRAPHQL TABLES INCLUDE user, post, comment;
```

#### `EXCLUDE`

You can specify a list of tables to leave out of the GraphQL schema using the `EXCLUDE` clause. Every other table in the database is included. The list of tables is specified as a comma-separated list without brackets.

```surql
DEFINE CONFIG GRAPHQL TABLES EXCLUDE audit_log, session;
```

> [!NOTE]
> `TABLES EXCLUDE` works from SurrealDB 3.0.0 and 2.6.1. Earlier releases store it as `TABLES INCLUDE`, so the GraphQL schema exposes only the tables it was meant to hide.

### `FUNCTIONS` configuration

The `FUNCTIONS` clause in the `DEFINE CONFIG GRAPHQL` statement specifies how functions are exposed via GraphQL. There are four options for the `FUNCTIONS` configuration:

- `AUTO`: Automatically include all functions in the GraphQL schema.
- `NONE`: Do not include any functions in the GraphQL schema.
- `INCLUDE`: Specify a list of functions to include in the GraphQL schema.
- `EXCLUDE`: Specify a list of functions to exclude from the GraphQL schema.

#### `AUTO`

When you specify `FUNCTIONS AUTO`, all functions in the database are automatically included in the GraphQL schema.

```surql
DEFINE CONFIG GRAPHQL FUNCTIONS AUTO;
```

#### `NONE`

When you specify `FUNCTIONS NONE`, no functions are included in the GraphQL schema.

```surql
DEFINE CONFIG GRAPHQL FUNCTIONS NONE;
```

#### `INCLUDE`

You can specify a list of functions to include in the GraphQL schema using the `INCLUDE` clause. The functions are named in full, with their `fn::` prefix, and separated by commas.

```surql
DEFINE CONFIG GRAPHQL FUNCTIONS INCLUDE fn::getUser, fn::listPosts, fn::searchComments;
```

#### `EXCLUDE`

You can specify a list of functions to exclude from the GraphQL schema using the `EXCLUDE` clause. The list takes the same form as for `INCLUDE`.

```surql
DEFINE CONFIG GRAPHQL FUNCTIONS EXCLUDE fn::debugFunction, fn::testFunction;
```

### `DEPTH` and `COMPLEXITY` limits

`DEPTH` sets how deeply the fields of a GraphQL query can be nested, and `COMPLEXITY` sets the highest complexity score a query can have, where each selected field adds to the score. A query over either limit is refused before it runs. Without the clause, the limit is `16` for `DEPTH` and `1000` for `COMPLEXITY`.

```surql
DEFINE CONFIG GRAPHQL AUTO DEPTH 8 COMPLEXITY 500;
```

### Using the `IF NOT EXISTS` clause

The `IF NOT EXISTS` clause can be used to define the GraphQL configuration only if it does not already exist. This is useful when you want to ensure that the configuration is only created if it does not already exist, preventing errors due to duplicate definitions.

```surql
-- Define GraphQL configuration only if it does not already exist
DEFINE CONFIG IF NOT EXISTS GRAPHQL TABLES AUTO FUNCTIONS AUTO;
```

### Using the `OVERWRITE` clause

The `OVERWRITE` clause can be used to redefine the GraphQL configuration, overwriting any existing configuration. This is useful when you want to update or modify the existing GraphQL configuration.

```surql
-- Redefine GraphQL configuration, overwriting existing configuration
DEFINE CONFIG OVERWRITE GRAPHQL TABLES INCLUDE user,
  post FUNCTIONS NONE;
```

### Examples

#### Example 1: Include specific tables and functions

This example defines a GraphQL configuration that includes specific tables and functions.

```surql
DEFINE CONFIG GRAPHQL TABLES INCLUDE user, post FUNCTIONS INCLUDE fn::getUser, fn::listPosts;
```

#### Example 2: Automatically include all tables and functions

This example defines a GraphQL configuration that automatically includes all tables and functions.

```surql
DEFINE CONFIG GRAPHQL TABLES AUTO FUNCTIONS AUTO;
```

#### Example 3: Exclude specific functions

This example defines a GraphQL configuration that includes all functions except specific ones.

```surql
DEFINE CONFIG GRAPHQL FUNCTIONS EXCLUDE fn::debugFunction, fn::testFunction;
```

### Error handling

#### NotConfigured Error

If you attempt to access the GraphQL endpoint without defining the GraphQL configuration, you will receive a `NotConfigured` error.

```surql title="Error output"
{
  "error": "NotConfigured: GraphQL endpoint is not configured. Please
    define the GraphQL configuration using DEFINE CONFIG GRAPHQL."
}
```

Execute the `DEFINE CONFIG GRAPHQL` statement to define the GraphQL configuration.

```surql
-- Define GraphQL configuration
DEFINE CONFIG GRAPHQL TABLES AUTO FUNCTIONS AUTO;
```

#### "No tables found" error

If you have defined the GraphQL configuration but no tables are defined in the database, you will receive an error stating "No tables found in database" when attempting to use the GraphQL API. You can fix this by defining at least one table in your database using the [`DEFINE TABLE`](/docs/reference/query-language/statements/define/table.md) statement.

```surql title="Error output"
{
  "error": "No tables found in database. Please define at least one
    table to use the GraphQL API."
}
```

**Solution**: Define at least one table in your database.

```surql
DEFINE TABLE foo SCHEMAFUL;
DEFINE FIELD val ON foo TYPE int;
CREATE foo:1 SET val = 42;
```

### Authentication errors when accessing data via GraphQL

**Cause**: Insufficient permissions or incorrect authentication credentials.

**Solution**: Ensure you are authenticated as a user with the necessary permissions and that the permissions on tables and fields are correctly configured.

#### Authentication and permissions

- The GraphQL API respects SurrealDB's authentication and permission model.
- You must authenticate using the appropriate credentials to access data via GraphQL.
- Permissions set on tables and fields will affect the data accessible through the GraphQL API.
- If you attempt to access data without sufficient permissions, you will receive an authentication error.

#### Example: Basic authentication

```surql
-- Define a user with access permissions
DEFINE USER my_user ON DATABASE PASSWORD 'my_password';
DEFINE ACCESS user ON DATABASE TYPE RECORD
  SIGNUP ( CREATE user SET email = $email,
    pass = crypto::argon2::generate($pass) )
  SIGNIN ( SELECT * FROM user WHERE email = $email
    AND crypto::argon2::compare(pass, $pass) )
  DURATION FOR SESSION 60s, FOR TOKEN 1d;

-- Define a table with permissions
DEFINE TABLE foo SCHEMAFUL PERMISSIONS FOR select
  WHERE $auth.email = email;
DEFINE FIELD email ON foo TYPE string;
DEFINE FIELD val ON foo TYPE int;

-- Insert data
CREATE foo:1 SET val = 42, email = "user@example.com";
CREATE foo:2 SET val = 43, email = "other@example.com";
```

When querying the GraphQL API as `user@example.com`, only the records where `email = "user@example.com"` will be accessible due to the permissions set.

### Examples

#### Example 1: Defining GraphQL configuration and fetching data

```surql
-- Define GraphQL configuration to include all tables automatically
DEFINE CONFIG GRAPHQL TABLES AUTO;

-- Define a table and insert data
DEFINE TABLE foo SCHEMAFUL;
DEFINE FIELD val ON foo TYPE int;
CREATE foo:1 SET val = 42;
CREATE foo:2 SET val = 43;
```

Now, you can fetch data via GraphQL:

```graphql
query {
  foo {
    id
    val
  }
}
```

**Response:**

```json
{
  "data": {
    "foo": [
      {
        "id": "foo:1",
        "val": 42
      },
      {
        "id": "foo:2",
        "val": 43
      }
    ]
  }
}
```

#### Example 2: Including Specific Tables

```surql
-- Define GraphQL configuration to include only specific tables
DEFINE CONFIG OVERWRITE GRAPHQL TABLES INCLUDE foo;
```

When querying the GraphQL schema, only the included tables will be available.

#### Example 3: Using limit, start, order, and filter in GraphQL queries

You can use `limit`, `start`, `order`, and `filter` in your GraphQL queries to control the data returned.

##### Limit

```graphql
query {
  foo(limit: 1) {
    id
    val
  }
}
```

##### Start

```graphql
query {
  foo(start: 1) {
    id
    val
  }
}
```

##### Order

```graphql
query {
  foo(order: { desc: val }) {
    id
    val
  }
}
```

##### Filter

```graphql
query {
  foo(filter: { val: { eq: 42 } }) {
    id
    val
  }
}
```

### More information

The `DEFINE CONFIG GRAPHQL` statement enables and configures the GraphQL API in SurrealDB. By specifying which tables and functions are included or excluded, you can fine-tune the GraphQL schema to match your application's needs.

- **Authentication**: Ensure you are authenticated with the appropriate credentials.
- **Permissions**: Set up permissions on tables and fields to control access via GraphQL.
- **Configuration**: The GraphQL configuration must be defined before using the GraphQL API.
- **Error Handling**: Be aware of possible errors when the configuration is missing or incomplete.

> [!IMPORTANT]
> Always ensure you have the necessary permissions and have selected the appropriate namespace and database before using the `DEFINE CONFIG GRAPHQL` statement.

## Summary

- Use `DEFINE CONFIG GRAPHQL` to enable and configure the GraphQL API.
- Define your tables and set up permissions to control data access.
- Use the `OVERWRITE` and `IF NOT EXISTS` clauses as needed to manage your configuration.
- Always authenticate with appropriate credentials when accessing the GraphQL API.
- Use GraphQL query features like `limit`, `start`, `order`, and `filter` to control the data returned.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/database

# DEFINE DATABASE

The DEFINE DATABASE statement allows you to instantiate a named database, enabling you to specify security and configuration options.

The `DEFINE DATABASE` statement allows you to instantiate a named database, enabling you to specify security and configuration options.

## Requirements

- You must be authenticated as a root owner or editor, or namespace owner or editor before you can use the `DEFINE DATABASE` statement.
- [You must select your namespace](/docs/reference/query-language/statements/use.md) before you can use the `DEFINE DATABASE` statement.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
DEFINE DATABASE [ OVERWRITE | IF NOT EXISTS ] @name
	[ STRICT ]
	[ COMPATIBILITY 3 | 4 ]
	[ COMMENT @string ]
```

## Example usage
Below shows how you can create a database using the DEFINE DATABASE statement.

```surql
-- Specify the namespace for the database
USE NS abcum;

-- Define database
DEFINE DATABASE app_vitalsense;
```

## Using `IF NOT EXISTS` clause

The `IF NOT EXISTS` clause can be used to define a database only if it does not already exist. You should use the `IF NOT EXISTS` clause when defining a database in SurrealDB if you want to ensure that the database is only created if it does not already exist. If the database already exists, the `DEFINE DATABASE` statement will return an error.

It's particularly useful when you want to safely attempt to define a database without manually checking its existence first.

On the other hand, you should not use the `IF NOT EXISTS` clause when you want to ensure that the database definition is updated regardless of whether it already exists. In such cases, you might prefer using the `OVERWRITE` clause, which allows you to define a database and overwrite an existing one if it already exists, ensuring that the latest version of the definition is always in use.

```surql
-- Create a database if it does not already exist
DEFINE DATABASE IF NOT EXISTS app_vitalsense;
```

## Using `OVERWRITE` clause

The `OVERWRITE` clause can be used to define a database and overwrite an existing one if it already exists. You should use the `OVERWRITE` clause when you want to modify an existing database definition. If the database already exists, the `DEFINE DATABASE` statement will overwrite the existing definition with the new one.

```surql
-- Create a database and overwrite if it already exists
DEFINE DATABASE OVERWRITE app_vitalsense;
```

## Defining a `STRICT` database

_(since v3.0.0)_

A strict database is one that does not allow a resource to be used unless it has already been defined. The default behaviour in SurrealDB works otherwise, by allowing statements like [CREATE](/docs/reference/query-language/statements/create.md), [INSERT](/docs/reference/query-language/statements/insert.md) and [UPSERT](/docs/reference/query-language/statements/create.md) to work.

```surql
CREATE some_new_table;
INFO FOR DATABASE.tables;
```

The output of the [INFO](/docs/reference/query-language/statements/info.md) statement shows that a table called `some_new_table` has been created with a few default clauses.

```surql
{
	some_new_table: 'DEFINE TABLE some_new_table TYPE ANY SCHEMALESS PERMISSIONS NONE'
}
```

Such an operation within a strict database is simply not allowed.

```surql
DEFINE DATABASE new_db STRICT;
USE DATABASE new_db;
CREATE some_new_table;
```

```surql title="Output"
"The table 'some_new_table' does not exist"
```

## Compatibility level

_(since v4.0.0)_

A database has a compatibility level, `3` or `4`, which decides how a `SCHEMAFULL` table treats the records it already holds when one of its fields changes:

| Level | A field change that existing records may not satisfy | `REMOVE FIELD` |
| --- | --- | --- |
| `4` | Refused unless the statement says what the records become, with [`MIGRATE EXISTING ROWS`](/docs/reference/query-language/statements/define/field.md#migrating-existing-records) | Removes the field's stored values |
| `3` | Accepted, and the records keep the values they held, as in SurrealDB 3.x | Removes only the definition |

A database created by SurrealDB 4.0 is at level 4 unless the statement says otherwise. A database that a 3.x release created stays at level 3 after an upgrade, so its schema changes behave as they did before. `INFO FOR DB` shows the level as `compatibility`.

```surql
DEFINE DATABASE legacy_app COMPATIBILITY 3;
```

To change the level of an existing database, use [`ALTER DATABASE`](/docs/reference/query-language/statements/alter/database.md#compatibility), and to change the level that databases created later start at, use [`ALTER SYSTEM`](/docs/reference/query-language/statements/alter/system.md#compatibility-clause).

Level 4 and `MIGRATE EXISTING ROWS` need the [4.0 record format](/docs/operate/upgrading/3x-to-4x.md#the-40-record-format). A datastore that still writes the 3.x format, such as a TiKV cluster that has not yet been switched with `SURREAL_FEATURE_LEVEL=4.0`, refuses them.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/event

# DEFINE EVENT

The DEFINE EVENT statement can be used to create events which can be triggered after any change or modification to the data in a record.

Events allow you to define custom logic that is executed when a record is created, updated, or deleted. These events are triggered automatically within the current transaction after data modifications in the record, giving you access to the state of the record [before and after](/docs/reference/query-language/language-primitives/parameters.md#before-after) the change.

> [!NOTE]
> Events are a side effect of other operations and thus are not triggered when data is [imported](/docs/reference/cli/db/commands/import.md).

## Key concepts

- **Events**: Triggered after changes (create, update, delete) to records in a table.
* **$event**: A preset parameter containing the type of event as a string, will always be one of "CREATE", "UPDATE", or "DELETE".
- **$before / $after**: Refer to the record state before and after the modification. Learn more about the `$before` and `$after` parameters in the [parameters documentation](/docs/reference/query-language/language-primitives/parameters.md#before-after).
- **$value**: The record in question. For a `CREATE` or `UPDATE` event, this will be the record after the changes were made. For a `DELETE` statement, this will be the record before it was deleted.
- **WHEN condition**: Determines when the event should be triggered.

## Requirements

- You must be authenticated as a root owner or editor, namespace owner or editor, or database owner or editor before you can use the `DEFINE EVENT` statement.
- [You must select your namespace and database](/docs/reference/query-language/statements/use.md) before you can use the `DEFINE EVENT` statement.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
DEFINE EVENT [ IF NOT EXISTS | OVERWRITE ] @name ON [ TABLE ] @table
  [ ASYNC [ RETRY @retry ] [ MAXDEPTH @max_depth ] ]
  [ WHEN @condition ]
  [ THEN @action ]
  [ COMMENT @string ]
```

### Clauses:

- **OVERWRITE**: Replaces the existing event if it already exists.
- **IF NOT EXISTS**: Only creates the event if it doesn't already exist.
- **WHEN**: Conditional logic that controls whether the event is triggered. Will show up in the event definition as `WHEN true` if not specified.
- **THEN**: Specifies the action(s) to execute when the event is triggered.
- **COMMENT**: Optional comment for describing the event.
- **ASYNC**: Whether to run the event outside of the transaction that triggers it. Available since SurrealDB 3.0.0.

## Example usage

-  **Email Change Detection**: Create an event that logs whenever a user's email is updated.

In this example:
- The `WHEN` clause checks if the email has changed.
- The `THEN` clause records this change in a `log` table.

```surql
-- Create a new event whenever a user changes their email address
-- One-statement event
DEFINE EVENT OVERWRITE test
  ON TABLE user WHEN $before.email != $after.email THEN (
    CREATE log SET 
        user       = $value.id,
        -- Turn events like "CREATE" into string "email created"
        action     = 'email' + ' ' + $event.lowercase() + 'd',
        -- `email` field may be NONE, log as '' if so
        old_email  = $before.email ?? '',
        new_email  = $after.email  ?? '',
        at         = time::now()
);
UPSERT user:test SET email = 'old_email@test.com';
UPSERT user:test SET email = 'new_email@test.com';
DELETE user:test;
SELECT * FROM log ORDER BY at ASC;
```

```surql title="Example output"
[
	{
		action: 'email created',
		at: d'2024-11-25T02:59:41.003Z',
		id: log:e3thw1l0q7xiapznar1f,
		new_email: 'old_email@test.com',
		old_email: '',
		user: user:test
	},
	{
		action: 'email updated',
		at: d'2024-11-25T02:59:41.003Z',
		id: log:uaarfyk191jgod06xobm,
		new_email: 'new_email@test.com',
		old_email: 'old_email@test.com',
		user: user:test
	},
	{
		action: 'email deleted',
		at: d'2024-11-25T02:59:41.003Z',
		id: log:mlkag8h1xotglpz9wt2i,
		new_email: '',
		old_email: 'new_email@test.com',
		user: user:test
	}
]
```

### More complex logic:

-  **Purchase Event with Multiple Actions**: Log a purchase and establish relationships between the customer and product.

```surql
DEFINE EVENT purchase_made ON TABLE purchase
    WHEN $before == NONE
    THEN {
        LET $customer = (SELECT * FROM customer
          WHERE id = $after.customer);
        LET $product = (SELECT * FROM product WHERE id = $after.product);

        RELATE $customer->bought->$product CONTENT {
            quantity: $after.quantity,
            total: $after.total,
            status: 'Pending',
        };

        CREATE log SET
            customer_id = $after.customer,
            product_id = $after.product,
            action = 'purchase_created',
            timestamp = time::now();
    };
```

In this example:

- We perform multiple actions when a purchase is created: establishing relationships using the [RELATE](/docs/reference/query-language/statements/relate.md) statement and creating a log entry.

A `RELATE` inside an event often builds the ends of the relation from fields of `$after`. A field path such as `$after.from` has to be wrapped in parentheses there, as `($after.from)`. See [Expressions at the ends of a relation](/docs/reference/query-language/statements/relate.md#expressions-at-the-ends-of-a-relation) for the rule and an example, and for `INSERT RELATION`, which needs no parentheses.

## Specific events

You can trigger events based on specific events. You can use the variable $event to detect what type of event is triggered on the table.

```surql
-- UPDATE event
-- Here we are creating a notification when a user is updated.
DEFINE EVENT user_updated ON TABLE user
    WHEN $event = "UPDATE"
    THEN (
        CREATE notification SET message = "User updated", user_id = $after.id, created_at = time::now()
    );

-- DELETE event is triggered when a record is deleted from the table.
-- Here we are creating a notification when a user is deleted.
DEFINE EVENT user_deleted ON TABLE user
    WHEN $event = "DELETE"
    THEN (
        CREATE notification SET message = "User deleted", user_id = $before.id, created_at = time::now()
    );

-- You can combine multiple events based on your use cases.
-- Here we are creating a log when a user is created, updated or deleted.
DEFINE EVENT user_event ON TABLE user
    WHEN $event = "CREATE" OR $event = "UPDATE" OR $event = "DELETE"
    THEN (
        CREATE log SET
            table = "user",
            event = $event,
            happened_at = time::now()
    );
```

This longer example shows an event that updates all posts for a publication to "published" status once a publication containing them is created.

```surql
-- Define an event
DEFINE FIELD status ON post TYPE "submitted" | "published" DEFAULT "submitted";
DEFINE EVENT publish_post ON TABLE publication
    WHEN $event = "CREATE"
    THEN (
        FOR $post IN $after.posts {
            UPDATE $post SET status = "published";
        }        
    );

CREATE post:one SET content = "I read the news today, oh boy...";
CREATE post:two SET content = "On the banks of Tuonela Bleach the skeletons of kings";
CREATE post:three SET content = "뭐 화끈한 일 뭐 신나는 일 없을까";
CREATE publication SET posts = [post:one, post:two, post:three];

SELECT * FROM post;
```

```surql title="Output"
[
	{
		content: 'I read the news today, oh boy...',
		id: post:one,
		status: 'published'
	},
	{
		content: '뭐 화끈한 일 뭐 신나는 일 없을까',
		id: post:three,
		status: 'published'
	},
	{
		content: 'On the banks of Tuonela Bleach the skeletons of kings',
		id: post:two,
		status: 'published'
	}
]
```

## Events and permissions

Queries inside the event always execute without any permission checks, even when triggered by changes made by the currently authenticated user. This can be very useful to perform additional checks and changes that involve tables/records that are inaccessible for the user.

Inside the event, [`$auth`](/docs/reference/query-language/language-primitives/parameters.md#auth) is the user whose change triggered it, not the user who defined the event. For a change made by a record user, `$auth` is that user's record ID, and for a change made by a system user such as root, it is `NONE`. This also holds for an [async event](#async-events), which runs later in its own transaction. An event can therefore record who made a change:

```surql
DEFINE EVENT log_author ON note THEN {
	CREATE note_log SET note = $after.id, author = $auth;
};
```

Consider a CREATE query sent by a record user that has CREATE access to the `comment` table only:

```surql
CREATE comment SET
    post = post:tomatosoup,
    content = "So delicious!",
    author = $auth.id
;
```

By having the following event defined, SurrealDB will perform the additional checks and changes:

```surql
DEFINE EVENT on_comment_created ON TABLE comment
    WHEN $event = "CREATE"
    THEN {
        -- Check if the post allows for adding comments.
        -- User record doesn't have access to the `post` table.
        IF $after.post.disable_comments {
            THROW "Can't create a comment - Comments are disabled for this post";
        };

        -- Set the `approved` field on the new comment - automatically approve
        -- comments made by the author of the post.
        -- For security reasons, record users don't have any permissions for the `approved` field.
        UPDATE $after.id SET
            approved = $after.post.author == $after.author;
    };
```

## Keeping secret values out of records

The record that triggers an event is stored with all of its fields, including any secret in it, such as a new password for a reset. Unsetting the field inside the event removes it from the stored record, but the statement that wrote the record still returns it, because events run after the statement:

```surql
DEFINE EVENT reset ON reset_password WHEN $event = "CREATE" THEN {
	UPDATE user SET pass = crypto::argon2::generate($after.password) WHERE email = $after.email;
	UPDATE $after.id UNSET password;
};
```

When the secret is only needed to make a change, pass it to a [defined function](/docs/reference/query-language/statements/define/function.md) as an argument instead of writing it to a record. The function can still record that the change happened:

```surql
DEFINE FUNCTION fn::reset_password($email: string, $password: string) {
	UPDATE user SET pass = crypto::argon2::generate($password) WHERE email = $email;
	CREATE reset_log SET email = $email, at = time::now();
};
```

An event that copies a record somewhere else, such as an audit log, can leave a field out with [`.remove()`](/docs/reference/query-language/functions/database-functions/object.md#objectremove):

```surql
DEFINE EVENT audit ON user WHEN $event = "UPDATE" THEN {
	CREATE audit SET before = $before.remove("pass"), after = $after.remove("pass");
};
```

## Accessing `$input` in events

_(since v3.0.0)_

The behaviour of events can be further refined via the `$input` parameter, which represents the record in question for the event.

```surql
-- Set CREATE in event to only trigger when record has `true` for `log_event`
DEFINE EVENT something ON person WHEN $input.log_event = true THEN {
    CREATE log SET at = time::now(), of = $input;
};

-- Set to `false`, does not trigger CREATE
CREATE person:debug SET name = "Billy", log_event = false;
-- Triggers CREATE
CREATE person:real SET name = "Bobby", log_event = true;

SELECT * FROM log;
```

Output:

```surql
[
	{
		at: d'2025-10-14T06:15:21.141Z',
		id: log:svbr2qhjywml20mufb0o,
		of: {
			log_event: true,
			name: 'Bobby'
		}
	}
]
```

## Using `IF NOT EXISTS` clause

The `IF NOT EXISTS` clause can be used to define an event only if it does not already exist. You should use the `IF NOT EXISTS` clause when defining an event in SurrealDB if you want to ensure that the event is only created if it does not already exist. If the event already exists, the `DEFINE EVENT` statement will return an error.

It's particularly useful when you want to safely attempt to define an event without manually checking its existence first.

On the other hand, you should not use the `IF NOT EXISTS` clause when you want to ensure that the event definition is updated regardless of whether it already exists. In such cases, you might prefer using the `OVERWRITE` clause, which allows you to define an event and overwrite an existing one if it already exists, ensuring that the latest version of the event definition is always in use.

```surql
-- Create a EVENT if it does not already exist
DEFINE EVENT IF NOT EXISTS example ON example THEN {};
```

## Using `OVERWRITE` clause

The `OVERWRITE` clause can be used to define an event and overwrite an existing one if it already exists. You should use the `OVERWRITE` clause when you want to modify an existing event definition. If the event already exists, the `DEFINE EVENT` statement will overwrite the existing event definition with the new one.

```surql
-- Create an EVENT and overwrite if it already exists
DEFINE EVENT OVERWRITE example ON example THEN {};
```

## Async events

_(since v3.0.0)_

Events in SurrealDB are executed synchronously within the same transaction that triggers them. While this ensures consistency, it can lead to increased latency for write operations if the event logic is complex or resource intensive.

To allow events to execute independently of the transaction that triggers them, the `ASYNC` clause can be used.

### How async events are processed

Async events are processed in an interval dependant on the environment variable `SURREAL_ASYNC_EVENT_PROCESSING_INTERVAL` (or `--async-event-interval` when starting the server) which is set to 5 seconds as the default. Lowering this will reduce the latency between a document change and its events, while leading to more frequent polls by the background worker.

Some more notes on the characteristics of async events:

* Atomicity: The event is enqueued within the same transaction as the document change. If the transaction fails, the event is never queued.
* Consistency: Asynchronous events run in a separate transaction from the original change. They see the database state at the time they are executed.
* Ordering: Events are generally processed in the order they were created, though parallel processing may occur within a single batch.
* Waiting: an event that waits, for example with [`sleep()`](/docs/reference/query-language/functions/database-functions/sleep.md), holds up the events queued behind it, including events on other tables, until it finishes. The event reads the database as it was when it started, so a check made after a `sleep()` does not see changes that were committed while it slept.
* Delivery: An event runs at least once, and can run more than once. If the event's transaction fails to commit because of a write conflict with another event, it runs again in a new transaction. From SurrealDB 3.3.1 these conflict retries do not count against the `RETRY` clause. The database changes of a failed attempt are rolled back, but side effects outside the database, such as an [`http::post()`](/docs/reference/query-language/functions/database-functions/http.md#httppost) call, are not, so make those safe to repeat.

<img src="~/assets/img/diagrams/light/event-sync-async-light.webp" darkSrc="~/assets/img/diagrams/event-sync-async.webp" alt="Two timelines. A synchronous event runs inside transaction 1, between CREATE person and COMMIT, so if the event fails the write rolls back too. An ASYNC event is only queued in transaction 1. After it commits, a worker polls every 5 seconds and runs the event in transaction 2, which commits on its own." />

The easiest way to demonstrate that async events do not occur in the same transaction is by causing one to [throw](/docs/reference/query-language/statements/throw.md) an error. As an error inside any part of a transaction will cause the transaction to fail and roll back, the following event which fails about 50% of the time would cause the `CREATE` statement that follows to fail if it were not async. As an async event, however, the events that follow the statement are each run in their own transaction.

```surql
DEFINE TABLE did_not_throw;

DEFINE EVENT may_throw ON person ASYNC THEN {
  IF rand::bool() {
      THROW "This message will never show";
  } ELSE {
    CREATE did_not_throw;  
  }
};

CREATE |person:50|;
count(SELECT * FROM did_not_throw);
```

### The `MAXDEPTH` clause

The `MAXDEPTH` clause is used to set the maximum number of times that an async event can be triggered. The number following this can range from 0 to 65535.

The default for `MAXDEPTH` is 3, as events defined on other events that lead to record creation can quickly spiral out of control at greater levels.

Taking the following contrived example:

```surql
DEFINE EVENT start ON start THEN {
    CREATE cat;
};

DEFINE EVENT cat ON person ASYNC MAXDEPTH 4 THEN {
  CREATE |cat:9|;  
};

DEFINE EVENT person ON cat ASYNC MAXDEPTH 4 THEN {
  CREATE |person:9|;
};

CREATE start;

count(SELECT VALUE id FROM person, cat);
```

Each event creates nine records of the other table, so every level holds nine times as many as the one before. While the `MAXDEPTH` in this case is only one greater than the default, the final `count()` is 7381, compared to 820 if the default is used:

<img src="~/assets/img/diagrams/light/event-maxdepth-light.webp" darkSrc="~/assets/img/diagrams/event-maxdepth.webp" alt="Records created at each depth of the example: 1 cat from CREATE start, then 9 people at depth 1, 81 cats at depth 2, 729 people at depth 3 and 6,561 cats at depth 4. The default MAXDEPTH of 3 stops after depth 3, for 820 records in all, and MAXDEPTH 4 adds depth 4 for 7,381." />

This is somewhat similar to recursive queries which can also quickly add up.

```surql
-- Create five people
CREATE |person:1..=5|;
-- Make each person friends with each of the four others
UPDATE person SET friends = (SELECT VALUE id
  FROM person).complement([$this.id]);
-- Count after five levels of depth is already 1024!
count(person:1.{..5}.friends);
```

### The `RETRY` clause

The `RETRY` clause is suitable for events that may fail but can succeed on successive attempts.

The example below shows two events that each have a 50% chance of failure and zero retries.

```surql
DEFINE EVENT one ON account ASYNC RETRY 0 THEN {
    IF rand::bool() {
        THROW "Failed!"
    } ELSE {
        CREATE it:worked SET very = "well";
    }
};

DEFINE EVENT two ON account ASYNC RETRY 0 THEN {
    IF rand::bool() {
        THROW "Failed!"
    } ELSE {
        CREATE it:worked SET very = "well";
    }
};

CREATE account;
```

Following up these events with a `SELECT * FROM it` will most likely lead to the following input.

```surql
[
	{
		id: it:worked,
		very: 'well'
	}
]
```

However, with zero retries there is still a 25% chance that the query will only ever lead to the error `"The table 'it' does not exist"`.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/extension

# DEFINE EXTENSION

The DEFINE EXTENSION statement loads a SurrealDB extension into a database from a bucket or Silo, with its DIGEST, SIGNER or UNSIGNED, CAPABILITIES, BINDINGS and PERMISSIONS, so that its functions can be called as ext::name::function().

_(since v4.0.0)_

A `DEFINE EXTENSION` statement loads a [SurrealDB extension](/docs/learn/extensions/plugins/overview.md), a WebAssembly package built from Rust, into the current database and gives it a name. Its functions are then called as `ext::name::function()`. Before SurrealDB 4.0, extensions were called modules and were defined with `DEFINE MODULE`, which still works as an alias. See [Defining an extension before 4.0](#defining-an-extension-before-40).

The [`surreal ext install`](/docs/reference/cli/ext.md#ext-install) command checks an archive's signer and the capabilities it requests, asks for approval, and then runs this statement for you. Writing the statement by hand is useful in a schema file, or when the values are already known.

## Requirements

- The `surrealism` [experimental capability](/docs/learn/security/authorization/capabilities.md) must be enabled, for example with `--allow-experimental surrealism`.
- [You must select your namespace and database](/docs/reference/query-language/statements/use.md) before you can use the `DEFINE EXTENSION` statement.

## Statement syntax

**SurrealDB 4.x**

```syntax title="SurrealQL Syntax"
DEFINE EXTENSION [ OVERWRITE | IF NOT EXISTS ] ext::@name
	FROM [ @file | silo::@organisation::@package<@version> ]
	[ DIGEST @string ]
	[ SIGNER @object | UNSIGNED ]
	[ CAPABILITIES @object ]
	[ BINDINGS @object ]
	[ PERMISSIONS [ NONE | FULL | WHERE @condition ] ]
	[ COMMENT @string ]
```

**SurrealDB 3.x**

```syntax title="SurrealQL Syntax"
DEFINE MODULE [ OVERWRITE | IF NOT EXISTS ] mod::@name
	FROM @file UNSIGNED
	[ COMMENT @string ]

DEFINE MODULE [ OVERWRITE | IF NOT EXISTS ]
	silo::@organisation::@package::<@version> UNSIGNED
	[ COMMENT @string ]
```

Before SurrealDB 3.3, the statement took the archive after `AS`, and had no `UNSIGNED` clause:

```syntax title="SurrealQL Syntax"
DEFINE MODULE [ OVERWRITE | IF NOT EXISTS ] mod::@name AS @file
	[ COMMENT @string ]
```

The clauses after `FROM` can appear in any order, and each one at most once. Either `SIGNER` or `UNSIGNED` is required. A statement with neither fails with `DEFINE EXTENSION needs SIGNER {…} or UNSIGNED`.

## Example usage

An extension is built into a `.surli` archive with [`surreal ext build`](/docs/reference/cli/ext.md#ext-build), and the archive is placed in a [bucket](/docs/reference/query-language/statements/define/bucket.md) that the database can read. The extension below was built from these functions:

```rust
use surrealism::surrealism;

#[surrealism(default)]
fn hello() -> String {
	format!("Hello from your extension!")
}

#[surrealism]
fn greet(name: String) -> String {
	format!("Hello, {name}!")
}

#[surrealism]
fn add(a: i64, b: i64) -> i64 {
	a + b
}
```

With the archive in a bucket called `extensions`, define it and call its functions through the name given after `ext::`. The function marked `#[surrealism(default)]` is called by the name alone:

```surql
DEFINE EXTENSION ext::demo FROM f"extensions:/acme-demo-1.0.0.surli" UNSIGNED;

ext::demo::greet('Ada');
//- 'Hello, Ada!'

ext::demo::add(2, 3);
//- 5

ext::demo();
//- 'Hello from your extension!'
```

The name after `ext::` is chosen when the extension is defined, so one archive can be defined under several names, and two extensions can export functions with the same name.

An extension function can be called from queries, functions, events and [analyzers](/docs/reference/query-language/statements/define/analyzer.md), but not from a `COMPUTED`, `VALUE`, `DEFAULT` or `ASSERT` clause or a `PERMISSIONS` clause, because the database cannot see what the function does. See [Clauses that must not have effects](/docs/reference/query-language/statements/define/field.md#clauses-that-must-not-have-effects).

## `DIGEST`

A `.surli` archive holds a `MANIFEST` file that lists every other file in it with its SHA-256 hash, and the archive's digest is the SHA-256 hash of that `MANIFEST`. The digest identifies the exact code, and [`surreal ext build`](/docs/reference/cli/ext.md#ext-build) prints it.

When `DIGEST` is left out, the database computes it from the archive and stores it with the definition, so the definition pins the code that was there when it was defined. When `DIGEST` is given, the archive must match it:

```surql
DEFINE EXTENSION ext::demo FROM f"extensions:/acme-demo-1.0.0.surli"
	DIGEST "sha256:0000000000000000000000000000000000000000000000000000000000000000"
	UNSIGNED;
```

```surql title="Error output"
"The archive's MANIFEST digest is sha256:7b36da7d8386c1561b7d61f83f39a3bf590e25b774d935d9f8252604e80134b5, but the definition's DIGEST is sha256:0000000000000000000000000000000000000000000000000000000000000000"
```

## `SIGNER` and `UNSIGNED`

`SIGNER` names who must have signed the archive, and the database verifies the archive's signature against it when the extension is defined and before the code is loaded. An archive is signed with [`surreal ext sign`](/docs/reference/cli/ext.md#ext-sign), either with an SSH key or with Sigstore from a CI workflow.

For an archive signed with an SSH key, the signer is the public key:

```surql
DEFINE EXTENSION ext::demo FROM f"extensions:/acme-demo-1.0.0.surli"
	SIGNER { key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPhuVs9Jcx4/KCUWdMr/8Vv2BDOMj5v1qyDhCRlcDttN release@acme" };
```

For an archive signed through Sigstore, the signer object holds a `sigstore` object that names the trust anchors (`ca`, `log` and `tsa`), the certificate `issuer`, and the `identity` of the workflow that signed it, with the `repository_id` and `owner_id` that pin it to one repository. `surreal ext install` writes this object from the signature, so it is rarely written by hand.

The definition is refused when the signature does not match the signer, and when the archive carries no signature at all:

```surql title="Error output"
"The extension's SIGNATURE does not prove its SIGNER: the signature was made with a different key"
```

```surql title="Error output"
"The extension has a SIGNER, but its archive carries no SIGNATURE"
```

`UNSIGNED` loads the archive without checking a signature, whether it has one or not. Use it for an extension built and loaded within one team, where the bucket is the only route the code takes. `DIGEST` still pins the code in an unsigned definition.

## `CAPABILITIES`

An extension can reach nothing outside its own functions unless its definition grants it. A definition without `CAPABILITIES` stores `CAPABILITIES {}`, which grants nothing, whatever the archive's `package.toml` requests. The fields are:

| Field | Value | Grants |
| --- | --- | --- |
| `net` | `true`, or an array of `host:port` strings | Outgoing network access, to any address or to the listed ones |
| `functions` | An array of function names or patterns, such as `"http::get"` | Calls to SurrealQL functions |
| `queries` | `bool` | Running arbitrary SurrealQL queries |
| `scripting` | `bool` | Running embedded JavaScript |
| `write` | `bool` | Functions that write data. Without it, a function that writes runs read-only |
| `memory` | `int`, in bytes | A memory limit for each call |
| `timeout` | `duration` | A time limit for each call |
| `strict_timeout` | `bool` | `false` runs the extension without time checks, which takes effect only on a server started with [`SURREAL_SURREALISM_ALLOW_UNBOUNDED_EXECUTION`](/docs/reference/cli/db/environment-variables.md#extension-config) |

```surql
DEFINE EXTENSION ext::colour FROM f"extensions:/acme-colour-1.0.0.surli"
	SIGNER { key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPhuVs9Jcx4/KCUWdMr/8Vv2BDOMj5v1qyDhCRlcDttN" }
	CAPABILITIES { net: ["api.colour.io:443"], functions: ["http::get"] };
```

A capability granted here never exceeds the server's own: an extension granted `net: true` still cannot reach an address that the server's [capabilities](/docs/learn/security/authorization/capabilities.md) deny. In the same way, `memory` and `timeout` can only lower the server's [extension limits](/docs/reference/cli/db/environment-variables.md#extension-config).

The `net` grant also covers HTTP requests that an extension makes through the `wasi:http` interface, for example with a crate such as `waki`. Each request is checked against the grant: the host name must be allowed, the addresses it resolves to are filtered, and the connection goes to an address the grant admits. A name that resolves to a loopback or private address is refused unless the grant names that IP address. An extension granted no `net` can make no request.

## `BINDINGS`

`BINDINGS` gives an extension values that it reads by name, such as an API key or a setting that differs from one database to another. The extension declares each name and its SurrealQL type under `[bindings]` in its `package.toml`, and the definition gives each name an expression:

```toml title="package.toml"
[bindings]
api_key = { type = "string", description = "Mailgun API key", sensitive = true }
author = "option<string>"
```

```surql
DEFINE EXTENSION ext::mailer FROM f"extensions:/acme-mailer-1.2.0.surli" UNSIGNED
	BINDINGS {
		api_key: (SELECT VALUE key FROM ONLY vault:mailgun),
		author: 'noreply@acme.com'
	};
```

A name in `[bindings]` takes the type alone, as `author` does, or a table with a `type`, a `description` that [`surreal ext install`](/docs/reference/cli/ext.md#ext-install) shows when it asks for the value, and `sensitive = true` for a value that should not be written into the definition as a literal. The extension reads a value with `surrealism::binding("api_key")`. See [Reading bindings](/docs/learn/extensions/guides/extension-attribute-reference.md#reading-bindings).

### How a binding is evaluated

The database evaluates a binding's expression the first time the extension reads that name during a call, and keeps the value for the rest of the call. An expression that the extension never reads is never evaluated. The evaluation has these rules:

- **Permissions are off.** A binding can read a record that the caller cannot read, such as a key in a table defined with `PERMISSIONS NONE`. This is how a definition gives an extension a value without giving it to every user who calls the extension.
- **The caller's level is capped at the definer's.** The definition records the level of the user who defined it. A binding runs at the caller's level or the definer's level, whichever is lower, so a binding in a definition made by a database owner cannot read the namespace, even when a root user calls the extension. A caller is never raised above its own level.
- **The caller's parameters are not in scope.** A `LET` parameter or a request parameter of the caller is not visible to the expression, so a caller cannot change what the binding reads. `$auth`, `$session`, `$token` and `$access` are available.
- **The value is converted to the declared type.** A value that cannot be converted fails the read.

An error from a binding names the binding and the extension, for example ``The binding `api_key` of extension `mailer` failed to evaluate``. It never includes the value, or the error of the expression, because either could hold data that was read with permissions off. The extension receives this error and decides how to report it.

### What `DEFINE EXTENSION` checks

When the database reads the archive to define the extension, it compares `BINDINGS` with the archive's `[bindings]`. The statement is refused when `BINDINGS` gives a name that the package does not declare, or leaves out a name whose type is not `option<...>`:

```surql title="Error output"
"`BINDINGS` gives `other`, which the extension's package.toml does not declare under [bindings]"
```

```surql title="Error output"
"The extension requires the binding `api_key` of kind `string`, which `BINDINGS` does not give"
```

A name of an `option<...>` type that the definition leaves out reads as `NONE`. A definition that gives a `DIGEST` while its archive cannot be read yet, as when an import restores the definition before the archive is in its bucket, is stored without this check. A required name that such a definition leaves out fails when the extension reads it.

An archive whose extension reads no bindings is built for an earlier extension ABI, which takes no `BINDINGS`. Rebuild it with a current `surrealism` crate before you give it bindings:

```surql title="Error output"
"The extension is built for ABI 4, which cannot read bindings: rebuild it with a newer SDK to give it `BINDINGS`"
```

`BINDINGS` takes one object literal. A second `BINDINGS` clause, a name given twice, and a value that is not an object are parse errors.

### Expressions that are refused

Because every caller's call can evaluate a binding with permissions off, a binding must not have effects. `DEFINE EXTENSION` refuses an expression that writes data, writes to an external system such as `http::post`, advances state outside the transaction such as `sequence::nextval()`, blocks such as `sleep()`, or calls code whose effects the database cannot see, such as another extension:

```surql
DEFINE EXTENSION ext::mailer FROM f"extensions:/acme-mailer-1.2.0.surli" UNSIGNED
	BINDINGS { api_key: type::string((CREATE ONLY leak:1).id) };
```

```surql title="Error output"
"The BINDINGS clause must not have effects: `CREATE` writes data"
```

A read of an external system, such as `http::get`, is allowed. See [Clauses that must not have effects](/docs/reference/query-language/statements/define/field.md#clauses-that-must-not-have-effects) for the rules that schema clauses share.

Calls to an extension are also refused when a binding is read. A binding that calls a function which was redefined after the extension was defined, and which now calls an extension, fails at that point, and the read reports that the binding failed to evaluate.

### Bindings in `INFO` and exports

`INFO FOR DB` and an export show each binding as its expression, never as its value. `INFO FOR DB STRUCTURE` lists them under `bindings`, with each expression as a string:

```surql
(INFO FOR DB STRUCTURE).extensions[0].bindings;
```

```surql title="Output"
{
	api_key: '(SELECT VALUE key FROM ONLY vault:mailgun)',
	author: "'noreply@acme.com'"
}
```

A value written as a literal, such as `'noreply@acme.com'`, is therefore visible to every user who can run `INFO FOR DB` and in every export. Bind a secret as an expression that reads it from a protected table, not as a literal. `surreal ext install` prints a warning when a name marked `sensitive` is given a literal.

## Silo packages

An extension can also be loaded from a package published to Silo, SurrealDB's extension registry. The package is fetched over HTTPS from `https://silo.surrealdb.com` and cached, so it does not need to be built locally or placed in a bucket. The server needs network access to that address. There is one Silo registry, so an archive served from anywhere else is defined from a bucket instead. Before SurrealDB 4.0, `SURREAL_SURREALISM_SILO_ENDPOINT` could point `silo::` at another address.

```surql
DEFINE EXTENSION ext::palette FROM silo::acme::palette<2.1.0> UNSIGNED;
```

From SurrealDB 4.0, a Silo package needs a name like any other extension, and a definition without one is refused with `An extension needs a name`.

## Changing and removing an extension

[`ALTER EXTENSION`](/docs/reference/query-language/statements/alter/overview.md) changes only the `COMMENT` and `PERMISSIONS` of a definition. To load a new version of the code, or to change `CAPABILITIES` or `BINDINGS`, use `DEFINE EXTENSION OVERWRITE`, or [`surreal ext upgrade`](/docs/reference/cli/ext.md#ext-upgrade), which compares the new archive's signer and capabilities with the installed ones before it redefines the extension. `surreal ext upgrade --bind` changes a binding and keeps the others.

```surql
ALTER EXTENSION ext::demo COMMENT "Greeting helpers";
REMOVE EXTENSION ext::demo;
```

`INFO FOR DB` lists the database's extensions under `extensions`, with the `DIGEST`, `CAPABILITIES` and `BINDINGS` that the definition stores.

## Defining an extension before 4.0

Extensions were called modules before SurrealDB 4.0. The earlier spellings still work in 4.0 and log a deprecation warning: `DEFINE MODULE`, `ALTER MODULE` and `REMOVE MODULE` define the same thing as `DEFINE EXTENSION`, `ALTER EXTENSION` and `REMOVE EXTENSION`, and a function can be called as `mod::name::function()` as well as `ext::name::function()`. `INFO FOR DB` and exports always write the `EXTENSION` form.

A few things changed along with the name:

- **An extension defined on SurrealDB 3.x must be defined again.** Its definition has no `DIGEST` or signer, so 4.0 refuses to call it until it is defined again with `SIGNER` or `UNSIGNED`. `INFO FOR DB STRUCTURE` reports each such definition with a warning.
- **Extensions built for 3.x must be rebuilt**, because 4.0 uses a new extension ABI. See [Upgrading an extension to 4.0](/docs/learn/extensions/guides/extension-attribute-reference.md#upgrading-an-extension-to-40).
- **An `ext::` call cannot be read by SurrealDB 3.x.** A field, event, function or permission whose stored text calls `ext::` stops working on a 3.x node. Before returning a database to 3.x, rewrite those calls as `mod::`.

In SurrealDB 3.3, `FROM` replaced `AS` before the archive, and `UNSIGNED` became required:

```surql title="SurrealDB 3.3"
DEFINE MODULE mod::test FROM f"test:/demo.surli" UNSIGNED;
```

```surql notest title="Before SurrealDB 3.3"
DEFINE MODULE mod::test AS f"test:/demo.surli";
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/field

# DEFINE FIELD

The DEFINE FIELD statement allows you to instantiate a named field on a table, enabling you to set the field's schema and configuration.

The `DEFINE FIELD` statement allows you to instantiate a named field on a table, enabling you to set the field's data type, set a default value, apply assertions to protect data consistency, and set permissions specifying what operations can be performed on the field.

## Requirements

- You must be authenticated as a root owner or editor, namespace owner or editor, or database owner or editor before you can use the `DEFINE FIELD` statement.
- [You must select your namespace and database](/docs/reference/query-language/statements/use.md) before you can use the `DEFINE FIELD` statement.

## Statement syntax

**Regular Field Syntax**

```syntax title="SurrealQL Syntax"
DEFINE FIELD [ OVERWRITE | IF NOT EXISTS ] @name ON [ TABLE ] @table
	[ TYPE @type [ FLEXIBLE ] ]
	[ SQL TYPE [ POSTGRESQL | MYSQL | DYNAMODB ] @string ]
	[ INLINE ]
	[ REFERENCE 
		[ ON DELETE REJECT | 
			ON DELETE CASCADE | 
			ON DELETE IGNORE |
			ON DELETE UNSET | 
			ON DELETE THEN @expression ]
		[ MATERIALIZE INTO @table.@field [ WHERE @condition ] ]
	]
	[ DEFAULT [ALWAYS] @expression ]
  [ READONLY ]
	[ VALUE @expression ]
	[ ASSERT @expression ]
	[ PERMISSIONS [ NONE | FULL
		| FOR select @expression
		| FOR create @expression
		| FOR update @expression
	] ]
  [ COMMENT @string ]
  [ MIGRATE EXISTING ROWS AS @name USING @expression [ FALLBACK @value ] ]
  [ GRAPHQL_ALIAS @string ]
  [ GRAPHQL_DEPRECATED @string ]
```

**Computed Field Syntax**

```syntax title="SurrealQL Syntax"
DEFINE FIELD [ OVERWRITE | IF NOT EXISTS ] @name ON [ TABLE ] @table
	COMPUTED @expression
	[ TYPE @type ]
	[ PERMISSIONS [ NONE | FULL
		| FOR select @expression
		| FOR create @expression
		| FOR update @expression
	] ]
  [ COMMENT @string ]
```

## Example usage

The following expression shows the simplest way to use the `DEFINE FIELD` statement.

```surql
-- Declare the name of a field.
DEFINE FIELD email ON TABLE user;
```

The fields of an object and the items in an array can be defined individually using the `.` operator for objects, or the indexing operator for arrays.

```surql
-- Define nested object property types, after the object itself
DEFINE FIELD emails ON TABLE user TYPE object;
DEFINE FIELD emails.address ON TABLE user TYPE string;
DEFINE FIELD emails.primary ON TABLE user TYPE bool;

-- Define individual fields on an array, after the array itself
DEFINE FIELD metadata ON person TYPE array;
DEFINE FIELD metadata[0] ON person TYPE datetime;
DEFINE FIELD metadata[1] ON person TYPE int;
```

Non-unicode fields can be defined and set using backticks where necessary. Be sure that any periods to indicate nested fields are not inside the backticks, as anything enclosed in backticks will be treated as a literal string.

```surql
DEFINE FIELD name          ON user TYPE object;
DEFINE FIELD name.first    ON user TYPE string;
DEFINE FIELD `nómine`      ON user TYPE object;
DEFINE FIELD `nómine`.prim ON user TYPE string;
DEFINE FIELD `nómine.prim` ON user TYPE string;

CREATE user:one SET 
	-- Nested field
    name.first = "Billy",
	-- Also nested
    `nómine`.prim = "Billy",
	-- Not nested
    `nómine.prim` = "Billy";
```

As the output shows, the `.` enclosed inside backticks in the last field results in a single non-nested field name that includes the period, while the one immediately preceding it is nested.

```surql
[
	{
		id: user:one,
		name: {
			first: 'Billy'
		},
		"nómine": {
			prim: 'Billy'
		},
		"nómine.prim": 'Billy'
	}
]
```

## Defining data types

The `DEFINE FIELD` statement allows you to set the data type of a field. For a full list of supported data types, see [Data types](/docs/reference/query-language/language-primitives/data-types.md).

From SurrealDB 4.0, a nested field can only be defined inside a field that is already defined and can hold fields, such as an `object`. Define the parent first, as in `DEFINE FIELD address ON person TYPE object;` before `DEFINE FIELD address.city ON person TYPE string;`. Otherwise the statement fails with an error such as ``Cannot define field `address.city`: the field `address` it is nested in is not defined. Define `address` first``, or, for a parent of another type such as `int`, `any` or no type, ``only an object holds a field``. Nested definitions that a datastore already holds from an earlier version are kept.

When defining nested fields, if both the parent and the nested fields have types defined, those types must agree. Mismatching types are rejected to prevent impossible schema states.

For example, the following will fail:

```surql
DEFINE FIELD OVERWRITE fd ON c TYPE { a: string, b: number };
DEFINE FIELD OVERWRITE fd.* ON c TYPE number;
```

The above will fail with the following error:

```surql
'Cannot set field `fd.*` with type `number` as it mismatched with field `fd` with type `{ a: string, b: number }`'
```

### Simple data types

```surql
-- Set a field to have the string data type
DEFINE FIELD email ON TABLE user TYPE string;

-- Set a field to have the datetime data type
DEFINE FIELD created ON TABLE user TYPE datetime;

-- Set a field to have the bool data type
DEFINE FIELD locked ON TABLE user TYPE bool;

-- Set a field to have the number data type
DEFINE FIELD login_attempts ON TABLE user TYPE number;
```

A `|` vertical bar can be used to allow a field to be one of a set of types. The following example shows a field that can be a [`UUID`](/docs/reference/query-language/language-primitives/data-types/uuids.md) or an [`int`](/docs/reference/query-language/language-primitives/data-types/numbers.md#integer-numbers), perhaps for `user` records that have varying data due to two different legacy ID types.

```surql
-- Set a field to have either the uuid or int type
DEFINE FIELD user_id ON TABLE user TYPE uuid|int;
```

### Sized number types

_(since v4.0.0)_

A field can hold a number of a fixed width: `i8`, `u8`, `i16`, `u16`, `i32`, `u32` and `u64` for integers, and `f16` and `f32` for floating-point numbers. `i64` and `f64` are other names for `int` and `float`, and `INFO FOR TABLE` shows them as `int` and `float`. A value written to the field is converted to its type, and keeps that type when it is read back. A literal can name its type with a suffix, such as `255u8` or `1.5f16`.

```surql
DEFINE TABLE reading SCHEMAFULL;
DEFINE FIELD sensor ON reading TYPE u16;
DEFINE FIELD level ON reading TYPE f32;

CREATE reading:1 SET sensor = 65535, level = 1.25;
SELECT sensor, type::of(sensor) AS kind FROM reading:1;
```

```surql title="Output"
[{ kind: 'u16', sensor: 65535u16 }]
```

A value is converted only when it fits the type exactly. An integer outside the range of the type, or a number with a fractional part for an integer type, is refused. A whole number written as a float or a decimal, such as `20.0`, is accepted by an integer type, and an `f16` or `f32` field rounds a float to the nearest value it can hold, unless the value is too large for it.

```surql
CREATE reading:2 SET sensor = 65536, level = 1;
```

```surql title="Error output"
"Couldn't coerce value for field `sensor` of `reading:2`: Expected `u16` but found `65536`"
```

### Named types

_(since v4.0.0)_

A field can take a type declared with [`DEFINE TYPE`](/docs/reference/query-language/statements/define/type.md), written by its name. A write is coerced to the type and checked against its `ASSERT` clauses, and a field written `NONE` with no `DEFAULT` of its own takes the type's `DEFAULT`. A field of a union of strings, such as `priority` below, sorts and compares its values in the order the type declares them. See [Named types](/docs/reference/query-language/language-primitives/data-types/named-types.md) for the details.

```surql
DEFINE TYPE priority AS 'low' | 'medium' | 'high' | 'urgent';
DEFINE TYPE percent AS int ASSERT $value >= 0 AND $value <= 100
	DEFAULT 0;

DEFINE FIELD priority ON ticket TYPE priority DEFAULT 'medium';
DEFINE FIELD progress ON ticket TYPE percent;
```

### Array type

You can also set a field to have the array data type. The array data type can be used to store a list of values. You can also set the data type of the array's contents, as well as the required number of items that it must hold.

```surql
-- Set a field to have the array data type
DEFINE FIELD roles ON TABLE user TYPE array<string>;

-- Set a field to have the array data type, equivalent to `array<any>`
DEFINE FIELD posts ON TABLE user TYPE array;

-- Set a field to have the array object data type
DEFINE FIELD emails ON TABLE user TYPE array<object>;

-- Set a field that holds exactly 640 bytes
DEFINE FIELD bytes ON TABLE data TYPE array<int, 640> ASSERT $value.all(|$val| $val IN 0..=255);

-- Field for a block in a game showing the possible distinct directions a character can move next.
-- A set removes duplicates, so it holds each of the four directions at most once
DEFINE FIELD next_paths ON TABLE block TYPE set<"north" | "east" | "south" | "west">;
```

### Making a field optional

You can make a field optional by wrapping the inner type in an `option`, which allows you to store `NONE` values in the field.

What other databases call a nullable column can mean either of two values in SurrealDB. `NONE` means the field is absent, and `NULL` means the field is present with an empty value. Choose the type by which of the two a field can hold:

| Type | Field left out (`NONE`) | Field set to `NULL` |
| --- | --- | --- |
| `option<string>` | Accepted | Refused |
| `string \| null` | Refused | Accepted |
| `option<string \| null>` | Accepted | Accepted |

A value that the type does not accept is refused with an error such as ``Couldn't coerce value for field `bio` of `user:one`: Expected `none | string` but found `NULL` ``.

```surql
-- A user may enter a biography, but it is not required.
-- By using the option type you also allow for NONE values.
DEFINE FIELD biography ON TABLE user TYPE option<string>;
```

The example below shows how to define a field `user` on a `POST` table. The field is of type [record](/docs/reference/query-language/language-primitives/record-links.md). This means that the field can store a `record<user>` or `NONE`.

```surql
DEFINE FIELD user ON TABLE post TYPE option<record<user>>;
```

### Flexible data types

On a `SCHEMAFULL` table, every `object` is schemafull by default, meaning that only fields you define with nested `DEFINE FIELD` statements are allowed. The `FLEXIBLE` field clause relaxes that rule for a single field. It must appear immediately after `TYPE`, and it applies to **every `object` reachable in that field's type** - including objects inside `array<object>`, `option<object>`, union arms, and object literals.

`FLEXIBLE` is not part of the type expression. Writing `TYPE object FLEXIBLE` declares a field of type `object`, then sets the field's flexible flag. The same applies to `TYPE array<object> FLEXIBLE`: the stored type is `array<object>`, and each object element accepts arbitrary keys.

The field's type must contain at least one `object`. `FLEXIBLE` cannot be used with types such as `any` or `number` that do not include `object`.

```surql
DEFINE TABLE user SCHEMAFULL;
DEFINE FIELD name ON TABLE user TYPE string;
DEFINE FIELD metadata ON TABLE user TYPE object FLEXIBLE;
DEFINE FIELD metadata.user_id ON TABLE user TYPE int;
```

You can still define nested fields such as `metadata.user_id`. Defined subfields keep their types and assertions; `FLEXIBLE` only allows **additional** keys that are not declared in the schema.

Taking the following `CREATE` statement:

```surql
CREATE ONLY user SET
  name = "User1",
  metadata = {
      user_id: 8876687,
      country_code: "ee",
      time_zone: "EEST",
      age: 25
};
```

Without `FLEXIBLE`, the `metadata` field is a schemafull object and only declared subfields such as `metadata.user_id` are accepted.

In versions of SurrealDB before 3.0, the result of the above statement was a record in which the `metadata` field was only able to populate the `user_id` field.

```surql
{
	id: user:ke8w4u38gbm3ofp2u8fb,
	metadata: {
		user_id: 8876687
	},
  name: "User1"
}
```

As of version 3.0, the statement now returns an error upon finding the first field that was not defined in the schema.

```surql
"Found field 'metadata.age', but no such field exists for table 'user'"
```

With `FLEXIBLE`, the field accepts any extra keys on `metadata` while still requiring `name` and a valid `metadata.user_id`.

```surql title="Output"
{
	id: user:lsdk473e279oik1k484b,
	metadata: {
		age: 25,
		country_code: 'ee',
		time_zone: 'EEST',
		user_id: 8876687
	},
	name: 'User1'
}
```

The same field clause works when objects are nested inside other types. For example, `TYPE array<object> FLEXIBLE` makes every object in the array schemaless, while nested `DEFINE FIELD` paths such as `items.*.num` still type-check declared subfields:

```surql
DEFINE TABLE test SCHEMAFULL;
DEFINE FIELD items ON test TYPE array<object> FLEXIBLE;
DEFINE FIELD items.*.num ON test TYPE number;

CREATE test:1 SET items = [{ num: 1 }];
CREATE test:2 SET items = [{ num: 2, extra: 'allowed' }];
-- Fails: 'extra' is allowed but 'num' must be a number, not a string
CREATE test:3 SET items = [{ num: '3', extra: 'allowed' }];
//- "Couldn't coerce value for field `items.*.num` of `test:3`: Expected `number` but found `'3'`"
```

### Using the `DEFAULT` clause to set a default value

You can set a default value for a field using the `DEFAULT` clause. The default value will be used if no value is provided for the field.

```surql
-- A user is not locked by default.
DEFINE FIELD locked ON TABLE user TYPE bool
-- Set a default value if empty
  DEFAULT false;
```

### Using the `DEFAULT` and `ALWAYS` clauses

`DEFAULT ALWAYS` applies a default on `CREATE` and on `UPDATE` when the value is `NONE`. The `ALWAYS` keyword distinguishes this from plain `DEFAULT`, which only runs on `CREATE`.

```surql
DEFINE TABLE product SCHEMAFULL;
-- Set a default value of 123.456 for the primary field
DEFINE FIELD primary ON product TYPE number DEFAULT ALWAYS 123.456;
```

With the above definition, the `primary` field will be set to `123.456` when a new `product` is created without a value for the `primary` field or with a value of `NONE`, and when an existing `product` is updated if the value is specified the result will be the new value.

In the case of `NULL` or a mismatching type, an error will be returned.

```surql
-- This will return an error
CREATE product:test SET primary = NULL;

-- result 
"Couldn't coerce value for field `primary` of `product:test`: Expected `number` but found `NULL`"
```

On the other hand, if a valid number is provided during creation or update, that number will be used instead of the default value. In this case, `123.456`.

```surql
-- This will set the value of the `primary` field to `123.456`
CREATE product:test;

-- This will set the value of the `primary` field to `463.456`
UPSERT product:test SET primary = 463.456;

-- This will set the value of the `primary` field to `123.456`
UPSERT product:test SET primary = NONE;

```

```surql title="Query"
DEFINE TABLE post SCHEMAFULL;
DEFINE FIELD tags ON post TYPE array<object> DEFAULT ALWAYS [];
DEFINE FIELD tags.*.color ON post TYPE string DEFAULT ALWAYS 'red';
DEFINE FIELD tags.*.name ON post TYPE string;
--
CREATE post:test;
//- [{ id: post:test, tags: [] }]
UPSERT post:test SET tags += { name: 'test' };
//- [{ id: post:test, tags: [{ color: 'red', name: 'test' }] }]
UPSERT post:test SET tags += { name: 'test', color: 'blue' };
```

```surql title="Output"
[
	{
		id: post:test,
		tags: [
			{ color: 'red', name: 'test' },
			{ color: 'blue', name: 'test' }
		]
	}
]
```

### Using the `VALUE` clause to set a field's value

The `VALUE` clause differs from `DEFAULT` in that a default value is calculated if no other is indicated, otherwise accepting the value given in a query.

```surql
DEFINE FIELD updated ON TABLE user DEFAULT time::now();

-- Set `updated` to the year 1900
CREATE user SET updated = d"1900-01-01";
-- Then set to the year 1910
UPDATE user SET updated = d"1910-01-01";
```

A `VALUE` clause, on the other hand, will ignore attempts to set the field to any other value.

```surql
DEFINE FIELD updated ON TABLE user VALUE time::now();

-- Ignores 1900 date, sets `updated` to current time
CREATE user SET updated = d"1900-01-01";
-- Ignores again, updates to current time
UPDATE user SET updated = d"1900-01-01";
```

As the example above shows, a `VALUE` clause sets the value every time a record is modified (created or updated). However, the value will not be recalculated in a `SELECT` statement, which simply accesses the current set value.

```surql
DEFINE FIELD updated ON TABLE user VALUE time::now();

CREATE user:one;
SELECT * FROM ONLY user:one;
-- Sleep for one second
SLEEP 1s;
-- `updated` is still the same
SELECT * FROM ONLY user:one;
```

To create a field that is calculated each time it is accessed, a [computed field](#computed-fields) can be used.

```surql
DEFINE FIELD accessed_at ON TABLE user COMPUTED time::now();

CREATE user:one;
SELECT * FROM ONLY user:one;
-- Sleep for one second
SLEEP 1s;
-- `accessed_at` is a different value now
SELECT * FROM ONLY user:one;
```

### Altering a passed value

You can alter a passed value using the `VALUE` clause. This is useful for altering the value of a field before it is stored in the database.

In the example below, the `VALUE` clause is used to ensure that the email address is always stored in lowercase characters by using the [`string::lowercase`](/docs/reference/query-language/functions/database-functions/string.md#stringlowercase) function.

```surql
-- Ensure that an email address is always stored in lowercase characters
DEFINE FIELD email ON TABLE user TYPE string
  VALUE string::lowercase($value);
```

A `VALUE` clause runs on every write to the record, not only on writes that set the field. When a statement does not set the field, `$value` is the value already stored, so the clause runs on its own output. Lowercasing a lowercase string changes nothing, but a transformation that changes its input each time does. `VALUE crypto::argon2::generate($value)` hashes the password on `CREATE`, then hashes the stored hash on the next `UPDATE` of any other field, and the password no longer matches.

For such a transformation, compare `$value` with `$before`, which is the field's value before the statement, and only transform a value that has changed:

```surql
DEFINE FIELD pass ON TABLE user TYPE string
  VALUE IF $value != $before { crypto::argon2::generate($value) } ELSE { $value };
```

With this definition, `UPDATE user:one SET name = 'Ann'` leaves the hash as it is, and `UPDATE user:one SET pass = 'new-password'` stores a hash of the new password. Hashing the password in the statement that sets it, as the [record access](/docs/reference/query-language/statements/define/access/record.md) examples do with `crypto::argon2::generate($pass)` in `SIGNUP`, avoids the question.

### Adding a field to a table with existing records

Defining a field does not change the records already in the table. The clauses apply the next time each record is written:

- **`VALUE`** runs on the record's next write, including an `UPDATE` that sets no fields.
- **`DEFAULT`** only applies when a record is created, so existing records never receive it. `DEFAULT ALWAYS` also applies on an `UPDATE` when the field is `NONE`.
- **`ASSERT`** and **`TYPE`** check each record's next write, so an existing record that does not conform can make its next `UPDATE` fail.

To bring existing records in line straight away, update them after defining the field:

```surql
CREATE item:1 SET name = "a";

DEFINE FIELD upper ON item VALUE string::uppercase(name);
DEFINE FIELD status ON item DEFAULT "new";

-- Runs VALUE on every record
UPDATE item;
-- Sets the default on records that do not have the field
UPDATE item SET status = "new" WHERE status IS NONE;
```

```surql title="Output"
[
	{
		id: item:1,
		name: 'a',
		status: 'new',
		upper: 'A'
	}
]
```

A [computed field](#computed-fields) needs no update, because it is calculated when the record is read.

On a `SCHEMAFULL` table in a database at compatibility level 4, a new field whose type does not accept `NONE`, such as `TYPE int`, is refused while the table holds records, because none of them has a value for it yet. A `DEFAULT` does not change this, since it only applies to records created later. Either define the field as `option<int>`, or give the existing records a value as described in [Migrating existing records](#migrating-existing-records).

## Migrating existing records

_(since v4.0.0)_

A field's definition describes the values its records hold, but changing the definition does not rewrite records already stored. A `MIGRATE EXISTING ROWS` clause on `DEFINE FIELD` or [`ALTER FIELD`](/docs/reference/query-language/statements/alter/field.md) says what those records become:

```syntax title="SurrealQL Syntax"
MIGRATE EXISTING ROWS AS @name USING @expression [ FALLBACK @value ]
```

- **`AS @name`** names the migration, so that it runs once however many times the statement runs. See [Running a schema script again](#running-a-schema-script-again).
- **`USING @expression`** computes each record's new value from `$value`, its old value. The expression can call built-in functions, but not a custom function, a model, a script or an extension, and it cannot hold a statement, which includes a `SELECT` and an `IF` block. To choose a value by case, look it up in an object instead, as in `{ published: 'live' }[$value] ?? $value`.
- **`FALLBACK @value`** is a constant to store when the expression fails or its result does not fit the new definition. It may be left out only when SurrealDB can prove that the expression never fails and always produces a value that fits, which a cast such as `<string> $value` does not yet satisfy, so include a `FALLBACK` unless the statement is accepted without one.

```surql
-- In a database at compatibility level 4
DEFINE TABLE product SCHEMAFULL;
DEFINE FIELD stock ON product TYPE string;
CREATE product:1 SET stock = '7';
CREATE product:2 SET stock = 'unknown';

DEFINE FIELD OVERWRITE stock ON product TYPE int
    MIGRATE EXISTING ROWS AS stock_to_int
    USING <int> $value FALLBACK 0;

SELECT * FROM product;
```

```surql title="Output"
[
	{ id: product:1, stock: 7 },
	{ id: product:2, stock: 0 }
]
```

A migration takes effect when the statement commits: a record is converted the first time it is read, and a background job rewrites every record of the table. The same clause adds a required field to a table that already has records, with the expression giving each record its value:

```surql
DEFINE FIELD reorder_level ON product TYPE int
    MIGRATE EXISTING ROWS AS add_reorder_level USING 10;
```

To remove the fields that the table no longer defines from every record, use `REMOVE UNDECLARED FIELDS` on [`ALTER TABLE`](/docs/reference/query-language/statements/alter/table.md):

```surql
-- Setup from the example above
DEFINE TABLE product SCHEMAFULL;
DEFINE FIELD stock ON product TYPE string;
CREATE product:1 SET stock = '7';
CREATE product:2 SET stock = 'unknown';

ALTER TABLE product MIGRATE EXISTING ROWS AS drop_old_fields
    REMOVE UNDECLARED FIELDS;
```

A migration cannot change a field that something else is derived from: a field an index reads, a field of a view or of a view's source table, a field with `REFERENCE`, `INLINE` or `COMPUTED`, and `id`, `in` and `out`. For a field an index reads, remove the index, migrate the field, then define the index again.

`INFO FOR TABLE` lists the migrations a table has run under `migrations`, and names the fields whose stored values are all known to fit their definition under `guaranteed`.

### Running a schema script again

A schema script is often run more than once: on every deploy, by an application that applies its schema when it starts, or through [`surreal db import`](/docs/reference/cli/db/commands/import.md). `DEFINE FIELD OVERWRITE` gives the same result each time, but a transform applied twice usually does not. A table therefore records the name of every migration it has run, and skips a migration whose name it has already run.

```surql
DEFINE TABLE item SCHEMAFULL;
DEFINE FIELD price ON item TYPE int;
CREATE item:1 SET price = 5;

-- Prices move from whole units to cents
DEFINE FIELD OVERWRITE price ON item TYPE int
    MIGRATE EXISTING ROWS AS price_to_cents USING $value * 100 FALLBACK 0;

-- Running the same statement again leaves the prices as they are
DEFINE FIELD OVERWRITE price ON item TYPE int
    MIGRATE EXISTING ROWS AS price_to_cents USING $value * 100 FALLBACK 0;

SELECT price FROM item;
```

```surql title="Output"
[{ price: 500 }]
```

Without the name, the second statement would multiply the prices again, to `50000`. Running a name that the table has already run with a different transform is refused, because the name no longer says which transform the records went through. Choose a new name for each new migration, in the same way as the migration IDs of other schema tools.

The names stay with the table and appear under `migrations` in `INFO FOR TABLE`, so they also record which conversions the table's records have been through. This is also why `ALTER TABLE ... REMOVE UNDECLARED FIELDS` takes a name, although running it twice would do no harm. A migration cannot be undone: once it has run, the old values are gone.

### When a migration is required

A database has a [compatibility level](/docs/reference/query-language/statements/define/database.md#compatibility-level), `3` or `4`. In a database at level 4, a `SCHEMAFULL` table that holds records refuses a change to a field unless every value the old definition accepted also fits the new one, or the statement carries `MIGRATE EXISTING ROWS`. Widening a type, such as `option<int>` to `option<int | string>`, needs no migration. Narrowing it, or changing it to another type, does:

```surql
-- In a database at compatibility level 4
DEFINE TABLE person SCHEMAFULL;
DEFINE FIELD age ON person TYPE int;
CREATE person:1 SET age = 37;

DEFINE FIELD OVERWRITE age ON person TYPE string;
```

```surql title="Error output"
'Cannot change field `age` of table `person`: the table is SCHEMAFULL in a database at compatibility level 4 and has rows, and the new definition does not accept every value the old one did: add MIGRATE EXISTING ROWS'
```

Adding a field counts as a change from no definition, under which every existing record holds `NONE`. A new field with a type that does not accept `NONE` therefore needs a migration that gives those records a value:

```surql
DEFINE FIELD stock ON item TYPE int
    MIGRATE EXISTING ROWS AS add_stock USING 0;
```

A field defined as `option<int>` needs no migration, and records can be given a value later. Changing it to `TYPE int` afterwards is still a narrowing, though, and needs `MIGRATE EXISTING ROWS` even when every record already holds an integer, because the check compares the two definitions and not the stored values.

The same comparison applies to a change that converts values, even one that can never fail. A stored `float` is not a `decimal`, and a stored `200u8` is not a `u16`, so changing `float` to `decimal` or `u8` to `u16` needs a migration that says how to convert them:

```surql
-- In a database at compatibility level 4
DEFINE TABLE item SCHEMAFULL;
DEFINE FIELD price ON item TYPE float;
CREATE item:1 SET price = 0.1f + 0.2f;

DEFINE FIELD OVERWRITE price ON item TYPE decimal;
//- 'Cannot change field `price` of table `item`: the table is SCHEMAFULL in a database at compatibility level 4 and has rows, and the new definition does not accept every value the old one did: add MIGRATE EXISTING ROWS'

DEFINE FIELD OVERWRITE price ON item TYPE decimal
    MIGRATE EXISTING ROWS AS price_to_decimal USING <decimal> $value FALLBACK 0dec;
SELECT price FROM item;
//- [{ price: 0.3dec }]
```

The record held `0.30000000000000004f`, and the cast to `decimal` stored `0.3dec`. The order of a union matters for the same reason, because a value is converted to the first numeric type in the union that can hold it. `float` to `float | decimal` needs no migration, while `float` to `decimal | float` does, since it would turn a stored `1.5f` into `1.5dec`. `number` accepts every numeric value unchanged, so changing any numeric type to `number` needs no migration.

A type defined with [`DEFINE TYPE`](/docs/reference/query-language/statements/define/type.md) is checked the other way. Redefining it with `OVERWRITE` checks the values that its fields already hold, on every table, and it has no `MIGRATE EXISTING ROWS` clause. See [Changing a type that is in use](/docs/reference/query-language/statements/define/type.md#changing-a-type-that-is-in-use).

At level 4, [`REMOVE FIELD`](/docs/reference/query-language/statements/remove.md#behaviour-after-removal) on a `SCHEMAFULL` table also removes the field's stored values, so a field defined again later with the same name starts empty.

At level 3, a table accepts any change to its fields, as in SurrealDB 3.x, and records written before the change keep the values they held. `MIGRATE EXISTING ROWS` works at both levels, and a `SCHEMALESS` table accepts any change at either level.

### While a migration runs

A migration commits in one transaction, but the background job that rewrites the stored records can take much longer. During that time, some records are stored in the old form and some in the new form. The rules below say what reads, exports and writes see during that time.

**Reads.** A read converts each record that the job has not rewritten yet before the query sees it. This applies to every way of reading a record: a scan, a filter, `ORDER BY`, `GROUP BY`, a read by record ID, a record link and a graph traversal. A transaction that starts after the migration commits sees every record in the new form. A transaction that started before it sees every record in the old form. No transaction sees a mix of the two. The conversion is the same `USING` expression that the job applies, so a record that a read converts is identical to the same record after the job rewrites it.

**Exports.** An export reads records in the same way, so an export that you take during a migration contains the converted values. An import of that export gives the same values that a query returned when you took the export.

**Events, live queries and change feeds.** A conversion changes how a record is stored, not its value. Thus no event, live query or change feed entry occurs when a read converts a record or when the job rewrites it. When you write to a record that the job has not rewritten yet, the write applies to the converted record, and the change feed records the result. With `INCLUDE ORIGINAL`, the original that the change feed records is the converted record, as a read returned it before the write. Change feed entries written before the migration keep the values that they held.

**Writes.** A write stores the record in the new form, so the job has no more work to do for that record. The job rewrites the table in small batches, and each batch is a short transaction of its own. When a write conflicts with a batch, the write takes priority. The job does not cause a write that commits first to fail. It cancels its batch, waits briefly, and tries again with a smaller batch. If the batch commits first, the conflicting transaction fails with a retryable error, as with any two transactions that write the same record. See [Write conflicts and retries](/docs/learn/querying/concepts-and-guides/transactions.md#write-conflicts-and-retries) for how a client or the server runs it again.

A record that a transaction writes in the old form after the job passed it is converted each time that it is read. You do not have to wait for the job before you use the table. To see the progress of the job, use `INFO FOR TABLE`.

## Computed fields

_(since v3.0.0)_

A `COMPUTED` field is not stored. Its value is calculated from its expression every time the field is read, so it always reflects the rest of the record as it is now:

```surql
DEFINE FIELD can_drive ON person COMPUTED age >= 18;

CREATE person:one SET age = 17;
UPDATE person:one SET age = 18;
SELECT age, can_drive FROM person:one;
```

```surql title="Output"
[
	{
		age: 18,
		can_drive: true
	}
]
```

Compared with a [`VALUE` clause](#using-the-value-clause-to-set-a-fields-value), which is calculated when a record is written and then stored, a computed field needs no update to stay current and takes up no storage, but it is calculated again on every read.

A computed field takes only the `TYPE`, `PERMISSIONS` and `COMMENT` clauses, as the computed field syntax above shows. It must be a top-level field, so it cannot be defined on the `id` field or on a nested path such as `metadata.can_drive`, and a statement that sets it is ignored, because the value always comes from the expression.

The body of a computed field has further rules about what it may read and write, described in [Restrictions on computed fields](#restrictions-on-computed-fields).

> [!NOTE]
> Before SurrealDB 3.0.0, computed values were written with a data type called a `future`. See [the page on futures](/docs/reference/query-language/language-primitives/data-types/futures.md) for those versions.

## Defining a literal on a field
A field can also be defined as a [literal type](/docs/reference/query-language/language-primitives/data-types/literals.md), by specifying one or more possible values and/or permitted types.

```surql
DEFINE FIELD coffee
  ON TABLE order TYPE "regular" | "large" | { special_order: string };

CREATE order:good SET coffee = { special_order: "Venti Quadruple Ristretto Half-Decaf Soy Latte with 4 pumps of sugar-free vanilla syrup" };
CREATE order:bad SET coffee = "small";
```

```surql title="Output"
-------- Query --------

[
	{
		coffee: {
			special_order: 'Venti Quadruple Ristretto Half-Decaf Soy Latte with 4 pumps of sugar-free vanilla syrup'
		},
		id: order:good
	}
]

-------- Query --------
"Found 'small' for field `coffee`, with record `order:bad`, but expected a 'regular' | 'large' | { special_order: string }"
```

One more example of a literal containing settings for a [full text search](/docs/learn/data-models/full-text-search/overview.md) filter:

```surql
DEFINE FIELD filter ON TABLE search_settings TYPE
      "None"
    | { type: "Ascii" }
    | { type: "EdgeNgram", from: int, to: int }
    | { type: "Lowercase" }
    | { type: "Ngram", from: int, to: int }
    | { type: "Snowball", language: string }
    | { type: "Uppercase" };
```

## Comments

A `COMMENT` documents how the field is meant to be used. Comments can be useful when describing how someone (or an agent) would write a query: comparison rules, units, allowed values, or invariants. The comment is stored with the definition and shown by [`INFO`](/docs/reference/query-language/statements/info.md). See also [Comments on definitions](/docs/reference/query-language/statements/define/overview.md#comments-on-definitions).

```surql
DEFINE FIELD day ON meeting TYPE date
	COMMENT "Calendar day of the meeting, with no time zone. Compare it with a date literal (day >= pd'2026-07-10'), or cast a datetime first (<date> time::now()), because a datetime never equals a date.";

DEFINE FIELD is_organizer ON attended TYPE bool
	COMMENT "True if this person ran the meeting, false if they only attended. Exactly one attendee per meeting has it true.";

DEFINE FIELD score ON review TYPE float
	COMMENT "Rating from 0.0 to 5.0 inclusive. Always assert score >= 0 AND score <= 5.";
```

## Asserting rules on fields

You can take your field definitions even further by using asserts. Assert can be used to ensure that your data remains consistent. For example you can use asserts to ensure that a field is always a valid email address, or that a number is always positive.

```surql
-- Give the user table an email field. Store it in a string
DEFINE FIELD email ON TABLE user TYPE string
  -- Check if the value is a properly formatted email address
  ASSERT string::is_email($value);
```

To limit the length of a string, compare its length in the assertion:

```surql
DEFINE FIELD username ON TABLE user TYPE string
  ASSERT $value.len() <= 16;

CREATE user:1 SET username = 'a_much_too_long_username';
```

```surql title="Error output"
"Found 'a_much_too_long_username' for field `username`, with record `user:1`, but field must conform to: $value.len() <= 16"
```

A field of type `record<author>` accepts the ID of a record that does not exist. To refuse one, assert that the record exists:

```surql
DEFINE FIELD author ON TABLE book TYPE record<author>
  ASSERT $value.exists();

CREATE author:ann;
CREATE book:1 SET author = author:ann;
CREATE book:2 SET author = author:nobody;
```

```surql title="Error output"
"Found author:nobody for field `author`, with record `book:2`, but field must conform to: $value.exists()"
```

The assertion is checked when the field is written, so deleting `author:ann` later leaves `book:1` linking to a record that no longer exists. To prevent that as well, add [`REFERENCE ON DELETE REJECT`](/docs/reference/query-language/language-primitives/record-references.md) to the field.

As the `ASSERT` clause expects an expression that returns a boolean, an assertion with a custom message can be manually created by returning `true` in one case and using a [`THROW`](/docs/reference/query-language/statements/throw.md) clause otherwise.

```surql
DEFINE FIELD num ON data TYPE int ASSERT {
    IF $input % 2 = 0 {
        RETURN true
    } ELSE {
        THROW "Tried to make a " + <string>$this + " but `num` field requires an even number"
    }
};

CREATE data:one SET num = 11;
```

```surql title="Error output"
'An error occurred: Tried to make a { id: data:one, num: 11 } but `num` field requires an even number'
```

### Making a field `READONLY`

The `READONLY` clause can be used to prevent any updates to a field. This is useful for fields that are automatically updated by the system. To make a field `READONLY`, add the `READONLY` clause to the `DEFINE FIELD` statement. As seen in the example below, the `created` field is set to `READONLY`.

```surql
DEFINE FIELD created ON resource VALUE time::now() READONLY;
```

## Using regex to validate a string

You can use the `ASSERT` clause to apply a regular expression to a field to ensure that it matches a specific pattern. In the example below, the `ASSERT` clause is used to ensure that the `countrycode` field is always a valid ISO-3166 country code.

```surql
-- Specify a field on the user table
DEFINE FIELD countrycode ON user TYPE string
	-- Ensure country code is ISO-3166
	ASSERT $value = /[A-Z]{3}/
	-- Set a default value if empty
	VALUE $value OR $before OR 'GBR'
;
```

## Array with allowed values

By using an Access Control List as an example we can show how we can restrict what values can be stored in an array. In this example we are using an array to store the permissions for a user on a resource. The permissions are restricted to a specific set of values.

```surql
-- An ACL can be applied to any kind of resource (record)
DEFINE FIELD resource ON TABLE acl TYPE record;
-- We associate the acl with a user using record<user>
DEFINE FIELD user ON TABLE acl TYPE record<user>;

-- The permissions for the user+resource will be stored in an array.
DEFINE FIELD permissions ON TABLE acl TYPE array
  -- The array must not be empty because at least one permission is required to make a valid ACL
  -- The items in the array must also be restricted to specific permissions
  ASSERT
      array::len($value) > 0
      AND $value ALLINSIDE ["create", "read", "write", "delete"];

-- SEE IT IN ACTION
-- 1: Add users
CREATE user:tobie SET firstName = 'Tobie', lastName = 'Hitchcock',
  email = 'Tobie.Hitchcock@surrealdb.com';
CREATE user:abc SET firstName = 'A', lastName = 'B',
  email = 'c@d.com';
CREATE user:efg SET firstName = 'E', lastName = 'F',
  email = 'g@h.com';

-- 2: Create a resource
CREATE document:SurrealDB_whitepaper SET
  name = "some messaging queue";

-- 3: Associate with ACL
CREATE acl SET user = user:tobie, resource = document:SurrealDB_whitepaper,
  permissions = ["create", "write", "read"];
CREATE acl SET user = user:abc, resource = document:SurrealDB_whitepaper,
  permissions = ["read", "delete"];

-- Test Asserts using failure examples
-- A: Create ACL without permissions field
CREATE acl:invalid SET
  user = user:efg,
  permissions = [], # FAIL - permissions must not be empty
  resource = document:SurrealDB_whitepaper;
-- B: Create acl with invalid permisson
CREATE acl:also_invalid SET
  user = user:efg,
  permissions = ["all"], # FAIL - This value is not allowed in the array
  resource = document:SurrealDB_whitepaper;
```

## GraphQL names and deprecation

_(since v3.1.0)_

`GRAPHQL_ALIAS` sets the name a field has in the [GraphQL schema](/docs/learn/querying/graphql/overview.md), in place of the field name. The alias is used on the object type, the create and update input types, and the filter. It must be a valid GraphQL name, matching `[_A-Za-z][_0-9A-Za-z]*`, and any other value is rejected when the field is defined.

`GRAPHQL_DEPRECATED` takes a reason, which the schema adds to the start of the field's description as `[Deprecated: reason]`. The `isDeprecated` flag in GraphQL introspection stays false.

```surql
DEFINE FIELD first_name ON person TYPE option<string>
	GRAPHQL_ALIAS "firstName"
	GRAPHQL_DEPRECATED "Use name instead";
```

A GraphQL query then selects the field as `firstName`:

```graphql title="Query"
{ persons { id firstName } }
```

```json title="Output"
{"data":{"persons":[{"id":"person:amy","firstName":null}]}}
```

Fields defined with `READONLY` or `COMPUTED` are not part of the create and update input types, because a mutation cannot set them. A `COMPUTED` field appears in the object type only if it has a `TYPE`.

## Setting permissions on fields

By default, the permissions on a field will be set to `FULL` unless otherwise specified. The table is the main access gate, while field permissions only narrow further when you need to (for example, when hiding a password). With `FULL`, a field follows the [table](/docs/reference/query-language/statements/define/table.md#defining-permissions)'s rules without adding its own. Tables default the other way: omitting table `PERMISSIONS` in a `DEFINE` statement stores `PERMISSIONS NONE`.

```surql
DEFINE FIELD some_info ON TABLE some_table TYPE string;
INFO FOR TABLE some_table;
```

```surql title="Output"
{
	events: {},
	fields: {
		some_info: 'DEFINE FIELD some_info ON some_table TYPE string PERMISSIONS FULL'
	},
	indexes: {},
	lives: {},
	tables: {}
}
```

You can set permissions on fields to control who can perform operations on them using the `PERMISSIONS` clause. The `PERMISSIONS` clause can be used to set permissions for `SELECT`, `CREATE`, and `UPDATE` operations. The `DELETE` operation only relates to records and, as such, is not available for fields.

Like table permissions, field permissions apply to [record users](/docs/learn/security/authentication/users.md#record-users) (and guests when enabled), not to [system users](/docs/learn/security/authentication/users.md#system-users) such as `root`. A query run as `root`, including one in SurrealDB Studio or `surreal db sql` signed in as root, therefore still returns a field defined with `PERMISSIONS FOR select NONE`. To check that a field is hidden, sign in as a record user and run the query again.

```surql
-- Set permissions for the email field
DEFINE FIELD email ON TABLE user
  PERMISSIONS
    FOR select WHERE published=true OR user=$auth.id
    FOR update WHERE user=$auth.id OR $auth.role="admin";
```

### Checking the new value of a field

Inside a field's `PERMISSIONS FOR update` clause, `$before` holds the value the field had before the statement and `$after` the value it would have afterwards. A condition on `$after` can therefore decide whether a particular new value is allowed, such as an owner that must stay the user making the change.

```surql
DEFINE TABLE doc SCHEMAFULL PERMISSIONS FULL;
DEFINE FIELD owner ON doc TYPE record<user>
  PERMISSIONS FOR select, create FULL
  FOR update WHERE $after = $auth.id;
DEFINE FIELD title ON doc TYPE string;
```

A record user signed in as `user:ann` who updates `doc:one` to hand it to another user does not receive an error. The field keeps its previous value and the rest of the statement goes ahead:

```surql
UPDATE doc:one SET owner = user:bob RETURN AFTER;
```

```surql title="Output when doc:one is owned by user:ann"
[{ id: doc:one, owner: user:ann, title: 'x' }]
```

A table-level `FOR update` permission does not offer this. The condition is evaluated against the record itself, once before the update and again on the updated record, so a table defined with `PERMISSIONS FOR update WHERE owner = $auth.id` also stops an owner from handing a record to someone else. In that case the whole `UPDATE` returns an empty array and changes nothing.

## Interacting with other fields of the same record

While a `DEFINE TABLE` statement represents a template for any subsequent records to be created, a `DEFINE FIELD` statement pertains to concrete field data of a record. As such, a `DEFINE FIELD` statement gives access to the record's other fields through their names, as well as the current field through the [`$value`](/docs/reference/query-language/language-primitives/parameters.md#value) parameter.

```surql
DEFINE TABLE person SCHEMAFULL;

DEFINE FIELD first_name
  ON TABLE person TYPE string VALUE string::lowercase($value);
DEFINE FIELD last_name 
  ON TABLE person TYPE string VALUE string::lowercase($value);
DEFINE FIELD name      
  ON TABLE person             VALUE first_name + ' ' + last_name;

-- Creates a `person` with the name "bob bobson"
CREATE person SET first_name = "BOB", last_name = "BOBSON";
```

The `$this` parameter gives access to the entire record on which a field is defined.

```surql
DEFINE FIELD extra_self ON TABLE person VALUE $this;
CREATE person:one SET name = "Little person", age = 6;
```

```surql title="Output"
[
	{
		age: 6,
		extra_self: {
			age: 6,
			id: person:one,
			name: 'Little person'
		},
		id: person:one,
		name: 'Little person'
	}
]
```

### Reading the record with `$this`

`$this.start` and a bare `start` read the same field. `$this` is useful when a clause needs the record as a whole, or when a clause holds a subquery, where a bare field name refers to the subquery's own records.

An `ASSERT` that compares two fields reads the record as it will be stored, on `CREATE` as well as on `UPDATE`:

```surql
DEFINE FIELD start ON booking TYPE datetime;
DEFINE FIELD end ON booking TYPE datetime ASSERT $value > $this.start;

CREATE booking:1 SET start = d'2026-01-01', end = d'2026-01-02';
//- [{ end: d'2026-01-02T00:00:00Z', id: booking:1, start: d'2026-01-01T00:00:00Z' }]

CREATE booking:2 SET start = d'2026-01-02', end = d'2026-01-01';
```

```surql title="Error output"
"Found d'2026-01-01T00:00:00Z' for field `end`, with record `booking:2`, but field must conform to: $value > $this.start"
```

Because `$this` is an object, the [object functions](/docs/reference/query-language/functions/database-functions/object.md) work on it. This computed field lists the fields that a record holds:

```surql
DEFINE FIELD fields_set ON profile COMPUTED $this.keys();

CREATE profile:ann SET name = 'Ann', email = 'ann@example.com';
```

```surql title="Output"
[
	{
		email: 'ann@example.com',
		fields_set: ['email', 'id', 'name'],
		id: profile:ann,
		name: 'Ann'
	}
]
```

Inside a subquery, `$this` is the subquery's own current record. The record being written is one level up, so the subquery reads it through [`$parent`](/docs/reference/query-language/language-primitives/parameters.md#parent-this):

```surql
DEFINE FIELD namesakes ON person COMPUTED
    (SELECT VALUE id FROM person WHERE name = $parent.name AND id != $parent.id);

CREATE person:1 SET name = 'Ann';
CREATE person:2 SET name = 'Bo';
CREATE person:3 SET name = 'Ann';

SELECT id, namesakes FROM person;
```

```surql title="Output"
[
	{ id: person:1, namesakes: [person:3] },
	{ id: person:2, namesakes: [] },
	{ id: person:3, namesakes: [person:1] }
]
```

Writing `$this.name` in place of `$parent.name` compares each record in the subquery with itself, so every `namesakes` would be empty.

## Field evaluation order

_(since v3.3.0)_

When a record is written, field clauses run in **dependency order**: a field whose clause reads another field is evaluated after that field. `DEFAULT`, `VALUE`, and `COMPUTED` all take part, because each produces a value another field may need. Fields that do not read each other are evaluated in the order they were defined.

```surql
DEFINE FIELD z_src ON v TYPE int VALUE 10;
DEFINE FIELD a_dep ON v TYPE int VALUE z_src + 1;

CREATE v:1;
-- a_dep is 11
```

> [!NOTE]
> Before 3.3.0, fields were evaluated in name order. The example above failed because `a_dep` ran before `z_src` had a value, which meant that renaming a field could break a working schema. Nested fields are still evaluated after their parent.

`ASSERT` is different, because it produces no value and so imposes no order. Assertions run in a second pass, once every field holds its final value, so a clause that reads a sibling always sees that sibling's stored value. Two fields asserting against each other is ordinary rather than a cycle:

```surql
DEFINE FIELD in ON follows TYPE record<user> ASSERT in != out;
DEFINE FIELD out ON follows TYPE record<user> ASSERT out != in;
```

A genuine cycle between value-producing clauses is rejected when the field is defined rather than when a record is written.

<img src="~/assets/img/diagrams/light/field-evaluation-order-light.webp" darkSrc="~/assets/img/diagrams/field-evaluation-order.webp" alt="Two passes over a record. In pass 1, z_src evaluates VALUE 10 to 10, then a_dep evaluates VALUE z_src + 1 to 11, because a_dep reads z_src. In pass 2, the ASSERT clauses on in and out run once every field holds its final value, so two assertions that read each other are not a cycle. Before 3.3.0, fields ran in name order, so a_dep ran before z_src had a value." />

> [!NOTE]
> Computed fields are also populated on the records that [events](/docs/reference/query-language/statements/define/event.md), [live queries](/docs/reference/query-language/statements/live-select.md), and changefeeds receive. Before 3.3.0, `$before` and `$after` reported every computed field as `NONE`.

## Using `IF NOT EXISTS` clause

The `IF NOT EXISTS` clause can be used to define a field only if it does not already exist. You should use the `IF NOT EXISTS` clause when defining a field in SurrealDB if you want to ensure that the field is only created if it does not already exist. If the field already exists, the `DEFINE FIELD` statement will return an error.

It's particularly useful when you want to safely attempt to define a field without manually checking its existence first.

On the other hand, you should not use the `IF NOT EXISTS` clause when you want to ensure that the field definition is updated regardless of whether it already exists. In such cases, you might prefer using the `OVERWRITE` clause, which allows you to define a field and overwrite an existing one if it already exists, ensuring that the latest version of the definition is always in use.

```surql
-- Create a field if it does not already exist
DEFINE FIELD IF NOT EXISTS email ON TABLE user TYPE string;
```

## Using `OVERWRITE` clause

The `OVERWRITE` clause can be used to define a field and overwrite an existing one if it already exists. You should use the `OVERWRITE` clause when you want to modify an existing field definition. If the field already exists, the `DEFINE FIELD` statement will overwrite the existing definition with the new one.

```surql
-- Overwrite the current field definition if it already exists
DEFINE FIELD OVERWRITE example ON TABLE user TYPE string;
```

## Defining a reference

A field that is a record link (type `record`, `option<record>`, `array<record<person>>`, and so on) can be defined as a `REFERENCE`. If this clause is used, any linked to record will be able to define a computed field of its own using the `<~` syntax, which will be aware of the incoming links.

For more information, see [the page in the datamodel section on references](/docs/reference/query-language/language-primitives/record-references.md).

`REFERENCE` is only accepted on a field at the root of the record. A nested field such as `meta.thumbnail` or `items.*.object` is refused:

```surql
DEFINE TABLE file;
DEFINE FIELD meta ON file TYPE object;
DEFINE FIELD meta.thumbnail ON file TYPE option<record<storage_object>>
	REFERENCE;
```

```surql title="Error output"
'Cannot use the `REFERENCE` keyword on nested field `meta.thumbnail`. Specify a referencing field at the root level instead.'
```

To keep a reference that belongs with nested data, define it as a root-level field, such as `DEFINE FIELD thumbnail ON file TYPE option<record<storage_object>> REFERENCE;`.

Where the links sit inside an array of objects, a root-level array field can collect them with a `VALUE` clause. The clause runs on every write, so the array always holds the links that the nested objects hold, and the `REFERENCE` on it applies to each of them.

```surql
DEFINE TABLE storage_object SCHEMAFULL;
DEFINE FIELD name ON storage_object TYPE string;
DEFINE FIELD media ON storage_object COMPUTED <~media_item;

DEFINE TABLE media_item SCHEMAFULL;
DEFINE FIELD video ON media_item TYPE object;
DEFINE FIELD video.captions ON media_item TYPE option<array<object>>;
DEFINE FIELD video.captions.*.lang ON media_item TYPE string;
DEFINE FIELD video.captions.*.object ON media_item TYPE record<storage_object>;
-- Collects every video.captions.*.object, or an empty array when there are no captions
DEFINE FIELD caption_objects ON media_item TYPE array<record<storage_object>>
	VALUE video.captions.*.object ?? []
	REFERENCE ON DELETE REJECT;

CREATE storage_object:en SET name = 'captions-en.vtt';
CREATE storage_object:fr SET name = 'captions-fr.vtt';
CREATE media_item:intro SET video.captions = [
	{ lang: 'en', object: storage_object:en },
	{ lang: 'fr', object: storage_object:fr }
];

DELETE storage_object:fr;
//- 'Cannot delete `storage_object:fr` as it is referenced by `media_item:intro` with an ON DELETE REJECT clause'

storage_object:fr.media;
//- [media_item:intro]
```

Removing the caption from the nested array removes the link from `caption_objects` as well, and the delete then succeeds:

```surql
-- Setup from the example above
DEFINE TABLE storage_object SCHEMAFULL;
DEFINE FIELD name ON storage_object TYPE string;
DEFINE FIELD media ON storage_object COMPUTED <~media_item;

DEFINE TABLE media_item SCHEMAFULL;
DEFINE FIELD video ON media_item TYPE object;
DEFINE FIELD video.captions ON media_item TYPE option<array<object>>;
DEFINE FIELD video.captions.*.lang ON media_item TYPE string;
DEFINE FIELD video.captions.*.object ON media_item TYPE record<storage_object>;
DEFINE FIELD caption_objects ON media_item TYPE array<record<storage_object>>
	VALUE video.captions.*.object ?? []
	REFERENCE ON DELETE REJECT;

CREATE storage_object:en SET name = 'captions-en.vtt';
CREATE storage_object:fr SET name = 'captions-fr.vtt';
CREATE media_item:intro SET video.captions = [
	{ lang: 'en', object: storage_object:en },
	{ lang: 'fr', object: storage_object:fr }
];

UPDATE media_item:intro
	SET video.captions = video.captions.filter(|$c| $c.lang != 'fr');
DELETE storage_object:fr;
```

`ON DELETE REJECT` and `ON DELETE CASCADE` work with this pattern. `ON DELETE UNSET` does not: it removes the link from `caption_objects`, but the `VALUE` clause runs again on that update and reads the link back from the nested object, so the record is deleted while `video.captions` still links to it.

### Keeping a list of references with `MATERIALIZE INTO`

_(since v4.0.0)_

A `<~` lookup finds the records that reference a record each time it is read. `MATERIALIZE INTO` stores that list instead, in a field of the referenced record, and keeps it up to date in the same transaction as each write to the referencing field. Reading the list is then a plain field read.

```surql
DEFINE TABLE author SCHEMAFULL;
DEFINE FIELD name ON author TYPE string;
DEFINE FIELD posts ON author TYPE array<record<post>>
	DEFAULT [] READONLY;

DEFINE TABLE post SCHEMAFULL;
DEFINE FIELD title ON post TYPE string;
DEFINE FIELD author ON post TYPE record<author>
	REFERENCE ON DELETE CASCADE
	MATERIALIZE INTO author.posts;

CREATE author:a, author:b SET name = 'x';
CREATE post:3 SET author = author:a, title = 'c';
CREATE post:1 SET author = author:a, title = 'a';
CREATE post:2 SET author = author:b, title = 'b';
UPDATE post:1 SET author = author:b;

SELECT id, posts FROM author;
```

```surql title="Output"
[
	{ id: author:a, posts: [post:3] },
	{ id: author:b, posts: [post:1, post:2] }
]
```

The list holds each record once, in ascending order of record ID, which is the order a `<~` lookup returns. Creating a referencing record adds it to the list, changing the reference moves it from one list to the other, and deleting it removes it. With a field that holds an array of references, each element is handled in the same way. A `WHERE` condition, such as `MATERIALIZE INTO author.posts WHERE archived != true`, lists only the referencing records for which it is true, and a write that changes the result of the condition adds or removes the record. The condition must not have effects, in the same way as the [clauses that must not have effects](#clauses-that-must-not-have-effects).

The destination field must already be defined on the referenced table, at the top level, as a `READONLY` field of type `array<record<...>>` of the referencing table with no length limit. It cannot be `id`, a `COMPUTED` field or the referencing field itself, and only one `MATERIALIZE INTO` clause can fill it. A statement that does not meet these rules is refused, for example:

```surql title="Error output"
'An error occurred: MATERIALIZE INTO author.plain requires field `plain` to be READONLY: the engine keeps its list'
```

Because the destination is `READONLY`, a statement that writes to it directly fails. While the clause fills it, the destination field cannot be redefined, altered or removed, and its table cannot be removed. Removing the clause, for example with `ALTER FIELD ... DROP REFERENCE`, leaves the lists in place as ordinary data.

`DEFINE FIELD` fills the lists from the records that already exist, within the same statement. Updates to a list do not fire the [events](/docs/reference/query-language/statements/define/event.md) of the referenced table, but live queries and change feeds see them like any other write. An import restores the lists with the records.

## Defining a `TYPE` for the `id` field

The `DEFINE FIELD` statement can be defined for the `id` field to specify the acceptable type of ID.

```surql
DEFINE FIELD id ON TABLE product TYPE string;
DEFINE FIELD id ON TABLE invoice TYPE int;
DEFINE FIELD id ON TABLE session TYPE uuid;
```

Complex IDs can be specified as well.

```surql
-- using multiple data types for a Complex Record ID
DEFINE FIELD id
  ON TABLE log TYPE [record, "info" | "warn" | "error", datetime];

-- Incorrect ID format, generates an error
CREATE log:bad SET level = "info", time = time::now(), message = "Database started";

-- Acceptable ID format
CREATE log:[user:one, "info", time::now()] SET message = "Database started";
```

```surql title="Output"
-------- Query --------

"Couldn't coerce value for field `id` of `log:bad`: Expected `[record, 'info' | 'warn' | 'error', datetime]` but found `'bad'`"

-------- Query --------

[
	{
		id: log:[
			user:one,
			'info',
			d'2025-03-25T03:36:16.323Z'
		],
		message: 'Database started'
	}
]
```

### Definitions inside the `id` field

_(since v4.0.0)_

An object or array ID can also be described with a definition for each of its parts, such as `id.parent` or `id[0]`, after `id` itself is defined. The `TYPE` of each such definition is checked against the matching part of the record ID when the record is created, and a record whose ID does not fit is refused with an error that names the definition:

```surql
DEFINE TABLE test SCHEMAFULL;
DEFINE FIELD id ON test TYPE object;
DEFINE FIELD id.id ON test TYPE string;
DEFINE FIELD id.parent ON test TYPE record<accounts>;

CREATE test:{ id: 'aaa', parent: accounts:0 };
CREATE test:{ id: 1, parent: accounts:0 };
```

```surql title="Error output"
"Couldn't coerce value for field `id.id` of `test:{ id: 1, parent: accounts:0 }`: Expected `string` but found `1`"
```

The record ID is checked and stored as it was written. An `ASSERT` on such a definition is checked in the same way, but a `VALUE`, `DEFAULT` or `PERMISSIONS` clause on it has no effect, because a record ID does not change after the record is created.

A definition inside `id` needs a definition of `id` itself, and the statement is refused when the table has none:

```surql
DEFINE FIELD id.id ON other TYPE int;
```

```surql title="Error output"
"Cannot define field `id.id`: the field `id` it is nested in is not defined. Define `id` first"
```

### Naming the components of an array id

_(since v4.0.0)_

The elements of an array record ID can be given names in the type of the `id` field. Each name becomes a read-only field that holds the matching element of the ID, so `city` reads `id[0]` and `time` reads `id[1]`. The names appear in the output of `SELECT *`, but they are not stored in the body of the record.

```surql
DEFINE FIELD id ON reading TYPE [city: string, time: datetime];

CREATE reading SET city = 'London', time = d'2024-01-01T00:00:00Z', temp = 5.1;
CREATE reading SET city = 'London', time = d'2024-01-02T00:00:00Z', temp = 6.3;
CREATE reading SET city = 'Rome', time = d'2024-01-02T00:00:00Z', temp = 11.0;

SELECT * FROM reading
WHERE city = 'London'
	AND time >= d'2024-01-02T00:00:00Z'
	AND time < d'2024-01-03T00:00:00Z';
```

```surql title="Output"
[
	{
		city: 'London',
		id: reading:[
			'London',
			d'2024-01-02T00:00:00Z'
		],
		temp: 6.3f,
		time: d'2024-01-02T00:00:00Z'
	}
]
```

A `WHERE` clause on the named components is read as a range over the record keys, so the query reads only the matching part of the table instead of scanning all of it. The plan uses the longest run of equality tests from the first component, followed by one range on the next component, and `EXPLAIN` shows it as a `KeyRangeScan`. A `WHERE` clause on a component with `IN` or `OR` is read as several ranges. The remaining conditions of the clause, such as `temp > 6`, are still applied to each record that the range returns, and a condition on a field that is not a component reads the whole table as before.

`ORDER BY` on a component that follows the tests in the `WHERE` clause can be read from the scan in key order. A query for the latest records of one city reads the keys backwards from the end of that city's range, so `LIMIT` stops the scan early:

```surql
-- Setup from the example above
DEFINE FIELD id ON reading TYPE [city: string, time: datetime];

CREATE reading SET city = 'London', time = d'2024-01-01T00:00:00Z', temp = 5.1;
CREATE reading SET city = 'London', time = d'2024-01-02T00:00:00Z', temp = 6.3;
CREATE reading SET city = 'Rome', time = d'2024-01-02T00:00:00Z', temp = 11.0;

SELECT * FROM reading WHERE city = 'London'
ORDER BY time DESC LIMIT 10;
```

A datetime in a record key is compared to the whole second, so the planner keeps the sort and the filter for a `datetime` component, and these decide the final order and the final result.

#### Writing records

A record gets its ID from an explicit ID in the statement, or else from the values of all components set with `SET` or `CONTENT`, or else from a `DEFAULT` on the `id` field. The values of the components are taken into the ID, and the named fields still read them back. A component that is given both in the ID and in `SET` has to have the same value in both places.

```surql
CREATE reading:['London', d'2024-02-01T00:00:00Z'] SET city = 'Rome';
//- "Found 'Rome' for the `city` field, but it is part of the record id of `reading` and does not match it"

CREATE reading:['London'];
//- 'The record id of `reading` has the components [city, time], but 1 value was given'

CREATE reading SET city = 'London', temp = 3;
//- 'Cannot create a record in `reading` without the record id component `time`: set `time`, give the record id, or define a DEFAULT on the `id` field'

CREATE reading SET city = 'London', time = 'yesterday';
//- "Couldn't coerce value for the record id component `time` of `reading`: Expected `datetime` but found `'yesterday'`"
```

An `UPDATE` cannot change a component, because a component is part of the ID that the record is stored under.

#### Rules for components

- A component can be a `string`, `int`, `datetime`, `uuid`, `duration`, `bool` or `record`. These are the types that keep their order when stored in a key, so other types, such as `decimal`, are refused when the field is defined.
- An `int` component accepts only whole numbers. A float or decimal with no fractional part, such as `2.0`, is converted to an `int`, and any other number is refused.
- A name has to be a plain identifier of ASCII letters, digits and underscores that does not start with a digit, and it cannot be the name of another field of the table.
- The names can be used only as the whole type of the `id` field. They are not accepted inside a type such as `array<[city: string]>`.
- A component can be indexed like any other field, for example with `DEFINE INDEX by_time ON reading FIELDS time`.

```surql
DEFINE FIELD id ON reading TYPE [price: decimal, time: datetime];
```

```surql title="Error output"
'The record id component `price` of `reading` cannot have the type `decimal`: only string, int, datetime, uuid, duration, bool and record components keep their order in storage'
```

#### Existing records

When the statement is run on a table that already has records, every record is checked inside the same transaction. The statement is refused, and nothing is defined, if a record does not fit the type, or if it stores a field with the name of a component and a different value from its ID.

```surql
CREATE reading:['London', d'2024-01-01T00:00:00Z'] SET city = 'Rome';
DEFINE FIELD id ON reading TYPE [city: string, time: datetime];
```

```surql title="Error output"
"Cannot give `reading` the record id [city: string, time: datetime]: the record reading:['London', d'2024-01-01T00:00:00Z'] stores a `city` field that differs from its record id. Remove it first, for example with UPDATE reading UNSET city"
```

> [!WARNING]
> A table whose `id` field names its components cannot be read by an earlier release. Define the names only when every node of the deployment runs SurrealDB 4.0 or later, because a node that runs an earlier release cannot load the table. Nothing is stored differently, so removing the names makes the table readable again.

Removing the names, with `REMOVE FIELD id`, or with `ALTER FIELD` or `DEFINE FIELD OVERWRITE` and a type without names, is refused while the table holds records whose keys are stored in a different order from their record IDs. This happens with a `datetime` component, because a datetime in a key is compared to the whole second, so `d'2024-01-01T00:00:00.500Z'` is stored before `d'2024-01-01T00:00:00Z'`. Only the names let `ORDER BY id` return such records in the right order. Delete those records, or copy them into another table, before removing the names:

```surql
DEFINE FIELD id ON coarse TYPE [at: datetime];
CREATE coarse SET at = d'2024-01-01T00:00:00Z';
CREATE coarse SET at = d'2024-01-01T00:00:00.500Z';
REMOVE FIELD id ON coarse;
```

```surql title="Error output"
"Cannot remove the names from the record id of `coarse`: it holds coarse:[d'2024-01-01T00:00:00.500Z'] and coarse:[d'2024-01-01T00:00:00Z'], whose keys are stored in the opposite order to their record ids, which only the names account for. Delete those records, or copy them into a table with the record id you want, first"
```

### `ASSERT` and `DEFAULT` on `id`

_(since v3.2.0)_

`ASSERT` on the `id` field is evaluated like any other field assertion. Inside the assertion, `$value` is the whole record id; use `id.id()` (or `record::id($value)`) to inspect the key portion. Assertions run on create for generated, default-supplied, and explicitly supplied ids, and are skipped on update and under `OPTION IMPORT`.

`DEFAULT` supplies the record id when none is given in `CREATE` or `INSERT`, evaluated in the session context and coerced to the declared type. An explicit id in the statement always wins. `DEFAULT ALWAYS` is not allowed on `id`.

```surql
DEFINE FIELD id ON user TYPE string DEFAULT rand::ulid() ASSERT id.id().is_ulid();
CREATE user SET name = 'Ada';
```

`VALUE`, `REFERENCE`, `COMPUTED`, `READONLY`, `FLEXIBLE`, and non-key `TYPE` clauses are forbidden on `id`, a restriction which applies to [`ALTER FIELD`](/docs/reference/query-language/statements/alter/field.md) statements as well.

## Declaring a SQL type

_(since v4.0.0)_

The `SQL TYPE` clause records the type that a SQL column of the field would have, in the PostgreSQL, MySQL or DynamoDB dialect, and checks every write of the field against it. The type is a string, such as `'varchar(20)'` or `'numeric(10,2)'`, after the dialect keyword `POSTGRESQL`, `MYSQL` or `DYNAMODB`. A `CREATE TABLE` sent over the [Postgres](/docs/reference/protocols/postgres-protocol.md) or [MySQL](/docs/reference/protocols/mysql-protocol.md) wire protocol sets the clause on each column it defines, and those protocols report the declared type to their clients.

```surql
DEFINE TABLE customer SCHEMAFULL;
DEFINE FIELD name ON customer TYPE string
	SQL TYPE POSTGRESQL 'varchar(20)';
DEFINE FIELD country ON customer TYPE option<string>
	SQL TYPE POSTGRESQL 'char(2)';
DEFINE FIELD balance ON customer TYPE option<decimal>
	SQL TYPE POSTGRESQL 'numeric(10,2)';
DEFINE FIELD address ON customer TYPE option<string>
	SQL TYPE POSTGRESQL 'inet';

CREATE customer:1 SET
	name = 'Ada Lovelace',
	country = 'GB  ',
	balance = 12.345dec,
	address = '10.0.0.1/32';
```

```surql title="Output"
[{ address: '10.0.0.1', balance: 12.35dec, country: 'GB', id: customer:1, name: 'Ada Lovelace' }]
```

The declared type applies the rules of its dialect to the value that the field stores, after any `VALUE` clause, in every statement that writes the field. A text type limits the length of the value and a `char(n)` drops trailing spaces beyond its length, a `numeric(p,s)` rounds to its scale, and a type with a text form of its own, such as `inet`, checks and normalises that text. A value that does not fit is refused with the dialect's own message:

```surql
CREATE customer:2 SET name = 'Augusta Ada King, Countess of Lovelace';
//- 'value too long for type character varying(20) (field `name` of `customer:2`, SQL TYPE varchar(20))'

CREATE customer:3 SET name = 'Ada', balance = 123456789.5dec;
//- 'numeric field overflow (field `balance` of `customer:3`, SQL TYPE numeric(10,2))'

CREATE customer:4 SET name = 'Ada', address = 'not an address';
//- 'invalid input syntax for type inet: "not an address" (invalid network address "not an address") (field `address` of `customer:4`, SQL TYPE inet)'
```

The `TYPE` clause still decides which kind of value the field holds, and a declared SQL type does not replace it. Give the field a `TYPE` that matches the SQL type, such as `u8` for a MySQL `TINYINT UNSIGNED`, because a range that only the SQL type states is not checked. A `CREATE TABLE` over a wire protocol derives the `TYPE` from the column type as well as setting `SQL TYPE`.

`INFO FOR TABLE` shows the clause as part of the definition, and `INFO FOR TABLE ... STRUCTURE` gives it as an object with a `dialect` and a `text`:

```surql
(INFO FOR TABLE customer STRUCTURE).fields.filter(|$f| $f.name = 'name');
```

```surql title="Output"
[
	{
		kind: 'string',
		name: 'name',
		permissions: { create: true, select: true, update: true },
		readonly: false,
		sql_type: { dialect: 'POSTGRESQL', text: 'varchar(20)' },
		table: 'customer'
	}
]
```

[`ALTER FIELD`](/docs/reference/query-language/statements/alter/field.md) changes the declared type with `SQL TYPE` and removes it with `DROP SQL TYPE`.

## Clauses that must not have effects

The `COMPUTED`, `ASSERT`, `VALUE` and `DEFAULT` clauses of a field, and the `PERMISSIONS` clauses of a field, a table, a function or a parameter, are code that the database runs on behalf of whoever writes or reads a record. None of them may have an effect that lasts after the clause is evaluated. A clause is refused when it is defined if it:

- writes data, with `CREATE`, `UPDATE`, `UPSERT`, `INSERT`, `DELETE` or `RELATE`
- changes the schema, with a `DEFINE`, `ALTER` or `REMOVE` statement
- calls `sequence::nextval()`, except in a `VALUE` or `DEFAULT` clause
- waits with `SLEEP`
- calls a JavaScript function, `eval::surql()` or an [extension](/docs/reference/query-language/statements/define/extension.md) function, whose effects cannot be known when the clause is defined
- calls a closure whose body is not written in the clause, such as one held in a parameter, or passes one to a function or method such as `array::map()`. A closure written in the clause itself is checked like the rest of the clause, so `array::map([1, 2], |$v| $v * 2)` is allowed

```surql
DEFINE FIELD view_count ON article COMPUTED (UPDATE stats:articles SET views += 1);
```

```surql title="Error output"
'The COMPUTED clause must not have effects: `UPDATE` writes data'
```

A custom function that the clause calls is checked as well, including the functions that it calls in turn:

```surql
DEFINE FUNCTION fn::record_view() -> int { CREATE view_log SET at = time::now(); RETURN 1; };
DEFINE FIELD view_count ON article COMPUTED fn::record_view();
```

```surql title="Error output"
'The COMPUTED clause must not have effects: it calls `fn::record_view`, in whose body `CREATE` writes data'
```

A `VALUE` or `DEFAULT` clause runs once, when a record is written, so it may still draw the next number of a sequence. Random values and the clock are allowed in every clause:

```surql
DEFINE SEQUENCE invoice_number;
DEFINE FIELD number ON invoice TYPE int DEFAULT sequence::nextval('invoice_number');
DEFINE FIELD token ON invoice TYPE uuid DEFAULT rand::uuid();
DEFINE FIELD updated_at ON invoice TYPE datetime VALUE time::now();
```

A function that does not exist yet is not checked when the clause is defined, and a function can be redefined later to write. In both cases the clause fails with the same error each time it is evaluated and reaches the effect, and nothing is written. The same applies to a definition stored by an earlier release that allowed the effect. Check which definitions call a function before changing its body. See [Functions called from schema clauses](/docs/reference/query-language/statements/define/function.md#functions-called-from-schema-clauses).

A side effect that should happen when a record changes, such as a write to an audit log, belongs in [`DEFINE EVENT`](/docs/reference/query-language/statements/define/event.md), whose body may write.

> [!NOTE]
> These rules are new in SurrealDB 4.0. In 3.3, only a `COMPUTED` body and a `FOR select` clause were stopped from writing, and only when the write was reached, while the `FOR create`, `FOR update` and `FOR delete` clauses, `VALUE`, `DEFAULT` and `ASSERT` could write.

## Restrictions on computed fields

_(since v3.3.0)_

A [`COMPUTED`](#computed-fields) body is evaluated on every read of the field, inside the transaction of the statement that reads it. It is one of the [clauses that must not have effects](#clauses-that-must-not-have-effects), and the rules below also apply to it.

### A computed body is capped at the definer's permissions

A `COMPUTED` body is evaluated with the reader's own authentication, narrowed so that it can never exceed the level and role of the user who defined the field. As with [`DEFINE FUNCTION`](/docs/reference/query-language/statements/define/function.md), the limit is a ceiling: it only ever removes access.

A reader with broader permissions than the definer therefore gains nothing from the field. In the example below, the body needs a root-level identity, so it is refused under the definer's database-level Editor ceiling however privileged the reader is.

```surql
-- Defined by a database-level Editor
DEFINE FIELD server_info ON article COMPUTED (INFO FOR ROOT);

-- Selected by a root Owner: the body is still capped at database-level Editor
SELECT server_info FROM article;
```

The reverse does not hold, and a computed field is not a way to grant access. A reader with narrower permissions than the definer keeps their own: the body runs as them, and every permission that applies to their own queries applies inside it.

```surql
-- Defined by a root user
DEFINE TABLE audit_log SCHEMALESS PERMISSIONS NONE;
DEFINE TABLE article SCHEMALESS PERMISSIONS FULL;
DEFINE FIELD recent_audits ON article COMPUTED (SELECT * FROM audit_log);

-- Selected by a record user
SELECT id, title, recent_audits FROM article;
```

The record user can read `article`, so the row is returned. They cannot read `audit_log`, so the computed field is empty rather than exposing the table.

```surql title="Output"
[
	{
		id: article:1,
		recent_audits: [],
		title: 'Hello'
	}
]
```

> [!NOTE]
> For record and anonymous readers the narrowing is skipped altogether, because a system user's ceiling cannot narrow them any further. Auth limiting never escalates the reader - see [Capabilities](/docs/learn/security/authorization/capabilities.md).

### A computed field's own select permission is enforced everywhere

`PERMISSIONS FOR select` on a `COMPUTED` field applies wherever the field is read, not only in a `SELECT` projection. That includes the pre-mutation image an `UPDATE` reads, a `WHERE` condition, a write statement's `RETURN` list, and `RETURN DIFF`.

```surql
DEFINE TABLE item PERMISSIONS FOR select, update FULL;
DEFINE FIELD hidden ON item COMPUTED 'secret'
	PERMISSIONS FOR select NONE;
DEFINE FIELD leak ON item TYPE any PERMISSIONS FOR select, update FULL;

-- As a record user, both read the field as NONE
SELECT * FROM item:1;
UPDATE item:1 SET leak = hidden RETURN leak;
```

> [!WARNING]
> Before SurrealDB 3.3.0, a caller allowed to update a record could read a computed field denied to them and copy it into a field they were allowed to select, as in the `UPDATE` above. If you relied on a computed field's select permission to hide a value, check whether any writable field on the same table was used to copy it out.

### Computed fields and array elements in reduced results

Field-level select permissions narrow a record before it is returned. Before 3.3.0 that pass could remove whole elements of an array field rather than narrowing them, which also made `RETURN DIFF` come back empty for every session that was not the record's owner. Both now return the expected values.

## Using INLINE to filter a traversal during the scan

_(since v3.3.0)_

An `INLINE` field on a relation table is stored twice: once on the edge record as usual, and again inside the adjacency entries that the graph traversal walks. A traversal filtered on that field can then test the predicate while it scans, and fetch only the edge records that match.

```surql
DEFINE TABLE likes TYPE RELATION IN person OUT post;
DEFINE FIELD score ON likes TYPE number INLINE;
```

Inlining a field has no effect on the way it is queried. It is read and written exactly as before, and a traversal such as `person:one->(likes WHERE score > 8)->post` returns the same records. What changes is how many edge records the traversal has to read to produce them, which is why the clause helps on a filter that may run over many edges.

The condition has to sit inside the graph path for the inlined value to be reached. Written that way it becomes the scan's own predicate, which [`EXPLAIN`](/docs/reference/query-language/statements/explain.md) reports as `predicate_scope: payload` - the inlined copy is what the filter reads. The same condition written as an array filter, `person:one->likes[WHERE score > 8]->post`, walks every edge first and filters the resulting array afterwards, so the inlined value is never consulted and the clause brings no improvement in performance.

An inlined field can be thought of as an index in that it is a write-side cost paid for a read-side gain. Conversely, a field that is filtered rarely and written constantly is not one that you would want to inline.

Values for an inlined field should also be kept small. A payload larger than `SURREAL_GRAPH_INLINE_PROPS_CAP` (64 bytes by default) is spilled, meaning the value stays on the record only and the traversal falls back to fetching it. See [environment variables](/docs/reference/cli/db/environment-variables.md).

`ALTER FIELD` adds the clause to an existing field and removes it again, so the decision is reversible without redefining the field.

### What INLINE rejects

| Rejected | Error |
| --- | --- |
| A field on a table that is not `TYPE RELATION` | `INLINE requires an existing TYPE RELATION table` |
| The `id`, `in` or `out` fields | `the 'id', 'in' and 'out' fields already live in the adjacency keys and cannot be INLINE` |
| A nested field path, such as `meta.score` | `only a top-level field can be INLINE` |
| A `COMPUTED` field | There is no stored value to embed |
| A field on a [`LIGHTWEIGHT`](/docs/reference/query-language/statements/define/table.md#using-lightweight-for-relations-without-properties) relation | A lightweight relation has no edge records, so it has no fields at all |

Demoting a relation table to a normal table while it still carries `INLINE` fields is also rejected.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/function

# DEFINE FUNCTION

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

The `DEFINE FUNCTION` statement allows you to define custom functions that can be reused throughout a database. When using the `DEFINE FUNCTION` statement, you can define a function that takes one or more arguments and returns a value. You can then call this function in other SurrealQL statements.

Functions can be used to encapsulate logic that you want to reuse in multiple queries. They can also be used to simplify complex queries by breaking them down into smaller, more manageable pieces. They are particularly useful when you have a complex query that you need to run multiple times with different arguments.

## Requirements

- You must be authenticated as a root owner or editor, namespace owner or editor, or database owner or editor before you can use the `DEFINE FUNCTION` statement.
- [You must select your namespace and database](/docs/reference/query-language/statements/use.md) before you can use the `DEFINE FUNCTION` statement.

## Statement syntax

```syntax title="SurrealQL Syntax"
DEFINE FUNCTION [ OVERWRITE | IF NOT EXISTS ] fn::@name
  ( [ @argument: @type ... ] ) [ -> @type ] {
	[ @query ... ]
	[ RETURN @returned ]
} [ COMMENT @string ] [ PERMISSIONS [ NONE | FULL | WHERE @condition]]
  [ GRAPHQL_ALIAS @string ] [ GRAPHQL_DEPRECATED @string ]
```

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

```surql
-- 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) {
	"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:

```surql
-- Define a function that checks if a relation exists between two nodes
DEFINE FUNCTION fn::relation_exists(
	$in: record,
	$tb: string,
	$out: record
) {
	-- Check if a relation exists between the two nodes.
	LET $results = SELECT VALUE id FROM type::table($tb) WHERE in = $in
	  AND out = $out;
	-- Return true if a relation exists, false otherwise
    RETURN array::len($results) > 0;
};
```

## Stored procedures

A defined function is what SurrealDB has in place of a stored procedure. Its body can read and write records, it is stored in the database schema, and it runs as [one transaction](#transactional-behaviour), so a failure part way through leaves no partial writes. Where a relational database would use `CALL place_order(...)`, SurrealQL calls `fn::place_order(...)`, as a statement of its own or inside any other statement.

Function bodies are written in SurrealQL. To write the logic in Rust instead, compile it into a [SurrealDB extension](/docs/learn/extensions/plugins/overview.md), which SurrealDB loads with [`DEFINE EXTENSION`](/docs/reference/query-language/statements/define/extension.md) and calls with an `ext::` path. Extensions are experimental, so the server has to be started with `--allow-experimental=surrealism`, or the `SURREAL_CAPS_ALLOW_EXPERIMENTAL` environment variable set to the same value. On SurrealDB 3.x, loading an extension archive from a bucket also needs the experimental `files` feature, so 3.x takes `--allow-experimental=files,surrealism`. From 4.0, buckets are no longer experimental and the server refuses to start if `files` is listed.

## GraphQL names and deprecation

_(since v3.1.0)_

A custom function is exposed to [GraphQL](/docs/learn/querying/graphql/overview.md) as a root query field when the database's `DEFINE CONFIG GRAPHQL` includes functions. `GRAPHQL_ALIAS` sets the name of that field in place of one derived from the function name, and must match `[_A-Za-z][_0-9A-Za-z]*`. `GRAPHQL_DEPRECATED` adds `[Deprecated: reason]` to the start of the field's description.

```surql
DEFINE FUNCTION fn::get_user($n: string) -> string { "hi " + $n }
	GRAPHQL_ALIAS "getUser"
	GRAPHQL_DEPRECATED "Use fn::greet instead";
```

```graphql title="Query"
{ getUser(n: "x") }
```

```json title="Output"
{"data":{"getUser":"hi x"}}
```

## Optional arguments
If one or more ending arguments have the `option<T>` type, they can be omitted when you invoke the function.

```surql
DEFINE FUNCTION fn::last_option($required: number, $optional: option<number>) {
	RETURN {
		required_present: type::is_number($required),
		optional_present: type::is_number($optional),
	}
};

RETURN fn::last_option(1, 2);
//- { optional_present: true, required_present: true }

RETURN fn::last_option(1);
//- { optional_present: false, required_present: true }
```

## Adding a return value

Optionally, the return value of a function can be specified.

For a function that is infallible, a return value is mostly for the sake of readability.

```surql
DEFINE FUNCTION fn::greet($name: string) -> string {
	"Hello, " + $name + "!"
};
```

For a function that is not infallible, specifying a return value can be used to customise error output.

```surql
-- Arguments must be of type 'number'
DEFINE FUNCTION fn::combine($one: number, $two: number) -> number {
  $one + $two
};

-- Accepts any value but expects the return type 'number'
DEFINE FUNCTION fn::combine_any($one: any, $two: any) -> number {
  $one + $two
};

fn::combine("one", "two");
fn::combine_any("one", "two");
```

While both of these return an error, the output of the second function happens only at the point that it attempts to return the combined arguments to the function.

```surql title="Output"
-------- Query 1 --------
"Expected `number` but found `'one'`"

-------- Query 2 --------
"Couldn't coerce return value from function `fn::combine_any`: Expected `number` but found `'onetwo'`"
```

The return value of a function can even be a [literal type](/docs/reference/query-language/language-primitives/data-types/literals.md). The following function returns such a type by either returning an object of a certain structure, or a string. In this case this output is used in case an application prefers to return an error as a simple string instead of [throwing](/docs/reference/query-language/statements/throw.md) an error or returning a NONE value.

```surql
DEFINE FUNCTION fn::age_and_name($user_num: int)
    -> { age: int, name: string } | string {
    LET $user = type::record("user", $user_num);
    IF $user.exists() {
        $user.{ name, age }
    } ELSE {
        { "Couldn't find user number " + <string>$user_num + "!" }        
    }
};

CREATE user:1 SET name = "Billy", age = 15;

fn::age_and_name(1);
//- { age: 15, name: 'Billy' }
fn::age_and_name(2);
//- "Couldn't find user number 2!"
```

## Permissions

You can set the permissions for a custom function using the `PERMISSIONS` clause. The `PERMISSIONS` clause restricts who can call a function. It can be set to `NONE`, `FULL`, or `WHERE @condition`.

- `FULL`: When Full permissions are granted [record](/docs/learn/security/authentication/users.md#record-users) users have access to the function. This is the default permission when not specified.
- `NONE`: When this permission is granted, [record](/docs/learn/security/authentication/users.md#record-users) users have no access to the defined function.
- `WHERE @condition`: Permissions are granted to the function based on the specified condition.

The `PERMISSIONS` clause decides who may call the function. It does not change what the body can do: the body runs with the permissions of the caller, so a record user's call can read and write only what that user could read and write directly. A query the user is not allowed to run returns no records rather than an error, in the same way as when the user runs it directly:

```surql
DEFINE TABLE secret_note PERMISSIONS NONE;
DEFINE FUNCTION fn::read_notes() -> array {
	SELECT * FROM secret_note
} PERMISSIONS FULL;

-- As a record user, both return [], however many notes exist
SELECT * FROM secret_note;
fn::read_notes();
```

To let users change data they cannot reach directly, use an [event](/docs/reference/query-language/statements/define/event.md#events-and-permissions) or a [`DEFINE API`](/docs/reference/query-language/statements/define/api.md#permissions) endpoint, whose bodies run without table permission checks, or a table permission clause that allows the change.

> [!NOTE]
> The examples below use the [`Surreal Deal Store`](/docs/learn/tutorials/demos/surreal-deal-store.md) dataset.

### Using the `FULL` permission

The `FULL` permission grants all users access to the function. The following example defines a function that fetches all products from the `product` table and grants the function full permissions to access the data to all users.

```surql
-- Define a function to fetch all products. All users can access this function
DEFINE FUNCTION fn::fetchAllProducts() {
	RETURN (SELECT * FROM product LIMIT 10);
} PERMISSIONS FULL;
-- Returns: The first 10 products in the product table
RETURN fn::fetchAllProducts();
```

### Using the `NONE` permission

The `NONE` permission denies all [record](/docs/learn/security/authentication/users.md#record-users) users access to the function. The following example defines a function that fetches all products from the `product` table

```surql
CREATE payment_details:1 SET stored_cards = { expiry_year: 2028 };

-- Define a function that fetches all expiration years from the payment_details table and denies access to all non-admin users
DEFINE FUNCTION fn::fetchAllPaymentDetails() -> array {
	SELECT stored_cards.expiry_year FROM payment_details LIMIT 5
} PERMISSIONS NONE;

RETURN fn::fetchAllPaymentDetails();
```

### Using the `WHERE` clause

The `WHERE` clause allows you to specify a condition that determines the permissions granted to the function. The condition must evaluate to a boolean value. If the condition evaluates to `true`, the function is granted permissions. If the condition evaluates to `false`, the function is not granted permissions.

```surql
-- Define a function that fetches all products with the condition that only admin users can access it
DEFINE FUNCTION fn::fetchAllProducts() -> array {
	 SELECT * FROM product LIMIT 10
} PERMISSIONS WHERE $auth.admin = true;
```

## Transactional behaviour

A function body runs as a single transaction, without `BEGIN` or `COMMIT` appearing in the definition. It commits when the body finishes, and rolls back if anything inside it fails.

> [!WARNING]
> `BEGIN`, `COMMIT` and `CANCEL` inside a function body are accepted but have no effect. A `CANCEL` does not undo the body's changes, and a `COMMIT` does not keep them if the function fails afterwards. Use `THROW` to roll back from inside a function.

An error rolls the whole body back, whether it is a [`THROW`](/docs/reference/query-language/statements/throw.md) or a statement that fails on its own:

```surql
-- Setup
DEFINE TABLE order;
CREATE product:keyboard SET stock = 20;

DEFINE FUNCTION fn::place_order($item: record<product>, $quantity: int) -> record<order> {
    LET $order = CREATE ONLY order SET item = $item, quantity = $quantity;
    IF $item.stock < $quantity {
        THROW "Insufficient stock for " + <string>$item;
    };
    UPDATE $item SET stock -= $quantity;
    RETURN $order.id;
};

fn::place_order(product:keyboard, 500);

-- No order exists: the THROW rolled the whole body back, so no order
-- is left behind reserving stock that was never decremented
SELECT VALUE id FROM order;
```

An early `RETURN` is not a failure, so the body commits and the work already done is kept:

```surql
DEFINE FUNCTION fn::ship_order($order: record<order>) -> record<shipment> {
    LET $shipment = CREATE ONLY shipment SET order = $order, carrier = 'DHL';
    RETURN $shipment.id;                          -- the caller only wants the id
    UPDATE $order SET status = 'shipped';         -- never runs
};
```

Calling a function from inside a manual transaction makes its statements part of that transaction rather than a nested one, so a failure inside the function aborts the caller's transaction too. See [Transactions](/docs/learn/querying/concepts-and-guides/transactions.md#implicit-transactions).

## Recursive functions

A function is able to call itself, making it a recursive function. One example of a recursive function is the one below which creates a relation between each and every record passed in.

Consider a situation in which seven person records exist. First, `person:1` will need to be related to the rest of the `person` records, after which there are no more relations to create for it. Following this, the relations for `person:2` and all the other records except for `person:1` will need to be created, and so on.

This can be done in a recursive function by creating all the relations between the first record and the remaining records, after which the function calls itself by passing in all the records except the first. This continues until the function receives less than two records, in which case it ceases calling itself by doing nothing, thereby ending the recursion.

```surql
DEFINE FUNCTION fn::relate_all($records: array<record>) {
  IF $records.len() < 2 {
      -- Don't do anything, ending the recursion
  }  ELSE {
      LET $first = $records[0];
      LET $remainder = $records[1..];
      FOR $counterpart IN $remainder {
          RELATE $first->to->$counterpart;
      };
      fn::relate_all($remainder);
  }
};

CREATE |person:1..8|;

fn::relate_all(SELECT VALUE id FROM person);

SELECT id, ->to->? FROM person;
```

The last query [can be viewed graphically](/blog/whats-new-in-surrealist-3-2#graph-visualisation) inside SurrealDB Studio, leading to an output showing a seven-pointed star.

<img src="~/assets/img/image/light/recursive_star.png" darkSrc="~/assets/img/image/dark/recursive_star.png" alt="An image of a seven-pointed star created visually by relating seven records to each other and displayed inside SurrealDB Studio's graph view." />

## Functions called from schema clauses

_(since v4.0.0)_

A custom function called from a `COMPUTED`, `ASSERT`, `VALUE` or `DEFAULT` clause, or from a `PERMISSIONS` clause, is held to the rules of that clause: it may not write data, change the schema or `SLEEP`, and outside `VALUE` and `DEFAULT` it may not call `sequence::nextval()`. The rules are listed in [Clauses that must not have effects](/docs/reference/query-language/statements/define/field.md#clauses-that-must-not-have-effects). The clause is checked when it is defined, and the check follows each function into the functions it calls:

```surql
DEFINE FUNCTION fn::log_access() -> bool { CREATE access_log SET at = time::now(); RETURN true; };
DEFINE TABLE product PERMISSIONS FOR select WHERE fn::log_access();
```

```surql title="Error output"
'The PERMISSIONS clause must not have effects: it calls `fn::log_access`, in whose body `CREATE` writes data'
```

A function can change after the clause that calls it was defined. `DEFINE FUNCTION OVERWRITE` and [`ALTER FUNCTION`](/docs/reference/query-language/statements/alter/function.md) accept a body that starts to write, and the clause then fails each time it is evaluated, so check which definitions call a function before changing its body:

```surql
DEFINE FUNCTION fn::price_with_tax($price: number) -> number { RETURN $price * 1.2; };
DEFINE FIELD gross_price ON product COMPUTED fn::price_with_tax(price);

-- Accepted, but every read of `gross_price` now fails
DEFINE FUNCTION OVERWRITE fn::price_with_tax($price: number) -> number {
	CREATE price_change SET price = $price, at = time::now();
	RETURN $price * 1.2;
};

CREATE product:1 SET price = 10;
```

```surql title="Error output"
'The COMPUTED clause must not have effects: `CREATE` writes data'
```

## Using `IF NOT EXISTS` clause

The `IF NOT EXISTS` clause can be used to define a function only if it does not already exist. You should use the `IF NOT EXISTS` clause when defining a function in SurrealDB if you want to ensure that the function is only created if it does not already exist. If the function already exists, the `DEFINE FUNCTION` statement will return an error.

It's particularly useful when you want to safely attempt to define a function without manually checking its existence first.

On the other hand, you should not use the `IF NOT EXISTS` clause when you want to ensure that the function definition is updated regardless of whether it already exists. In such cases, you might prefer using the `OVERWRITE` clause, which allows you to define a function and overwrite an existing one if it already exists, ensuring that the latest version of the function definition is always in use.

```surql
-- Create a FUNCTION if it does not already exist
DEFINE FUNCTION IF NOT EXISTS fn::example() {};
```

## Using `OVERWRITE` clause

The `OVERWRITE` clause can be used to define a function and overwrite an existing one if it already exists. You should use the `OVERWRITE` clause when you want to modify an existing function definition. If the function already exists, the `DEFINE FUNCTION` statement will overwrite the existing definition with the new one.

```surql
-- Create a FUNCTION and overwrite if it already exists
DEFINE FUNCTION OVERWRITE fn::example() {};
```

## Functions as custom middleware

_(since v3.0.0)_

A `DEFINE FUNCTION` statement can be used to define a function for use as custom middleware. For more details on defining a custom function in this manner, see the [`DEFINE API`](/docs/reference/query-language/statements/define/api.md#custom-middleware) page.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/indexes

# DEFINE INDEX

SurrealDB uses indexes to help optimise query performance. An index can consist of one or more fields in a table and can enforce a uniqueness constraint - including SPATIAL indexes for geometries and HNSW and DISKANN vector indexes.

> [!NOTE]
> Before SurrealDB version 3.0.0, the `FULLTEXT ANALYZER` clause used the syntax `SEARCH ANALYZER`.

Just like in other databases, SurrealDB uses indexes to help optimise query performance. An index can consist of one or more fields in a table and can enforce a uniqueness constraint. If you don't intend for your index to have a uniqueness constraint, then the fields you select for your index should have a high degree of cardinality, meaning that there is a high amount of diversity between the data in the indexed table records.

## Requirements

- You must be authenticated as a root owner or editor, namespace owner or editor, or database owner or editor before you can use the `DEFINE INDEX` statement.
- [You must select your namespace and database](/docs/reference/query-language/statements/use.md) before you can use the `DEFINE INDEX` statement.

## Statement syntax

**SurrealQL Syntax**

```syntax title="Basic syntax"
DEFINE INDEX [ OVERWRITE | IF NOT EXISTS ] @name
    ON [ TABLE ] @table 
    [ FIELDS | COLUMNS ] @fields
    [ @special_clause ]
    [ COMMENT @string ]
    [ CONCURRENTLY ]
    [ DEFER ]
```

The `@special_clause` part of the statement is an optional part in which an index can be declared for special usage such as guaranteeing unique values, full-text search, and so on. The available clauses are:

```syntax title="Special index clauses"
UNIQUE [ NULLS NOT DISTINCT ]
| COUNT [ WHERE @condition ]
| FULLTEXT ANALYZER @analyzer [ BM25 [(@k1, @b)] ] [ HIGHLIGHTS ]
| HNSW DIMENSION @dimension [ TYPE @type ] [ DIST @distance ]
    [ EFC @efc ] [ M @m ]
| DISKANN DIMENSION @dimension [ TYPE @type ] [ DIST @distance ]
    [ DEGREE @degree ] [ L_BUILD @l_build ]
    [ ALPHA @alpha ] [ HASHED_VECTOR ]
| SPATIAL
```

An index has at most one of these clauses. From SurrealDB 4.0, a statement that gives two of them, or the same one twice, is a parse error such as `Cannot combine UNIQUE with COUNT` or `UNIQUE is given twice`, rather than keeping only the last one.

## Index types

SurrealDB offers a range of indexing capabilities designed to optimise data retrieval and search efficiency.

### Standard (non-unique) index

An index without any special clauses allows for the indexing of attributes that may have non-unique values, facilitating efficient data retrieval. Non-unique indexes help index frequently appearing data in queries that do not require uniqueness, such as categorization tags or status indicators.

The following example creates a non-unique index for an age field on a user table.

```surql
-- optimise queries looking for users of a given age
DEFINE INDEX userAgeIndex ON TABLE user FIELDS age;
```

Besides `=` and comparisons such as `>` and `<`, a standard index is used for a range with `IN`, and for a string prefix with [`string::starts_with()`](/docs/reference/query-language/functions/database-functions/string.md#stringstarts_with). Before SurrealDB 3.3.1, these two scanned the whole table.

```surql
-- Both use the index from 3.3.1
SELECT * FROM user WHERE age IN 18..30;
SELECT * FROM user WHERE string::starts_with(name, 'Ann');
```

Only the function-call form is read as a prefix. The method form `name.starts_with('Ann')` returns the same records, but scans the table.

#### Indexing an array field

On a field that holds an array, a standard index has one entry for each element. A condition still compares the whole value, so with `tags = ['a', 'b']`, the condition `tags = 'a'` is false and `tags = ['a', 'b']` is true, with or without the index. To find the records whose array holds an element, use [`CONTAINS`](/docs/reference/query-language/language-primitives/operators.md#contains-or-) or `CONTAINSANY` and index the elements with `tags.*`:

```surql
DEFINE INDEX post_tags ON post FIELDS tags.*;

SELECT * FROM post WHERE tags CONTAINS 'a';
SELECT * FROM post WHERE tags CONTAINSANY ['a', 'c'];
```

An index declared as `FIELDS tags` is not used for `CONTAINS`, and the query scans the table instead. The field may still hold a string written before its type was declared, and `CONTAINS` on a string looks for a substring, which an element lookup cannot find. A `tags.*` index finds such a string for the plain form `tags CONTAINS 'a'`, as described in [Array-element composite indexes](#array-element-composite-indexes). The form `tags.* CONTAINS 'a'` takes each element of the field, and a string is indexed whole, so it does not find a substring inside a string.

> [!WARNING]
> Before SurrealDB 3.3.1, the query planner treated a `FIELDS tags` index on an array field as if each record held a single value, so a query could return different records with the index than without it. `count()` with `tags = 'a'` counted the records whose array held `'a'`, `tags = ['a', 'b']` returned nothing, a range such as `tags > 'a'` could return a record twice, and `ORDER BY tags` followed the order of the index entries. From 3.3.1 these return the same results as without the index on a field whose type is an array, such as `array<string>` or `option<array<string>>`, and the index does not need to be rebuilt. A field with no declared type, or a type that also allows a value that is not an array, keeps the earlier behaviour. So does a server started with [`SURREAL_PLANNER_STRATEGY`](/docs/reference/cli/db/environment-variables.md) set to `compute-only`.

#### Indexing a computed value

The field path in `FIELDS` can end with one or more method calls. The index then stores the result of the methods for each record, and updates it when the record changes. This lets a query that filters on a transformed value, such as a lowercase name, use an index:

```surql
DEFINE INDEX product_kind ON product FIELDS kind.trim().lowercase();

CREATE product:1 SET kind = ' Banana ';
CREATE product:2 SET kind = 'apple';

SELECT id FROM product WHERE kind.trim().lowercase() = 'banana';
```

```surql title="Output"
[
	{
		id: product:1
	}
]
```

Adding [`EXPLAIN`](/docs/reference/query-language/clauses/explain.md) to the query shows that it reads the index. The `IndexScan` operator names `product_kind` and looks up the computed value `'banana'`:

```surql
SELECT id FROM product WHERE kind.trim().lowercase() = 'banana' EXPLAIN;
```

```surql title="Output"
{
	attributes: {
		projections: 'id'
	},
	children: [
		{
			attributes: {
				access: "= 'banana'",
				direction: 'Forward',
				index: 'product_kind',
				table: 'product'
			},
			context: 'Db',
			operator: 'IndexScan'
		}
	],
	context: 'Db',
	operator: 'SelectProject'
}
```

A query uses the index only when its condition repeats the expression as it is written in `FIELDS`. `WHERE kind = 'banana'` and the function-call form `WHERE string::lowercase(kind) = 'banana'` both scan the table, although the second one returns the same records, and their `EXPLAIN` output shows a `TableScan` instead. Comparisons and `IN` work on a computed value in the same way as on a stored one, and a [composite index](#composite-index) can mix the two, as in `FIELDS kind.lowercase(), price`.

Only method calls on a field path are accepted. A function call such as `string::lowercase(kind)` or an operator such as `price * qty` fails when the index is defined. To index one of those, store the result in a field of its own with [`DEFINE FIELD ... VALUE`](/docs/reference/query-language/statements/define/field.md) and index that field.

A column that ends in method calls is accepted on a `SCHEMALESS` table only. On a `SCHEMAFULL` table, defining such an index fails with an error such as `The field 'kind.lowercase()' does not exist`, even when the field `kind` is defined. On a `SCHEMAFULL` table, store the computed value with `DEFINE FIELD ... VALUE` and index that field instead.

#### Computed values on an optional field

Every record write runs the methods, and a method cannot run on `NONE` or `NULL`. With the index on `kind.trim().lowercase()` above, a record with no `kind`, or with `kind` set to `NULL`, fails with an error such as `There was a problem running the trim() function. no such method found for the none type`, and so does `CREATE product:3 SET kind = 5`. A `DEFINE INDEX` over existing records that lack the field fails in the same way. The index never yields `NONE` in place of the error, because the same condition in a table scan fails with it too.

To accept records without the field, write [`.?`](/docs/reference/query-language/language-primitives/idioms.md#optional-parts) before the first method in the column and in the condition. The methods are then skipped when the field is `NONE` or `NULL`, and the index returns the same records as a table scan:

```surql
DEFINE TABLE product SCHEMALESS;
DEFINE INDEX product_kind_optional ON product FIELDS kind.?.trim().lowercase();

CREATE product:1 SET kind = '  Banana ';
CREATE product:2 SET kind = 'APPLE';
CREATE product:3;
CREATE product:4 SET kind = NULL;
CREATE product:5 SET kind = 'banana';

SELECT VALUE id FROM product WHERE kind.?.trim().lowercase() = 'banana' ORDER BY id;
//- [product:1, product:5]

-- NULL is a value, so only the record without the field matches NONE
SELECT VALUE id FROM product WHERE kind.?.trim().lowercase() = NONE ORDER BY id;
//- [product:3]
```

A `UNIQUE` index on such a column accepts any number of records without the field or with it set to `NULL`, and still refuses two records whose computed values are equal.

Writing the optional part as `?.`, as in `kind?.trim().lowercase()`, is a parse error.

### Unique index

Ensures each value in the index is unique. A unique index helps enforce uniqueness across records by preventing duplicate entries in fields such as user IDs, email addresses, and other unique identifiers.

The following example creates a unique index for the email address field on a user table.

```surql
-- Makes sure that the email address in the user table is always unique
DEFINE INDEX userEmailIndex ON TABLE user FIELDS email UNIQUE;
```

The created index can be tested using the [`INFO` statement](/docs/reference/query-language/statements/info.md).

```surql
INFO FOR TABLE user;
```
The `INFO` statement will help you understand what indexes are defined in your `TABLE`.

```surql
{
    "events": {},
    "fields": {},
    "indexes": {
        "userEmailIndex": {
            sql: "DEFINE INDEX userEmailIndex ON user FIELDS email UNIQUE"
        }
    },
    "lives": {},
    "tables": {}
}
```

As a `UNIQUE` index is defined on the `email` field, a duplicate entry for that field will throw an error.

```surql
-- Create a user record and set an email ID.
CREATE user:1 SET email = 'test@surrealdb.com';
```

```surql title="Output"
[
    {
        "email": "test@surrealdb.com",
        "id": "user:1"
    }
]
```

Creating another record with the same email ID will throw an error.

```surql
-- Setup from the examples above
DEFINE INDEX userEmailIndex ON TABLE user FIELDS email UNIQUE;
CREATE user:1 SET email = 'test@surrealdb.com';

-- Create another user record and set the same email ID.
CREATE user:2 SET email = 'test@surrealdb.com';
```

```surql title="Error output"
"Database index `userEmailIndex` already contains 'test@surrealdb.com', with record `user:1`"
```

To set the same email for `user:2`, the original record must be deleted

```surql
DELETE user:1;
CREATE user:2 SET email = 'test@surrealdb.com'
```
```text
[
    {
        "email": "test@surrealdb.com",
        "id": "user:2"
    }
]
```

A `UNIQUE` index does not treat an empty field as a duplicate. Any number of records can leave the field out (`NONE`) or set it to `NULL`, so a unique field can still be optional.

```surql
DEFINE FIELD email ON user TYPE option<string | null>;
DEFINE INDEX userEmailIndex ON user FIELDS email UNIQUE;

CREATE user:1;
CREATE user:2;
CREATE user:3 SET email = NULL;
CREATE user:4 SET email = NULL;

SELECT count() FROM user GROUP ALL;
```

```surql title="Output"
[{ count: 4 }]
```

#### Treating `NULL` as a value with `NULLS NOT DISTINCT`

_(since v4.0.0)_

`UNIQUE NULLS NOT DISTINCT` makes `NULL` take part in uniqueness like any other value, so only one record can hold `NULL` in the field. A record that leaves the field out (`NONE`) is still not compared, so any number of records can do that. In a composite index, a tuple that holds `NULL` is compared as a whole, and a tuple that holds `NONE` is not compared.

```surql
DEFINE INDEX unique_v ON solo FIELDS v UNIQUE NULLS NOT DISTINCT;

CREATE solo:1 SET v = NULL;
CREATE solo:2;
CREATE solo:3;
CREATE solo:4 SET v = NULL;
```

```surql title="Error output"
"Database index `unique_v` already contains NULL, with record `solo:1`"
```

An empty array is indexed as `NULL`, so on such an index two records with an empty array collide, and so do an empty array and `NULL`. Adding the clause to an existing index with `DEFINE INDEX OVERWRITE` builds the index again, and the statement fails, keeping the existing index, if the table already holds more than one `NULL`. `INFO FOR TABLE` shows the clause as part of the index definition.

#### Conditional uniqueness

A `UNIQUE` index applies to every record in the table. `WHERE` is accepted only on a `COUNT` index, so `DEFINE INDEX ... UNIQUE WHERE ...` is a parse error. Because a unique index ignores `NONE`, a field with a `VALUE` clause that holds the value only when the condition is true gives the same effect as a partial unique index. The following index allows any number of inactive plans for an email address, but only one active plan:

```surql
DEFINE FIELD email ON plan TYPE string;
DEFINE FIELD active ON plan TYPE bool;
DEFINE FIELD active_email ON plan VALUE IF active { email } ELSE { NONE };
DEFINE INDEX one_active_plan ON plan FIELDS active_email UNIQUE;

CREATE plan SET email = 'ana@example.com', active = false;
CREATE plan SET email = 'ana@example.com', active = false;
CREATE plan SET email = 'ana@example.com', active = true;
CREATE plan SET email = 'ana@example.com', active = true;
```

```text title="Error output"
Database index `one_active_plan` already contains 'ana@example.com', with record `plan:...`
```

A unique index stays correct when transactions write at the same time: of two concurrent inserts with the same value, one commits and the other fails with a retryable transaction conflict. See [Unique indexes under concurrent writes](/docs/learn/querying/concepts-and-guides/transactions.md#unique-indexes-under-concurrent-writes).

On a field that holds an array, an index has one entry for each element rather than one for the whole array. A `UNIQUE` index on such a field therefore makes every element unique across all records, so two records cannot share any element:

```surql
DEFINE INDEX unique_tag ON post FIELDS tags UNIQUE;

CREATE post:1 SET tags = ['a', 'b'];
CREATE post:2 SET tags = ['b', 'c'];
```

```text title="Error output"
Database index `unique_tag` already contains 'b', with record `post:1`
```

The uniqueness is between records. One record whose array holds the same element twice, such as `tags = ['d', 'd']`, does not conflict with itself, and the index holds that element once for it.

To make the array as a whole unique instead, so that two records cannot have the same tags but may share some, end the field with [`...`](/docs/reference/query-language/language-primitives/idioms.md#flattening). The index then has one entry for the whole array:

```surql
DEFINE INDEX unique_tags ON post FIELDS tags... UNIQUE;

CREATE post:1 SET tags = ['a', 'b'];
CREATE post:2 SET tags = ['b', 'c'];
CREATE post:3 SET tags = ['a', 'b'];
```

```text title="Error output"
Database index `unique_tags` already contains ['a', 'b'], with record `post:1`
```

[`INFO FOR TABLE`](/docs/reference/query-language/statements/info.md) shows this index as `FIELDS tags…`, with a single ellipsis character, which SurrealQL also accepts in place of `...`. The order of the elements counts, so `['b', 'a']` is a different value from `['a', 'b']`. To treat the two as the same, index a field that holds the array sorted and converted to a single value:

```surql
DEFINE FIELD tag_key ON post VALUE <string> tags.sort();
DEFINE INDEX unique_tags ON post FIELDS tag_key UNIQUE;
```

A `UNIQUE` index compares values exactly, so `'Bob'` and `'bob'` count as different. For a case-insensitive unique value, [index a computed value](#indexing-a-computed-value) that normalises it:

```surql
DEFINE INDEX unique_name ON user FIELDS name.lowercase() UNIQUE;

CREATE user:1 SET name = 'Bob';
CREATE user:2 SET name = 'bOB';
```

```text title="Error output"
Database index `unique_name` already contains 'bob', with record `user:1`
```

A query uses this index for `WHERE name.lowercase() = 'bob'`, but not for a condition on `name` alone. Alternatively, store the normalised value in a field of its own and index that field, which keeps the lowercase value visible in query results:

```surql
DEFINE FIELD name_key ON user VALUE name.lowercase();
DEFINE INDEX unique_name ON user FIELDS name_key UNIQUE;
```

### Composite index

A composite index spans multiple fields of a table. Composite indexes are mainly used to create a unique index when the definition of what is unique pertains to more than one field.

```surql
-- Create an index on the account and email fields of the user table
DEFINE INDEX test ON user FIELDS account, email UNIQUE;
```

As with a single field, a composite `UNIQUE` index does not check a record for duplicates when any of its fields is `NONE` or `NULL`. In the following example, `t:1` and `t:2` both have `i = 1` and no `j`, and both are created. Only `t:4` fails, because it repeats both values of `t:3`.

```surql
DEFINE INDEX t_idx ON t FIELDS i, j UNIQUE;

CREATE t:1 SET i = 1;
CREATE t:2 SET i = 1;
CREATE t:3 SET i = 1, j = 'a';
CREATE t:4 SET i = 1, j = 'a';
```

```text title="Error output"
Database index `t_idx` already contains [1, 'a'], with record `t:3`
```

To check the other fields when one is missing, give the optional field a default value, such as `DEFINE FIELD j ON t TYPE string DEFAULT ''`, or add a separate `UNIQUE` index on the fields that must be unique by themselves.

When more than one of the fields holds an array, the index has one entry for every combination of their elements. A record with `tags = ['a', 'b']` and `authors = ['x', 'y']` gives four entries, so a `UNIQUE` index refuses any later record that repeats one of those four pairs:

```surql
DEFINE INDEX tag_author ON post FIELDS tags, authors UNIQUE;

CREATE post:1 SET tags = ['a', 'b'], authors = ['x', 'y'];
CREATE post:2 SET tags = ['a'], authors = ['y'];
```

```text title="Error output"
Database index `tag_author` already contains ['a', 'y'], with record `post:1`
```

A query that uses such an index returns each record once, however many of its entries match.

> [!WARNING]
> Before SurrealDB 3.3.1, an index over two or more array fields stored only some of the combinations, so the `CREATE post:2` above succeeded. An index written by an earlier release stays incomplete after upgrading until you run [`REBUILD INDEX`](/docs/reference/query-language/statements/rebuild.md) on it. Earlier releases could also return a record once for each matching entry when a query used a composite index with an array field, such as `FIELDS account, emails.*.address` queried by `account` alone. That needs no action after upgrading.

#### Array-element composite indexes

_(since v3.1.0)_

From SurrealDB 3.1.0, a composite index can lead with an **array-element** field (`tags.*`) so containment predicates combine with ordering on a trailing field without a full table scan. This supports patterns such as `WHERE tags.* CONTAINS 'x' ORDER BY age DESC LIMIT N` and the multi-value forms `CONTAINSANY` / `ANYINSIDE` on array fields.

```surql
DEFINE INDEX tag_age ON article FIELDS tags.*, age;

-- Bounded index walk (check with EXPLAIN FULL)
SELECT * FROM article
WHERE tags.* CONTAINS 'release-notes'
ORDER BY age DESC
LIMIT 10;
```

`CONTAINSALL` / `ALLINSIDE` may still apply a residual filter above the union when intersection semantics require it. See [operators](/docs/reference/query-language/language-primitives/operators.md) and [`EXPLAIN`](/docs/reference/query-language/statements/explain.md) to confirm the planner choice.

A containment condition that takes each element of the field, as `tags.* CONTAINS 'x'`, `tags[*] CONTAINS 'x'` and `'x' INSIDE tags[*]` do, reads the index on `tags.*` directly. The plain form `tags CONTAINS 'x'`, and `'x' INSIDE tags`, `CONTAINSANY` and `CONTAINSALL`, can also match a record whose `tags` is not an array, such as a string that holds `'x'` as a substring. The index lists a record whose `tags` is a string, a range, another single value or missing under `NONE`, so from SurrealDB 4.0 the plain form reads the entries for `'x'`, `NONE` and `NULL` together, and checks the condition on each record it reads. `EXPLAIN` shows this as a `UnionIndexScan` with one branch for each value.

The plain form reads the table instead in three cases:

- Any record has stored an object or a record link in the field. The index stores such a value whole, so it has no entry that the condition can find.
- The query has an `ORDER BY` that the index does not give, such as `ORDER BY` a field that is not the next field of the index, or a `LIMIT` with no `ORDER BY`. A table scan rejects most records without decoding them, so it costs less in these cases.
- The index was built by a release before 4.0, which did not record the kinds of value it stored. [`REBUILD INDEX`](/docs/reference/query-language/statements/rebuild.md) records them.

With `ORDER BY` on the next field of the index, as in `WHERE tags CONTAINS 'x' ORDER BY created DESC LIMIT 10`, the plan reads the three sets of entries in index order and stops at the limit.

> [!NOTE]
> From SurrealDB 4.0, a field declared as a [set](/docs/reference/query-language/language-primitives/data-types/sets.md#paths-and-indexes-over-sets) is indexed as a whole by `.*`, not element by element. `WHERE s CONTAINS 3` on a set field reads the records instead of using the index, and a `UNIQUE` index over `s.*` treats the whole set as the key.

A composite index can include more than one array field, and a record can hold arrays in all of them. The index holds an entry for each combination of their elements, so a query with a condition on each field reads both from the index:

```surql
DEFINE INDEX tags_sizes ON product FIELDS tags.*, sizes.*;
CREATE product:jumper SET tags = ["wool", "winter"], sizes = ["S", "M"];
CREATE product:shirt SET tags = ["cotton"], sizes = ["M", "L"];

EXPLAIN SELECT id FROM product
	WHERE tags.* CONTAINS "wool" AND sizes.* CONTAINS "M";
```

```surql title="Output"
"SelectProject [ctx: Db] [projections: id]
    IndexScan [ctx: Db] [table: product, index: tags_sizes, access: ['wool', 'M'], direction: Forward]
"
```

### Count index

_(since v3.0.0)_

A count index maintains a running count of records on a table. It is used with `count()` and `GROUP ALL` in a query. SurrealDB stores incremental count deltas and compacts them in the background.

Count indexes come in two forms:

- **`COUNT`** - counts every record in the table. Used with `SELECT count() FROM <table> GROUP ALL` (no `WHERE`).
- **`COUNT WHERE <condition>`** - counts only records that match the condition. Used with `SELECT count() FROM <table> WHERE <condition> GROUP ALL` when the query `WHERE` clause **exactly matches** the index condition.

As a count index is declared on a table as a whole, it cannot use the `FIELDS` / `COLUMNS` clause.

#### Full-table counts

For `SELECT count() FROM <table> GROUP ALL`, SurrealDB already uses a `CountScan` fast path that counts record keys in storage without deserialising every record. An unconditional `COUNT` index is optional here; it can reduce work further once count deltas have been compacted, but a freshly built index on a large existing table may hold millions of delta entries until compaction runs.

```surql
DEFINE INDEX idx ON indexed_reading COUNT;

FOR $_ IN 0..100000 {
    CREATE reading SET temperature = rand::int(0, 10);
};

FOR $_ IN 0..100000 {
    CREATE indexed_reading SET temperature = rand::int(0, 10);
};

-- Wait a moment before running these two
-- queries to ensure the index is built
SELECT count() FROM reading GROUP ALL;
SELECT count() FROM indexed_reading GROUP ALL;
```

#### Filtered counts (`COUNT WHERE`)

Use `COUNT WHERE` when you repeatedly need `SELECT count() … WHERE … GROUP ALL` and do not want to scan and deserialise every record. The planner uses `IndexCountScan` when the query `WHERE` matches the index condition exactly (same expression as written in `DEFINE INDEX`).

```surql
DEFINE TABLE item SCHEMALESS;
DEFINE INDEX item_active_count ON item COUNT WHERE status = "active";

CREATE item:a SET status = "active";
CREATE item:b SET status = "active";
CREATE item:c SET status = "inactive";

SELECT count() FROM item WHERE status = "active" GROUP ALL;

EXPLAIN ANALYZE SELECT count() FROM item WHERE status = "active" GROUP ALL;
```

Requirements for the filtered fast path:

- `GROUP ALL` must be present.
- The query `WHERE` must match the index condition exactly (not a broader or different predicate).
- The index build must be complete (`INFO FOR INDEX …` shows `ready`).
- Field-level `SELECT` permissions on fields in the condition must not block index-only counting.

If the `WHERE` clause is not an exact match, SurrealDB falls back to a full table scan, filter, and count.

#### When to use which

For many applications, a **standard B-tree index** (`FIELDS` / `COLUMNS`) is the default for filtered counts. Recent planner improvements let a covering B-tree use the same `IndexCountScan` fast path as a `COUNT WHERE` index, so the two often perform similarly at query time.

_(since v4.0.0)_

A B-tree index also counts several values of its field without reading a record: `count()` over `status IN ['draft', 'review']`, or over `status = 'draft' OR status = 'review'`, adds up one walk of the index per value. The values must be literals and must differ from each other, so `IN ['draft', 'draft']` reads the records instead, and an `IN` list of more than 32 values does not use the index at all. A count over a page of results, `SELECT count() FROM (SELECT 1 FROM article WHERE status = 'draft' LIMIT 100) GROUP ALL`, stops walking the index once it reaches the limit. `EXPLAIN` shows each walk as an `IndexScan` with `keys_only: yes` under the `IndexCountScan`.

That does **not** make count indexes obsolete, however, as they solve a narrower problem and have a smaller storage footprint.

* If you would add `DEFINE INDEX … FIELDS status` anyway, a separate `COUNT WHERE status = "active"` index is usually redundant. In this case, a standard B-tree is preferred.

* When to use `COUNT WHERE` instead: materialised cardinality for a fixed condition you do not want to back with a B-tree; compound predicates without a covering index; or a dedicated counter separate from lookup indexes.

The following chart sums up a few use cases and when to prefer one vs. the other.

| Goal | Prefer |
| --- | --- |
| `count() … GROUP ALL` with no `WHERE` | Nothing extra required; `CountScan` counts record keys. Unconditional `COUNT` is optional. |
| `count() … WHERE field = value GROUP ALL` on a field you already filter on | `FIELDS field` B-tree (also supports `SELECT`, `ORDER BY`, and other predicates) |
| Many per-value counts on the same field | One B-tree on that field |
| One fixed combined predicate (`IN`, `AND`, etc.) counted repeatedly | `COUNT WHERE` with the **exact** same expression in the query |
| Fast counts for a predicate but **no** B-tree on those fields | `COUNT WHERE` |
| Compound `WHERE` with no covering composite B-tree | `COUNT WHERE` with the exact compound condition |

#### Storage footprint

Count indexes and B-tree indexes store different shapes of data, so size is not the same even when query performance is similar.

A **B-tree index** stores one entry per indexed record: encoded field value(s) plus the record id in the key. Storage grows **with the number of records** in the table (O(n) for that index).

A **`COUNT WHERE` index** does not store per-record field keys. It appends small **delta entries** (`IndexCountKey`) when records enter or leave the predicate, then **compacts** them into a single aggregate entry in the background. In steady state, footprint is usually **much smaller** than a B-tree on the same field, often a handful of keys rather than one per record.

So `COUNT WHERE` can be attractive when you need fast filtered counts **without** paying the per-record storage of a B-tree if it will not be used for anything else.

To compare indexed and non-indexed performance, the `WITH NOINDEX` clause can be used.

```surql
-- Slow path: scan every record
SELECT count() FROM item WITH NOINDEX WHERE status = "active" GROUP ALL;

-- Fast path: count index deltas (or B-tree keys if a covering index exists)
SELECT count() FROM item WHERE status = "active" GROUP ALL;
```

#### Multiple conditions

As each `COUNT WHERE` index tracks one fixed predicate, it does not accelerate several different counts unless each query repeats the **exact** condition stored in the index.

```surql
DEFINE INDEX openish_count ON person COUNT
    WHERE status IN ["active", "non-active", "delayed"];

-- Fast only when the WHERE matches the index exactly
SELECT count() FROM person
    WHERE status IN ["active", "non-active", "delayed"]
    GROUP ALL;
```

In the above example, it does not also speed up `WHERE status = "active" GROUP ALL` or other subsets.

For separate per-status totals, one `FIELDS status` B-tree is usually simpler than one `COUNT WHERE` index per value. See [When to use which](/docs/reference/query-language/statements/define/indexes.md#when-to-use-which).

Use [`EXPLAIN ANALYZE`](/docs/reference/query-language/statements/explain.md) to confirm `IndexCountScan` is selected. If the query `WHERE` differs even slightly from the index condition, SurrealDB falls back to a full scan.

#### Other `COUNT` syntax notes

```surql
-- Other clauses like `COMMENT` are fine
DEFINE INDEX idx ON users COUNT
    COMMENT "Users are expected to grow substantially so index the count"
    CONCURRENTLY;

-- Conditional count indexes
DEFINE INDEX active_users ON users COUNT WHERE status = "active" CONCURRENTLY;

-- But not `FIELD`
DEFINE INDEX idx2 ON person FIELD name;
```

```text title="Error output"
Parse error: Expected at least one column - Use FIELDS to define columns
 --> [1:29]
  |
1 | DEFINE INDEX idx2 ON person FIELD name;
  |                             ^^^^^
```

### Full-text search (`FULLTEXT`) index

Enables efficient searching through textual data, supporting advanced text-matching features like proximity searches and keyword highlighting.

The [Full-Text search](/docs/learn/data-models/full-text-search/overview.md) index helps implement comprehensive search functionalities in applications, such as searching through articles, product descriptions, and user-generated content.

The following example creates a full-text search index for a `name` field on a `user` table.

```surql
-- Define the an analyzer with
DEFINE ANALYZER example_ascii TOKENIZERS class FILTERS ascii;
-- Since 3.0.0: only FULLTEXT used to benefit from concurrent full-text search
DEFINE INDEX userNameIndex ON TABLE user FIELDS name
	FULLTEXT ANALYZER example_ascii BM25 HIGHLIGHTS;
```

- `SEARCH` or `FULLTEXT`: By using the `SEARCH` keyword, you enable full-text search on the specified field.
- `ANALYZER ascii`: Uses a custom [analyzer](/docs/reference/query-language/statements/define/analyzer.md) called `example_ascii` which uses the class tokenizer and `ascii` filter to analyse the text input.
- `BM25`: Ranking algorithm used for relevance scoring. BM25 weighs a term by how rare it is, and every matching term gets a weight above zero, so [`search::score`](/docs/reference/query-language/functions/database-functions/search.md#searchscore) is positive for every match. Before SurrealDB 4.0, the weight of a term appearing in half or more of the indexed documents was clamped to zero, which made `search::score` return `0` for it. See [how common terms are weighted](/docs/learn/data-models/full-text-search/scoring-and-ranking.md#how-common-terms-are-weighted).
- `HIGHLIGHTS`: Allows keyword highlighting in search results output when using the [`search::highlight`](/docs/reference/query-language/functions/database-functions/search.md#searchhighlight) function
- `FIELDS`: a full-text search index can only be used on one field at a time. To use full-text search on more than one field, use a separate `DEFINE INDEX` statement for each one.

#### A field that is unique and searchable

An index has a single kind, such as `UNIQUE` or `FULLTEXT`. For a field that has to be both unique and searchable, define two indexes on it:

```surql
DEFINE ANALYZER simple TOKENIZERS blank FILTERS lowercase;
DEFINE INDEX title_unique ON book FIELDS title UNIQUE;
DEFINE INDEX title_search ON book FIELDS title FULLTEXT ANALYZER simple BM25;

CREATE book:1 SET title = 'The Grey Book';
SELECT id FROM book WHERE title @@ 'grey';
```

```surql title="Output"
[{ id: book:1 }]
```

Both indexes are used without naming them: the query planner chooses the index by the operator in the condition, so `WHERE title = 'The Grey Book'` uses `title_unique` and `WHERE title @@ 'grey'` uses `title_search`. [`WITH INDEX`](/docs/reference/query-language/statements/select.md#the-with-clause) is not needed here, and naming the index that cannot serve the operator, as in `WITH INDEX title_search` with `=`, makes the query scan the table instead.

From SurrealDB 4.0, a `DEFINE INDEX` takes at most one of `UNIQUE`, `COUNT`, `FULLTEXT`, `HNSW`, `DISKANN` and `SPATIAL`. Writing two kinds in one statement is a parse error that points at the second kind, and the same kind written twice reports that it is given twice. SurrealDB 3.x accepts the statement below without an error but keeps only the last kind, so the index is a `FULLTEXT` index and the `UNIQUE` check is silently dropped. Define two indexes, as above, on every version:

```surql
DEFINE INDEX title ON book FIELDS title UNIQUE FULLTEXT ANALYZER simple;
```

```text title="Error output"
Parse error: Cannot combine FULLTEXT with UNIQUE
 --> [1:48]
  |
1 | DEFINE INDEX title ON book FIELDS title UNIQUE FULLTEXT ANALYZER simple;
  |                                                ^^^^^^^^ an index can only be one of UNIQUE, COUNT, FULLTEXT, HNSW, DISKANN or SPATIAL
 --> [1:41]
  |
1 | DEFINE INDEX title ON book FIELDS title UNIQUE FULLTEXT ANALYZER simple;
  |                                         ^^^^^^ First given here
```

The `UNIQUE` index above compares titles exactly, while the search ignores case. To make the unique check match the same way as the search, store a key built with the analyzer itself, using [`search::analyze()`](/docs/reference/query-language/functions/database-functions/search.md#searchanalyze), and make the key unique. With the `ascii` filter, the key also ignores accents, which a [computed value](#indexing-a-computed-value) such as `nickname.lowercase()` does not:

```surql
DEFINE ANALYZER ascii_lcase TOKENIZERS blank FILTERS lowercase, ascii;
DEFINE FIELD nickname ON user TYPE string;
DEFINE FIELD nickname_key ON user VALUE search::analyze('ascii_lcase', nickname).join(' ');
DEFINE INDEX nickname_unique ON user FIELDS nickname_key UNIQUE;
DEFINE INDEX nickname_search ON user FIELDS nickname FULLTEXT ANALYZER ascii_lcase BM25;

CREATE user:1 SET nickname = 'Zoë';
CREATE user:2 SET nickname = 'ZOE';
```

```text title="Error output"
Database index `nickname_unique` already contains 'zoe', with record `user:1`
```

`search::analyze()` returns the tokens as an array, and `.join(' ')` turns them into one string. The key is computed again on each write, so do not make the field `READONLY`, or a changed nickname keeps its old key. A lookup on the key uses the unique index:

```surql
SELECT id FROM user WHERE nickname_key = 'zoe' EXPLAIN;
```

```surql title="Output"
{
	attributes: {
		projections: 'id'
	},
	children: [
		{
			attributes: {
				access: "= 'zoe'",
				direction: 'Forward',
				index: 'nickname_unique',
				predicate: "nickname_key = 'zoe'"
			},
			context: 'Db',
			operator: 'IndexScan'
		}
	],
	context: 'Db',
	operator: 'SelectProject'
}
```

#### `FULLTEXT` vs. `SEARCH`

Since version 3.0.0, using `FULLTEXT ANALYZER` is the syntax used for a text analyzer. The `FULLTEXT` clause allows for more performant [concurrent full-text search](https://github.com/surrealdb/surrealdb/pull/5571), as well as the ability to [use the `OR` operator](https://github.com/surrealdb/surrealdb/pull/6179).

### Spatial index

_(since v4.0.0)_

A `SPATIAL` index lets a query find the records whose geometry lies in an area without reading every record of the table. It indexes a field holding a [geometry](/docs/reference/query-language/language-primitives/data-types/geometries.md), such as a `geometry<point>`, and it can index any geometry type.

```syntax title="Syntax"
DEFINE INDEX @name ON [ TABLE ] @table
	FIELDS [ @prefix_field, ... , ] @geometry_field SPATIAL
```

The index serves these conditions on the indexed field:

- The spatial operators `INSIDE`, `CONTAINS`, `INTERSECTS`, `CONTAINSANY`, `CONTAINSALL`, `ANYINSIDE` and `ALLINSIDE`, with the field on either side.
- A radius in metres given with [`geo::distance`](/docs/reference/query-language/functions/database-functions/geo.md#geodistance) and `<` or `<=`, such as `geo::distance(location, $here) < 10000`. The arguments can be in either order, and the comparison can be written either way round, as in `10000 > geo::distance(location, $here)`.
- Several of these conditions joined with `AND` or `OR`, and a condition beside one that another index serves, such as `status = 'open' AND location INSIDE $area`.

The following example indexes the locations of six cities and finds those within 400 km of London:

```surql
DEFINE TABLE city SCHEMAFULL;
DEFINE FIELD name ON city TYPE string;
DEFINE FIELD location ON city TYPE geometry<point>;
DEFINE INDEX city_location ON city FIELDS location SPATIAL;

INSERT INTO city [
	{ id: city:london, name: 'London', location: (-0.1276, 51.5072) },
	{ id: city:paris, name: 'Paris', location: (2.3522, 48.8566) },
	{ id: city:brussels, name: 'Brussels', location: (4.3517, 50.8503) },
	{ id: city:amsterdam, name: 'Amsterdam', location: (4.9041, 52.3676) },
	{ id: city:berlin, name: 'Berlin', location: (13.4050, 52.5200) },
	{ id: city:tokyo, name: 'Tokyo', location: (139.6917, 35.6895) }
] RETURN NONE;

SELECT VALUE name FROM city
	WHERE geo::distance(location, (-0.1276, 51.5072)) < 400000
	ORDER BY name;
```

```surql title="Output"
['Amsterdam', 'Brussels', 'London', 'Paris']
```

The index stores each geometry as cells of a grid over the globe. A query reads the ranges of cells that cover its area and then checks each record it finds against the exact condition. [`EXPLAIN`](/docs/reference/query-language/clauses/explain.md) shows one `IndexScan` for each range:

```surql
-- Setup from the example above
DEFINE TABLE city SCHEMAFULL;
DEFINE FIELD name ON city TYPE string;
DEFINE FIELD location ON city TYPE geometry<point>;
DEFINE INDEX city_location ON city FIELDS location SPATIAL;
INSERT INTO city [
	{ id: city:london, name: 'London', location: (-0.1276, 51.5072) },
	{ id: city:paris, name: 'Paris', location: (2.3522, 48.8566) },
	{ id: city:brussels, name: 'Brussels', location: (4.3517, 50.8503) },
	{ id: city:amsterdam, name: 'Amsterdam', location: (4.9041, 52.3676) },
	{ id: city:berlin, name: 'Berlin', location: (13.4050, 52.5200) },
	{ id: city:tokyo, name: 'Tokyo', location: (139.6917, 35.6895) }
] RETURN NONE;

EXPLAIN SELECT VALUE name FROM city
	WHERE geo::distance(location, (-0.1276, 51.5072)) < 400000;
```

```surql title="Output"
'ProjectValue [ctx: Db] [expr: name]
    UnionIndexScan [ctx: Db] [table: city, branches: 5, decode: [name]]
        IndexScan [ctx: Db] [table: city, index: city_location, access: >=1655143231802834952 <=1655283969291190264, point_filter: geo::distance(location, (-0.1276, 51.5072)) < 400000, direction: Forward]
        IndexScan [ctx: Db] [table: city, index: city_location, access: >=1655635813012078600 <=1655706181756256248, point_filter: geo::distance(location, (-0.1276, 51.5072)) < 400000, direction: Forward]
        IndexScan [ctx: Db] [table: city, index: city_location, access: >=1655776550500433928 <=1656481337453838328, point_filter: geo::distance(location, (-0.1276, 51.5072)) < 400000, direction: Forward]
        IndexScan [ctx: Db] [table: city, index: city_location, access: >=1802284275878330376 <=1803128700808462328, point_filter: geo::distance(location, (-0.1276, 51.5072)) < 400000, direction: Forward]
        IndexScan [ctx: Db] [table: city, index: city_location, access: >=1803410175785173000 <=1803691650761883640, point_filter: geo::distance(location, (-0.1276, 51.5072)) < 400000, direction: Forward]
'
```

The cells are rectangles of longitude and latitude, and each range is a run of neighbouring cells. Drawn on a map, the five ranges cover the 400 km circle with some margin. London is in one range and Paris, Brussels and Amsterdam are in another, while Berlin and Tokyo are in none, so the query never reads them:

<img src="~/assets/img/diagrams/light/spatial-index-light.webp" darkSrc="~/assets/img/diagrams/spatial-index.webp" alt="A map of north-west Europe with a dashed 400 km circle around London. Rectangular cells in five colours cover the circle, one colour for each IndexScan range. Range 3 holds London, range 4 holds Paris, Brussels and Amsterdam, and ranges 1, 2 and 5 find nothing. Berlin is outside every cell, so the query never reads it." />

A polygon works in the same way. With the records above, this query uses the index and returns the cities inside a box around the Low Countries:

```surql
SELECT VALUE name FROM city
	WHERE location INSIDE { type: 'Polygon', coordinates: [[[0, 48], [6, 48], [6, 53], [0, 53], [0, 48]]] }
	ORDER BY name;
```

```surql title="Output"
['Amsterdam', 'Brussels', 'Paris']
```

The index does not serve every condition on a geometry:

- `OUTSIDE`, and a `geo::distance` comparison with `>` or `>=`, read the whole table.
- An ordering by distance, such as `ORDER BY distance LIMIT 3` on `geo::distance(location, $here) AS distance`, sorts every record. To find the nearest records with the index, add a radius to the `WHERE` clause, so that only the records inside it are sorted.

#### Fields before the geometry

Fields listed before the geometry field make a compound index, which serves a query that compares each of them for equality, or with `CONTAINS` for an array field indexed with `.*`, and also has a spatial condition. A query with only the spatial condition does not use a compound index, so define a separate index on the geometry field alone as well if such queries are common.

```surql
DEFINE TABLE vehicle SCHEMAFULL;
DEFINE FIELD fleet ON vehicle TYPE string;
DEFINE FIELD location ON vehicle TYPE geometry<point>;
DEFINE INDEX vehicle_fleet_location ON vehicle FIELDS fleet, location SPATIAL;

INSERT INTO vehicle [
	{ id: vehicle:1, fleet: 'north', location: (-0.12, 51.51) },
	{ id: vehicle:2, fleet: 'north', location: (2.35, 48.85) },
	{ id: vehicle:3, fleet: 'south', location: (-0.10, 51.50) },
	{ id: vehicle:4, fleet: 'north', location: (-0.11, 51.52) }
] RETURN NONE;

SELECT VALUE id FROM vehicle
	WHERE fleet = 'north'
		AND geo::distance(location, (-0.1276, 51.5072)) < 10000
	ORDER BY id;
```

```surql title="Output"
[vehicle:1, vehicle:4]
```

#### Arrays and sets of geometries

A field of type `array<geometry<point>>` is indexed with `FIELDS stops SPATIAL`, and each geometry in it is indexed. For a `set<geometry<point>>`, or an array on a schemaless table, use `FIELDS stops.* SPATIAL`. The operators that take several geometries, such as `ANYINSIDE` and `ALLINSIDE`, then use the index:

```surql
DEFINE TABLE route SCHEMAFULL;
DEFINE FIELD stops ON route TYPE array<geometry<point>>;
DEFINE INDEX route_stops ON route FIELDS stops SPATIAL;

CREATE route:a SET stops = [(-0.12, 51.51), (2.35, 48.85)];
CREATE route:b SET stops = [(13.40, 52.52)];

SELECT VALUE id FROM route
	WHERE stops ANYINSIDE { type: 'Polygon', coordinates: [[[-1, 51], [1, 51], [1, 52], [-1, 52], [-1, 51]]] };
```

```surql title="Output"
[route:a]
```

#### Vector search inside an area

When a KNN query on an [HNSW](#hnsw-hierarchical-navigable-small-world) or [DISKANN](#diskann-disk-based-approximate-nearest-neighbours) index has a spatial condition in the same `WHERE` clause, the `SPATIAL` index first finds the records inside the area, and the vector search then ranks only those records. The query returns the `k` nearest records inside the area, rather than the `k` nearest records overall with those outside the area removed. In the following example, `place:bistro` in Paris has the same vector as `place:cafe`, but is outside the 10 km radius:

```surql
DEFINE TABLE place SCHEMAFULL;
DEFINE FIELD location ON place TYPE geometry<point>;
DEFINE FIELD embedding ON place TYPE array<float>;
DEFINE INDEX place_location ON place FIELDS location SPATIAL;
DEFINE INDEX place_embedding ON place FIELDS embedding HNSW DIMENSION 2;

INSERT INTO place [
	{ id: place:cafe, location: (-0.12, 51.51), embedding: [1.0, 0.0] },
	{ id: place:bakery, location: (-0.10, 51.50), embedding: [0.8, 0.2] },
	{ id: place:library, location: (-0.11, 51.52), embedding: [0.0, 1.0] },
	{ id: place:bistro, location: (2.35, 48.85), embedding: [1.0, 0.0] }
] RETURN NONE;

SELECT id, vector::distance::knn() AS distance FROM place
	WHERE geo::distance(location, (-0.1276, 51.5072)) < 10000
		AND embedding <|2,40|> [1.0, 0.0]
	ORDER BY distance;
```

```surql title="Output"
[
	{ distance: 0f, id: place:cafe },
	{ distance: 0.28284270931360533f, id: place:bakery }
]
```

#### Datastore format

A `SPATIAL` index needs a datastore that uses the [4.0 record format](/docs/operate/upgrading/3x-to-4x.md#the-40-record-format), because a `3.x` node cannot read it. A new datastore, and an in-memory or SurrealKV datastore after its first `4.0` start, already does. A TiKV datastore upgraded from `3.x` refuses `DEFINE INDEX ... SPATIAL` until every node runs `4.0` and the nodes start with `SURREAL_FEATURE_LEVEL=4.0`.

## Vector search indexes

Vector search indexes in SurrealDB support efficient [k-nearest neighbors](https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm) (kNN) and [Approximate Nearest Neighbor](https://en.wikipedia.org/wiki/Nearest_neighbor_search) (ANN) operations, which are used to perform similarity searches within complex, high-dimensional datasets and data types. Refer to the [Vector Search Cheat Sheet](/docs/learn/data-models/vector-search/vector-indexes.md#vector-search-cheat-sheet) for the parameters allowed. To decide between an HNSW and a DISKANN index, see [Choosing HNSW or DISKANN](#choosing-hnsw-or-diskann).

> [!NOTE]
> After a large insert or update, a vector index stores the new records separately until a background process merges them into its graph. Searches return correct results throughout, but are slower until that merge completes. [`INFO FOR INDEX`](/docs/reference/query-language/statements/info.md#index-information) reports this as `building.compacting`, which is separate from `building.status`.

> [!WARNING]
> From 3.0.0 until 3.3.1, an HNSW or DISKANN index lost track of records when more than nine of them held an identical vector. KNN results left out the tenth and later records, and could return fewer than `k` results after such records were deleted. SurrealDB 3.3.1 fixes this for new writes, but an index that was already affected stays that way until it is rebuilt. After upgrading, run [`REBUILD INDEX`](/docs/reference/query-language/statements/rebuild.md) on each vector index whose table can hold more than nine records with the same vector, such as duplicated embeddings or a placeholder vector.

> [!WARNING]
> Before SurrealDB 3.3.1, a KNN query could return fewer than `k` results for a user whose table `SELECT` permission hides some records. With no other condition in the `WHERE` clause, as in `WHERE embedding <|10,40|> $query`, hidden records took places in the top `k` and were then removed, so a record user who can see few of the records could get no results at all. Adding any other condition to the `WHERE` clause avoided this. A DISKANN index could also return no results for a query with a `SELECT` permission or another `WHERE` condition once the index had been compacted. SurrealDB 3.3.1 applies the permission while it searches, so both return the nearest records that the user can see.

### Types

When defining a vector index with [HNSW](#hnsw-hierarchical-navigable-small-world), you can define the types the vector will be stored in. The `TYPE` clause is optional and can be used to specify the data type of the vector. SurrealDB supports the following types:
`F64` | `F32` | `F16` | `I64` | `I32` | `I16` | `I8` | `U8`

- `F64`: Represents 64-bit floating-point numbers (double precision floating-point numbers).
- `F32`: Represents 32-bit floating-point numbers (single precision floating-point numbers).
- `F16`: Represents 16-bit floating-point numbers (half precision floating-point numbers).
- `I64`: Represents 64-bit signed integers.
- `I32`: Represents 32-bit signed integers.
- `I16`: Represents 16-bit signed integers.
- `I8`: Represents 8-bit signed integers.
- `U8`: Represents 8-bit unsigned integers.

> [!NOTE]
> In SurrealDB the default type for vectors is `F32`.

> [!WARNING]
> An integer `TYPE` truncates each component rather than quantising it, so a normalised embedding, with components between -1 and 1, is stored as all zeros and KNN results become arbitrary. Use `F32` or `F16` for embeddings.

[DISKANN](#diskann-disk-based-approximate-nearest-neighbours) indexes, available from SurrealDB 3.1, accept a **narrower** set of element types: `F32`, `F16`, `I8`, and `U8` only, and only a subset of distance metrics - see the [DISKANN](#diskann-disk-based-approximate-nearest-neighbours) section below.

For example, to define a vector index with 64-bit signed integers, you can use the following query:

```surql
DEFINE INDEX idx_hnsw_embedding
  ON Document FIELDS items.embedding HNSW DIMENSION 4 TYPE I64;
```

### HNSW (Hierarchical Navigable Small World)

This method uses a graph-based approach to efficiently navigate and search in high-dimensional spaces.
While it is an approximate technique, it offers a high-performance balance between speed and accuracy, making it ideal for very large datasets.

> [!NOTE]
> Keep in mind the in-memory nature of HNSW when considering system resource allocation.

```surql
CREATE pts:3 SET point = [8,9,10,11];
DEFINE INDEX mt_pts ON pts FIELDS point HNSW DIMENSION 4 DIST EUCLIDEAN EFC 150 M 12;
// See output for info on EFC,M,MO AND LM
INFO FOR TABLE pts;
SELECT id FROM pts WHERE point <|10,40|> [2,3,4,5];
```

In the example above, you may notice the `EFC` and `M` parameters. These are optional to your query but are parameters of the [HNSW algorithm](https://arxiv.org/abs/1603.09320) and can be used to tune the index for better performance.

- M (Max Connections per Element):
Defines the maximum number of bidirectional links (neighbors) per node in each layer of the graph, except for the lowest layer. This parameter controls the connectivity and overall structure of the network. Higher values of M generally improve search accuracy but increase memory usage and construction time.

- EFC (EF construction):
Stands for "exploration factor during construction." This parameter determines the size of the dynamic list for the nearest neighbor candidates during the graph construction phase. A larger efConstruction value leads to a more thorough construction, improving the quality and accuracy of the search but increasing construction time. The default value is 150.

- M0 (Max Connections in the Lowest Layer):
Similar to M, but specifically for the bottom layer (the base layer) of the graph. This layer contains the actual data points. M0 is often set to twice the value of M to enhance search performance and connectivity at the base layer, at the cost of increased memory usage.

- LM (Multiplier for Level Generation):
Used to determine the maximum level l for a new element during its insertion into the hierarchical structure. It is used in the formula l←⌊−ln⁡(unif(0..1))⋅mL⌋, where unif(0..1) is a uniform random variable between 0 and 1. This parameter influences the distribution of elements across different levels, impacting the overall balance and efficiency of the search structure.

> [!NOTE]
> You can only provide TYPE, M, and EFC. SurrealDB automatically computes M0 and LM with the most appropriate value. If not specified, M AND EFC are set to 12 and 150, respectively.  Refer to the [Vector Search Cheat Sheet](/docs/learn/data-models/vector-search/vector-indexes.md#vector-search-cheat-sheet) for the parameters allowed.

#### Memory cache usage for HNSW indexes

_(since v3.0.0)_

HNSW vector search caches element vectors in a bounded memory cache, reducing memory spikes and improving stability under load. The cache is a single budget **shared across every HNSW index** in the process, not a per-index allowance. It defaults to 256 MiB and can be modified via the `SURREAL_HNSW_CACHE_SIZE` [environment variable](/docs/reference/cli/db/environment-variables.md). The value is an integer number of bytes - for example, `268435456` for the 256 MiB default.

This budget covers the cached **vectors** only. As noted above, the HNSW graph itself is held in memory: it is loaded on first use and is not bounded by this setting, so it must be sized for separately. If the full graph will not fit in RAM, DISKANN below is the index designed for that case.

### DISKANN (disk-based approximate nearest neighbours)

_(since v3.1.0)_

[DiskANN](https://arxiv.org/abs/1907.01668)-style indexes provide **on-disk** approximate nearest-neighbour graphs. They are aimed at **very large** embedding sets where keeping the full graph in RAM (as with HNSW) is impractical: vectors and graph structure are persisted in the key-value store and paged through a bounded cache, trading some latency for a much larger working set.

> [!NOTE]
> DISKANN is available on 64-bit platforms and in WebAssembly builds, including the [Wasm engine](/docs/reference/javascript/engines/wasm.md) in a browser. Other 32-bit platforms, such as 32-bit x86 and 32-bit Arm, do not include DISKANN and use HNSW as their vector index.

#### Syntax and defaults

The clause mirrors HNSW: `DISKANN DIMENSION …` followed by optional `TYPE`, `DIST`, tuning knobs, and `HASHED_VECTOR`.

```surql
DEFINE INDEX diskann_pts
  ON pts FIELDS point DISKANN DIMENSION 4 DIST EUCLIDEAN TYPE F32;
-- Same index with defaults written out explicitly:
-- DEFINE INDEX diskann_pts ON pts FIELDS point DISKANN DIMENSION 4 DIST EUCLIDEAN TYPE F32 DEGREE 64 L_BUILD 100 ALPHA 1.2;
```

| Clause | Default | Notes |
| --- | --- | --- |
| `DIST` | `EUCLIDEAN` | Only `EUCLIDEAN`, `COSINE`, `INNER_PRODUCT`, and `COSINE_NORMALIZED` are valid for DISKANN. |
| `TYPE` | `F32` | Must be one of `F32`, `F16`, `I8`, `U8`. `COSINE_NORMALIZED` further requires `F32` or `F16`. From SurrealDB 4.0, `I8` and `U8` allow a `DIMENSION` of at most 33025. |
| `DEGREE` | `64` | Target maximum graph degree (`> 0`). |
| `L_BUILD` | `100` | Construction search-list size (`> 0`). |
| `ALPHA` | `1.2` | DiskANN pruning parameter. |
| `HASHED_VECTOR` | off | Same semantics as for HNSW - hash-stabilised vector - document keys. |

Queries use the **same** KNN operator shape as HNSW: `<|K, EF|>` (approximate) or `<|K, DIST|>` when the distance matches the index, letting the optimiser pick the DISKANN graph. The second number in the approximate form bounds the dynamic candidate list during search (analogous to HNSW `EF`).

#### Memory model and cache size

While HNSW's graph is held resident in memory, a DISKANN index is **key-value-backed**. The graph, its adjacency lists, and the full-precision element vectors are persisted in the key-value store (for example, on disk under SurrealKV) and remain the source of truth. Only a bounded in-memory cache holds the hot working set, while cold nodes and vectors are streamed from the key-value store on demand. A DISKANN index's resident memory is therefore bounded by the cache size rather than by the size of the dataset, which is what makes it suitable for larger-than-memory workloads.

Vectors are stored at **full precision**, and every distance a query reports is computed from the full vector. From SurrealDB 4.0, a DISKANN index of `TYPE F32` or `TYPE F16` also keeps an 8-bit code of each vector, which adds one byte per dimension to each vector. A search compares candidates using these codes, then ranks its nearest results from the full vectors. An index defined before 4.0 has the codes only after [`REBUILD INDEX`](/docs/reference/query-language/statements/rebuild.md), and setting the [`SURREAL_DISKANN_QUANTIZED_SEARCH`](/docs/reference/cli/db/environment-variables.md#vector-search-config) environment variable to `false` makes a search compare full vectors throughout. Apart from the codes, the size of each vector depends only on the chosen `TYPE` (`F32`, `F16`, `I8`, or `U8`).

The cache is a single budget **shared across every DISKANN index** in the process. It defaults to 256 MiB and can be capped with the `SURREAL_DISKANN_CACHE_SIZE` [environment variable](/docs/reference/cli/db/environment-variables.md#cache-config), the DISKANN counterpart of `SURREAL_HNSW_CACHE_SIZE`. The value is an integer number of bytes - for example, `268435456` for the 256 MiB default.

#### Choosing HNSW or DISKANN

Use HNSW unless the index is too large for memory. HNSW keeps its graph in memory, so it gives the lowest latency when the graph is loaded and the working set fits in RAM. Use DISKANN when the embeddings are much larger than the RAM of the server. It keeps the graph and the vectors in the key-value store and holds only a bounded cache in memory, so each query can need more disk I/O. Both index types answer the same `<|K, EF|>` operator, so a query does not change when you change the index type.

| Concern | Prefer HNSW | Prefer DISKANN |
| --- | --- | --- |
| Working set size | Fits in memory, with room for the graph and for the HNSW vector cache | Much larger than RAM; cold data stays in the key-value store |
| Latency profile | Lowest latency when the graph is loaded in memory | Extra I/O for each node or vector that is not in the cache |
| Vector element types | `F64`, `F32`, `F16`, `I64`, `I32`, `I16`, `I8` and `U8` | `F32`, `F16`, `I8` and `U8` only |
| Deployment target | All builds, including 32-bit and WebAssembly | 64-bit native and WebAssembly builds, including the browser; not 32-bit x86 or Arm |

### Brute Force method

The Brute Force method is suitable for tasks with smaller datasets or when the highest accuracy is required.
Brute Force currently supports [Euclidean](/docs/reference/query-language/functions/database-functions/vector.md#vectordistanceeuclidean), [Cosine](/docs/reference/query-language/functions/database-functions/vector.md#vectorsimilaritycosine), [Manhattan](/docs/reference/query-language/functions/database-functions/vector.md#vectordistancemanhattan) and [Minkowski](/docs/reference/query-language/functions/database-functions/vector.md#vectordistanceminkowski) distance functions.

In the example below, the query searches for points closest to the vector `[2,3,4,5]` and uses [vector functions](/docs/reference/query-language/functions/database-functions/vector.md) to calculate the distance between two points, indicated by `<|2,EUCLIDEAN|>`.

```surql
CREATE pts:1 SET point = [1,2,3,4];
CREATE pts:2 SET point = [4,5,6,7];
CREATE pts:3 SET point = [8,9,10,11];
LET $pt = [2,3,4,5];
SELECT id, vector::distance::euclidean(point, $pt) AS dist FROM pts WHERE point <|2,EUCLIDEAN|> $pt;
SELECT id FROM pts WHERE point <|2,EUCLIDEAN|> $pt EXPLAIN;
```

## Verifying index use in queries

The [`EXPLAIN` clause](/docs/reference/query-language/clauses/explain.md) shows the execution plan of a query, including whether it uses an index.

```surql
DEFINE INDEX userEmailIndex ON user FIELDS email UNIQUE;
CREATE user:test SET email = 'test@surrealdb.com';

SELECT * FROM user WHERE email = 'test@surrealdb.com' EXPLAIN FULL;
```

An `IndexScan` operator names the index the query planner used. With `FULL`, each operator also reports `metrics`, including how many rows it produced (`output_rows`).

```surql title="Example output"
{
	attributes: {
		projections: '*'
	},
	children: [
		{
			attributes: {
				access: "= 'test@surrealdb.com'",
				direction: 'Forward',
				index: 'userEmailIndex',
				predicate: "email = 'test@surrealdb.com'"
			},
			context: 'Db',
			metrics: {
				elapsed_ns: 2380999,
				output_batches: 1,
				output_rows: 1,
				records_fetched: 0
			},
			operator: 'IndexScan'
		}
	],
	context: 'Db',
	metrics: {
		elapsed_ns: 47083,
		output_batches: 1,
		output_rows: 1,
		records_fetched: 0
	},
	operator: 'SelectProject',
	total_rows: 1
}
```

## Using the `ANY`/`ALL` operators for string indexes

_(since v2.4.0)_

An index on a string field is used by `=` and by `IN` with an array of values. The containment operators `CONTAINS`, `CONTAINSANY`, `ALLINSIDE` and `ANYINSIDE` return the same records on such a field, but they scan the table, because they only use an index defined on the elements of an array field (such as `tags.*`), through a condition that takes each element (such as `tags.* CONTAINS 'x'`). `CONTAINS` on a string is a substring match.

```surql
DEFINE FIELD name ON account TYPE string;
DEFINE INDEX name_index ON account FIELDS name;

CREATE account:billy SET name = "Billy McConnell";

-- IN uses the index
EXPLAIN SELECT * FROM account WHERE name IN ["Billy McConnell"];
//- "SelectProject [ctx: Db] [projections: *]\n    IndexScan [ctx: Db] [index: name_index, access: = 'Billy McConnell', direction: Forward, predicate: name INSIDE ['Billy McConnell']]\n"

-- CONTAINSANY scans the table
EXPLAIN SELECT * FROM account WHERE name CONTAINSANY ["Billy McConnell"];
//- "SelectProject [ctx: Db] [projections: *]\n    TableScan [ctx: Db] [table: account, direction: Forward, predicate: name CONTAINSANY ['Billy McConnell'], pre_decode_filter: yes]\n"
```

> [!NOTE]
> In SurrealDB 2.4 and later 2.x releases, `CONTAINSANY`, `ALLINSIDE` and `ANYINSIDE` with the values in an array used an index on a string field, and `CONTAINS` did not. From 3.0.0, use `=` or `IN` to query a string index.

## Rebuilding Indexes

Indexes can be rebuilt using the [`REBUILD`](/docs/reference/query-language/statements/rebuild.md) statement. This can be useful when you want to update the index definition or when you want to rebuild the index to optimise performance.

You may want to rebuild an index over time to ensure that the index is up-to-date with the latest data in the table.

```surql
REBUILD INDEX userEmailIndex ON user;
```

## Using `IF NOT EXISTS` clause

The `IF NOT EXISTS` clause can be used to define an index only if it does not already exist. If an index with the same name already exists, the statement does nothing and returns `NONE`, even when the new definition is different. The existing index keeps its old definition. Without the clause, defining an index that already exists returns the error `The index 'example' already exists`.

An existing index is not built again, but a changed definition in the statement is never applied either. To change an index, use the `OVERWRITE` clause, or `REMOVE INDEX` followed by `DEFINE INDEX`. For a schema script that runs each time an application starts, `OVERWRITE` is usually the better choice from SurrealDB 4.0, because it applies a changed definition and keeps an unchanged index as it is.

```surql
-- Create a INDEX if it does not already exist
DEFINE INDEX IF NOT EXISTS example ON example FIELDS example;
```

## Using `OVERWRITE` clause

The `OVERWRITE` clause can be used to define an index and overwrite an existing one if it already exists. You should use the `OVERWRITE` clause when you want to modify an existing index definition. If the index already exists, the `DEFINE INDEX` statement will overwrite the existing definition with the new one.

From SurrealDB 4.0, `OVERWRITE` builds the index again only when it needs to. When the table, the fields, and the index type with its parameters are the same as before, and the existing index is ready, the index and its data are kept and only the definition is replaced. A changed `COMMENT` is therefore applied without a rebuild, and a schema script that runs each time an application starts can use `OVERWRITE` for every index. The index is built again from the data in the table when the definition changes, when the existing index is still building or failed to build, or when it was built by an earlier release in an older index format.

An unchanged `OVERWRITE` does not tokenise the records again after an analyzer changes, because the index definition is the same. To build an unchanged index again, use [`REBUILD INDEX`](/docs/reference/query-language/statements/rebuild.md).

Before SurrealDB 4.0, `OVERWRITE` built the index again every time, even when the definition had not changed. On those versions, `IF NOT EXISTS` is the way to define an unchanged index without a rebuild.

```surql
-- Create an INDEX and overwrite if it already exists
DEFINE INDEX OVERWRITE example ON example FIELDS example;
```

## Using `CONCURRENTLY` clause
Building indexes can be lengthy and may time out before they're completed. Without `CONCURRENTLY`, `DEFINE INDEX` blocks until the index is fully built (or the build fails). The `CONCURRENTLY` clause can be used when you need the statement to return immediately while indexing continues in the background. This allows other operations to keep running while the index builds, during which you can monitor progress with [INFO FOR INDEX](/docs/reference/query-language/statements/info.md#index-information).

```surql
-- Create an INDEX concurrently
DEFINE INDEX test ON user FIELDS email CONCURRENTLY;
INFO FOR INDEX test ON user;
INFO FOR INDEX test ON user;
```

When building an index concurrently, SurrealDB starts the index creation as a background process. You can monitor the status of this process using the `INFO FOR INDEX` statement. The output includes a building block that provides several key details:

```surql
-- Check the indexing status
INFO FOR INDEX test ON user;
```

```surql title="Possible output"
-- Query

{
    building:  {
        initial: 8143,
        pending: 19,
        status: 'indexing',
        updated: 80
    }
}
```
The indexing process consists of two stages: **initial** and **update**.

1. **Initial Stage:**

   During this stage, SurrealDB indexes all existing records. The number of indexed records is represented by the `initial` property. While this stage is in progress, any new inserts, updates, or deletions are tracked as `pending`.

2. **Update Stage:**

   Once the initial stage is completed, SurrealDB begins indexing the pending records accumulated during the initial phase. At this point:

   - The `initial` count remains stable.
   - The `pending` count should gradually decrease as these records are processed; however, it may temporarily increase if new modifications occur during indexing.
   - The `updated` property indicates the number of pending records that have been indexed during this stage.

When both stages are complete, the index status changes to **ready**, meaning that the index is now automatically updated within the same transaction that inserts, updates, or deletes records.

```surql
-- Query

{
	building: {
		status: 'ready'
	}
}
```

If the build fails, for example because a `UNIQUE` index finds two records with the same value, the index stays defined and `INFO FOR INDEX` shows `status: 'error'` with the reason. From SurrealDB 4.0, while a `UNIQUE` index is in this state, a write that adds a value to it is refused, because the index cannot check that the value is unique. Deletes, and writes that do not set the indexed fields, still succeed. To recover, remove the duplicate values and run [`REBUILD INDEX`](/docs/reference/query-language/statements/rebuild.md), or remove the index with `REMOVE INDEX`.

```surql
CREATE t:1 SET a = 1;
CREATE t:2 SET a = 1;
DEFINE INDEX ua ON t FIELDS a UNIQUE CONCURRENTLY;
-- Wait for the background build to fail
SLEEP 500ms;
CREATE t:3 SET a = 2;
```

```surql title="Error output"
'Database index `ua` on table `t` failed to build, so it cannot enforce UNIQUE for this write: fix the duplicate values and run REBUILD INDEX, or REMOVE INDEX'
```

## Defining an index inside a transaction

A `DEFINE INDEX` without `CONCURRENTLY` builds the index in transactions of its own, which commit before the transaction that holds the statement. When the statement shares its transaction with other statements, such as inside `BEGIN ... COMMIT`, and the table already holds records, the rest of that transaction cannot read the entries the build wrote. From SurrealDB 4.0, the transaction handles the index as follows until it commits:

- Queries in the transaction do not use the new index. A query on the indexed fields reads the table instead, so its result is correct. A full-text match fails with `There was no suitable index supporting the expression`, and a nearest-neighbour search ranks the records of the table, as it does while a vector index builds.
- A `UNIQUE` index still checks the values the build indexed, so a duplicate of an existing value fails at the statement with the usual uniqueness error.
- A statement that deletes a record the build indexed, or changes one of its indexed fields, is refused and names the record and the index. A change to fields outside the index is allowed, and so is any change to a record that the transaction created after the definition.

```surql
CREATE product:1 SET sku = 'A-1';

BEGIN;
DEFINE INDEX sku ON product FIELDS sku UNIQUE;
UPDATE product:1 SET sku = 'A-2';
COMMIT;
```

```surql title="Error output"
'Cannot change record `product:1`: index `sku` was defined by this transaction, and the build that ran for it wrote an entry for the record that this transaction cannot see. Define the index CONCURRENTLY, or commit the definition before changing the record.'
```

As the error says, define the index with `CONCURRENTLY`, or commit the definition before the statements that change the records. A `CONCURRENTLY` build starts after the transaction closes, so none of these rules applies to it. An index defined over a table with no records has nothing to build, and the transaction reads and writes it as usual. If the transaction is cancelled or fails, the definition is removed with it.

The order matters in the other direction too. From SurrealDB 4.0, a `DEFINE INDEX` without `CONCURRENTLY` is refused when its transaction has already created, changed or deleted a record of the table, because the build cannot see those writes. The refusal comes before anything of the index is written, and the rest of the transaction fails with it:

```surql
BEGIN;
CREATE user:one SET email = 'one@example.com';
DEFINE INDEX email ON user FIELDS email UNIQUE;
COMMIT;
```

```surql title="Error output"
'Cannot define index `email` on `user`: this transaction has written records of `user`, which a build without CONCURRENTLY cannot see. Define the index CONCURRENTLY, or commit those writes first.'
```

The same applies to a block, a loop, a function and a transaction that a client holds open. Writes to other tables, reads of the table, a write that a rollback to a save point undid, and an `IF NOT EXISTS` definition of an index that already exists are not refused.

While such a transaction is open, other sessions on the same node cannot write the table without the risk that the build misses the write. From SurrealDB 4.0, a write by another session to a record of the table waits until the defining transaction ends. If that transaction commits, the waiting write fails with a retryable transaction conflict, and its retry sees the new index. If it rolls back, the write continues. A write that has waited for 60 seconds fails with the same retryable conflict. Reads, writes to other tables, and the defining transaction's own writes do not wait. The same applies to a `DEFINE INDEX OVERWRITE` that replaces an index, even as a statement of its own, because it builds inside its own transaction.

This wait is kept in the memory of the node that runs the definition. On a datastore that several nodes write, such as TiKV, a write through another node does not wait, and the index can miss it. On such a datastore, and on any table that other sessions write often, define the index as a statement of its own or with `CONCURRENTLY`, whose build starts only once the definition has committed.

## The `DEFER` clause

_(since v2.5.0)_

> [!WARNING]
> `DEFER` is available in SurrealDB 2.5 through 2.x only. On 3.x the clause is rejected at parse time, and this section applies to 2.x deployments, so its example uses the 2.x `SEARCH ANALYZER` clause that 3.x renamed to `FULLTEXT ANALYZER`. On 3.x, use [`CONCURRENTLY`](/docs/reference/query-language/statements/define/indexes.md#using-concurrently-clause) to build an index in the background - note that it addresses initial builds, not the ongoing write-path queueing `DEFER` provided.

Index updates in SurrealDB occur synchronously during document operations. This ensures **immediate consistency**, in which all reads return the most recent write. However, this can become a bottleneck during high-volume parallel ingestion, leading to write-write conflicts and increased latency, particularly with Full-Text or Vector indexes.

The `DEFER` clause can be used in this case if **eventual consistency** is acceptable, namely a setting in which reads may return stale data for a short period, but will eventually converge to the most recent write. An index with this clause will be enqueued in a persistent background queue so that ingestion and indexing are decoupled.

```surql
DEFINE ANALYZER simple TOKENIZERS blank,class FILTERS lowercase;
DEFINE INDEX title_index ON blog FIELDS title
	SEARCH ANALYZER simple BM25(1.2,0.75) HIGHLIGHTS DEFER;
```

Note: As unique indexes offer a guarantee that no records that contravene the index will ever exist, the `UNIQUE` clause cannot be used together with `DEFER`.

## Performance Implications

When defining indexes, consider which fields are queried most frequently, and index those to optimise performance.

Indexes may improve the performance of SurrealQL statements. This may not be noticeable with small tables but it can be significant for large tables; especially when the indexed fields are used in the `WHERE` clause of a [`SELECT`](/docs/reference/query-language/statements/insert.md) statement.

Indexes can also impact the performance of write operations ([INSERT](/docs/reference/query-language/statements/insert.md), [UPDATE](/docs/reference/query-language/statements/update.md), [DELETE](/docs/reference/query-language/statements/delete.md)) since the index needs to be updated accordingly. Therefore, the need for read performance has to be balanced against write performance.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/namespace

# DEFINE NAMESPACE

The DEFINE NAMESPACE statement can be used to setup namespaces, which can contain multiple databases.

SurrealDB has a multi-tenancy model which allows you to scope databases to a namespace. There is no limit to the number of databases that can be in a namespace, nor is there a limit to the number of namespaces allowed. Only users with root access are authorised to create namespaces.

Suppose you are using SurrealDB to create a multi-tenant SaaS application. You can guarantee that the data of each tenant will be kept separate from other tenants if you put each tenant's databases into separate namespaces. A user then only has access to the information in the namespace they are a member of.

## Requirements

- You must be authenticated as a root owner or editor before you can use the `DEFINE NAMESPACE` statement.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
DEFINE NAMESPACE [ OVERWRITE | IF NOT EXISTS ] @name [ COMMENT @string ]
```

## Example usage
Below shows how you can create a namespace using the `DEFINE NAMESPACE` statement.

```surql
-- Namespace for Abcum Ltd.
DEFINE NAMESPACE abcum;
```

## Using `IF NOT EXISTS` clause

The `IF NOT EXISTS` clause can be used to define a namespace only if it does not already exist. You should use the `IF NOT EXISTS` clause when defining a namespace in SurrealDB if you want to ensure that the namespace is only created if it does not already exist. If the namespace already exists, the `DEFINE NAMESPACE` statement will return an error.

It's particularly useful when you want to safely attempt to define a namespace without manually checking its existence first.

On the other hand, you should not use the `IF NOT EXISTS` clause when you want to ensure that the namespace definition is updated regardless of whether it already exists. In such cases, you might prefer using the `OVERWRITE` clause, which allows you to define a namespace and overwrite an existing one if it already exists, ensuring that the latest version of the namespace definition is always in use.

```surql
-- Create a NAMESPACE if it does not already exist
DEFINE NAMESPACE IF NOT EXISTS example;
```

## Using `OVERWRITE` clause

The `OVERWRITE` clause can be used to define a namespace and overwrite an existing one if it already exists. You should use the `OVERWRITE` clause when you want to modify an existing namespace definition. If the namespace already exists, the `DEFINE NAMESPACE` statement will overwrite the existing namespace definition with the new one.

```surql
-- Create an NAMESPACE and overwrite if it already exists
DEFINE NAMESPACE OVERWRITE example;
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/overview

# DEFINE

DEFINE declares SurrealDB schema: namespaces, tables, fields, indexes, functions, events and access in SurrealQL.

The DEFINE statement can be used to specify instructions to the schema such as authentication access and behaviour, global parameters, table configurations, table events, analyzers, and indexes.

> [!NOTE]
> Before SurrealDB version 3.0.0, the `FULLTEXT ANALYZER` clause used the syntax `SEARCH ANALYZER`.

```syntax title="SurrealQL Syntax"
DEFINE [
	NAMESPACE [ OVERWRITE | IF NOT EXISTS ] @name
	| DATABASE [ OVERWRITE | IF NOT EXISTS ] @name
	| TYPE [ OVERWRITE | IF NOT EXISTS ] @name AS @type
		[ [ CONSTRAINT @name ] ASSERT @expression ... ]
		[ DEFAULT @expression ]
		[ SQL TYPE POSTGRESQL @string ]
		[ PERMISSIONS [ NONE | FULL | WHERE @condition ] ]
	| USER [ OVERWRITE | IF NOT EXISTS ] @name
		ON [ ROOT | NAMESPACE | DATABASE ]
		[ PASSWORD @pass | PASSHASH @hash ]
		ROLES @roles
	| TABLE [ OVERWRITE | IF NOT EXISTS ] @name
		[ DROP ]
		[ SCHEMAFULL | SCHEMALESS ]
		[ AS SELECT @projections
			FROM @tables
			[ WHERE @condition ]
			[ GROUP [ BY ] @groups ]
		]
		[ PERMISSIONS [ NONE | FULL
			| FOR select @expression
			| FOR create @expression
			| FOR update @expression
			| FOR delete @expression
		] ]
	| EVENT [ OVERWRITE | IF NOT EXISTS ] @name ON [ TABLE ] @table
		WHEN @expression
		THEN @expression
	| FIELD [ OVERWRITE | IF NOT EXISTS ] @name ON [ TABLE ] @table
		[ TYPE @type ]
		[ VALUE @expression ]
		[ ASSERT @expression ]
		[ PERMISSIONS [ NONE | FULL
			| FOR select @expression
			| FOR create @expression
			| FOR update @expression
			| FOR delete @expression
		] ]
	| PARAM [ OVERWRITE | IF NOT EXISTS ] $name VALUE @value
	| FUNCTION [ OVERWRITE | IF NOT EXISTS ] fn::@name
		( [ ( @argument:@type ... ) ] ) { [@query] [RETURNS @returned] }
	| ANALYZER [ OVERWRITE | IF NOT EXISTS ] @name
		[ TOKENIZERS @tokenizers ]
		[ FILTERS @filters ]
	| INDEX [ OVERWRITE | IF NOT EXISTS ] @name ON [ TABLE ] @table
		[ FIELDS | COLUMNS ] @fields
		[ UNIQUE | FULLTEXT ANALYZER @analyzer [ BM25 [(@k1, @b)] ] [ HIGHLIGHTS ] ]
	| SEQUENCE [ OVERWRITE | IF NOT EXISTS ] @name
		[ BATCH @batch ]
		[ START @start ]
	| ACCESS [ OVERWRITE | IF NOT EXISTS ] @name ON [ NAMESPACE | DATABASE ]
		TYPE [
			JWT [ ALGORITHM @algorithm KEY @key | URL @url ]
			| RECORD
				[ SIGNUP @expression ]
				[ SIGNIN @expression ]
				[ WITH JWT [ ALGORITHM @algorithm KEY @key | URL @url ]
					[ WITH ISSUER KEY @key ] ]
		]
		[ DURATION [ FOR TOKEN @duration ] [ FOR SESSION @duration ] ]
    [ COMMENT @string ]
]
```

The [INFO](/docs/reference/query-language/statements/info.md) statement can be used to see which definition statements currently exist in a database connection. All `DEFINE` statements can be followed up with a `COMMENT`.

## Comments on definitions

A `COMMENT` is stored with the definition and returned by [`INFO`](/docs/reference/query-language/statements/info.md) (and by schema tools such as MCP `info` / `list`). Short, concrete comments help people and agents alike: they explain what a table or field is for, how values should be compared, and which graph edges or record-ID conventions matter.

Useful comments tend to include:

- What the entity represents, and what it deliberately does not store
- How to read the record ID or field (for example `record::id(id)` when the ID is the canonical name)
- How to compare or sort unusual types (ISO date strings vs datetimes)
- Cardinality or invariants ("exactly one organiser per meeting")
- The main graph paths to related tables

```surql
DEFINE TABLE person TYPE NORMAL SCHEMAFULL
	COMMENT "A person, deduplicated across notes. Has no fields: the record id IS the canonical full name, e.g. person:`Alice Chen`. Read the name with record::id(id). Meetings: person->attended->meeting.";

DEFINE TABLE meeting TYPE NORMAL SCHEMAFULL
	COMMENT "A calendar meeting. Link attendees with RELATE person->attended->meeting.";

DEFINE TABLE attended TYPE RELATION IN person OUT meeting SCHEMAFULL
	COMMENT "Attendance edge. Exactly one attendee per meeting has is_organizer = true.";

DEFINE FIELD is_organizer ON attended TYPE bool
	COMMENT "True if this person ran the meeting, false if they only attended.";
```

An example of defining a field on a table, followed by an `INFO` command for the same table:

```surql
DEFINE FIELD name ON TABLE person TYPE string COMMENT "Todo: add assertion for maximum length";
INFO FOR TABLE person;
```

```surql output="Response"
{
	events: {},
	fields: {
		name: "DEFINE FIELD name ON person TYPE string COMMENT 'Todo: add assertion for maximum length' PERMISSIONS FULL"
	},
	indexes: {},
	lives: {},
	tables: {}
}
```

An example of defining a user and a table for a database, followed by an `INFO` command for the current database:

```surql
DEFINE USER db_user ON DATABASE PASSWORD "strongpassword" ROLES OWNER;
DEFINE TABLE person SCHEMAFULL;
INFO FOR DB;
```

```surql output="Response"
{
    "accesses": {},
    "analyzers": {},
    "functions": {},
    "models": {},
    "params": {},
    "tables": {
        "person": "DEFINE TABLE person TYPE ANY SCHEMAFULL
          PERMISSIONS NONE"
    },
    "users": {
        "db_user": "DEFINE USER db_user ON DATABASE PASSHASH '[REDACTED]' ROLES OWNER"
    }
}
```

## Names from parameters

_(since v3.0.0)_

The name in a `DEFINE` statement can be a parameter, as can the table that a field, an index or an event belongs to. A schema can therefore be created with names that are only known when the query runs, and an SDK can pass them with its usual parameter binding:

```surql
LET $table = "shop";
LET $field = "price";

DEFINE TABLE $table SCHEMAFULL;
DEFINE FIELD $field ON $table TYPE number;
DEFINE INDEX price_idx ON $table FIELDS $field;

INFO FOR TABLE shop;
```

```surql title="Output"
{
	events: {},
	fields: {
		price: 'DEFINE FIELD price ON shop TYPE number PERMISSIONS FULL'
	},
	indexes: {
		price_idx: 'DEFINE INDEX price_idx ON shop FIELDS price'
	},
	lives: {},
	migrations: {
		generation: 2,
		guaranteed: [],
		migrations: []
	},
	tables: {}
}
```

The same applies to `REMOVE` and `INFO`, such as `REMOVE TABLE $table`. Before 3.0.0, a name had to be written into the query text.

Because a function argument is a parameter too, a [defined function](/docs/reference/query-language/statements/define/function.md) can add the same definitions to any table it is given:

```surql
DEFINE FUNCTION fn::add_timestamps($table: string) {
	DEFINE FIELD OVERWRITE created_at ON $table TYPE datetime DEFAULT time::now();
	DEFINE FIELD OVERWRITE updated_at ON $table TYPE datetime VALUE time::now();
};

fn::add_timestamps("article");
fn::add_timestamps("comment");
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/param

# DEFINE PARAM

The DEFINE PARAM statement allows you to define global (database-wide) parameters that are available to every client.

The `DEFINE PARAM` statement allows you to define global (database-wide) parameters that are available to every client.

## Requirements

- You must be authenticated as a root owner or editor, namespace owner or editor, or database owner or editor before you can use the `DEFINE PARAM` statement.
- [You must select your namespace and database](/docs/reference/query-language/statements/use.md) before you can use the `DEFINE PARAM` statement.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
DEFINE PARAM [ OVERWRITE | IF NOT EXISTS ] $name 
    VALUE @value
    [ COMMENT @string ]
    [ PERMISSIONS [ NONE | FULL | WHERE @condition ] ]
```

## Example usage
Below shows how you can create a parameter using the `DEFINE PARAM` statement.

```surql
DEFINE PARAM $endpointBase VALUE "https://dummyjson.com";
```

Then, simply use the global parameter like you would with any variable.

```surql
http::get($endpointBase + "/products");
```

A parameter belongs to the database, and `DEFINE PARAM` has no clause that attaches it to a table. For a value that differs from table to table, define one parameter that holds an object with a field for each table:

```surql
DEFINE PARAM $page_size VALUE { book: 10, author: 25 };

$page_size.book;
//- 10

-- With the table name in a variable
LET $table = "author";
$page_size[$table];
//- 25
```

## Using `IF NOT EXISTS` clause

The `IF NOT EXISTS` clause can be used to define a param only if it does not already exist. You should use the `IF NOT EXISTS` clause when defining a param in SurrealDB if you want to ensure that the param is only created if it does not already exist. If the param already exists, the `DEFINE PARAM` statement will return an error.

It's particularly useful when you want to safely attempt to define a param without manually checking its existence first.

On the other hand, you should not use the `IF NOT EXISTS` clause when you want to ensure that the param definition is updated regardless of whether it already exists. In such cases, you might prefer using the `OVERWRITE` clause, which allows you to define a param and overwrite an existing one if it already exists, ensuring that the latest version of the param definition is always in use.

```surql
-- Create a PARAM if it does not already exist
DEFINE PARAM IF NOT EXISTS $example VALUE 123;
```

## Using `OVERWRITE` clause

The `OVERWRITE` clause can be used to define a param and overwrite an existing one if it already exists. You should use the `OVERWRITE` clause when you want to modify an existing param definition. If the param already exists, the `DEFINE PARAM` statement will overwrite the existing param definition with the new one.

```surql
-- Create an PARAM and overwrite if it already exists
DEFINE PARAM OVERWRITE $example VALUE 123;
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/sequence

# DEFINE SEQUENCE

A DEFINE SEQUENCE statement defines a distributed generator of monotonically increasing numeric sequences.

_(since v3.0.0)_

A sequence is used to generate reliable, monotonically increasing numeric sequences in both single-node and clustered SurrealDB deployments. It uses a batch-allocation strategy to minimise coordination while guaranteeing global uniqueness.

The key features of a sequence are as follows:

* Batch allocation: Nodes request ranges of sequence values at once, reducing network chatter and coordination overhead.
* Node ownership tagging: Every batch is tagged with the requesting node's UUID to prevent overlap between nodes.
* Durable Persistence: Sequence metadata is stored in the underlying key-value store to survive restarts and network partitions.
* Concurrent, thread-safe access: A DashMap caches active sequences, allowing lock-free reads on the hot path.
* Exponential back-off with full jitter: When a batch-allocation attempt fails, the node retries with an exponential delay that includes full jitter to avoid thundering-herd effects across the cluster.
* Automatic cleanup: Listens for namespace and database-removal events and purges the corresponding sequence state.

The sequence implementation avoids contention by having each node reserve a range of sequence values, allowing it to serve multiple requests locally without requiring distributed coordination for every request. When a node exhausts its allocated range, it acquires a new batch from the distributed store.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
DEFINE SEQUENCE [ OVERWRITE | IF NOT EXISTS ] @name
	[ BATCH @batch ]
	[ START @start ]
	[ TIMEOUT @duration ]
```

## Examples

A sequence can be created with nothing more than a name.

```surql
DEFINE SEQUENCE mySeq;
```

The `BATCH`, `START`, and `TIMEOUT` clauses can be included to configure the sequence.

```surql
DEFINE SEQUENCE mySeq2 BATCH 1000 START 100 TIMEOUT 5s;
sequence::nextval('mySeq2');
//- 100

DEFINE SEQUENCE mySeq3 BATCH 1000 START 100 TIMEOUT 0ns;
-- Possible output, since the timeout may or may not be exceeded
sequence::nextval('mySeq3');
//- 'The query was not executed because it exceeded the timeout: 0ns'
```

Sequences are never rolled back, even in a failed transaction. This differs from an approach like a single record with a manually incrementing value.

```surql
DEFINE SEQUENCE seq;
CREATE my:counter SET val = 0;
sequence::nextval("seq");        -- 0
my:counter.val;                  -- 0

BEGIN TRANSACTION;
sequence::nextval("seq");        -- 1
UPDATE my:counter SET val += 1;  -- my:counter.val = 1
CANCEL TRANSACTION;
-- my:counter.val now rolled back to 0

sequence::nextval("seq");        -- 2
UPDATE my:counter SET val += 1;  -- 1
```

The largest value that a sequence issues is `9223372036854775806`, one below the largest `int`. After it, `sequence::nextval()` fails with an error instead of overflowing, so a sequence defined with `START 9223372036854775807` cannot issue any value.

```surql
DEFINE SEQUENCE big START 9223372036854775805;
sequence::nextval('big');
//- 9223372036854775805
sequence::nextval('big');
//- 9223372036854775806
sequence::nextval('big');
//- 'The sequence has no values left to issue: its values cannot exceed 9223372036854775806'
```

Every later call fails in the same way. Defining the sequence again with `OVERWRITE` and a lower `START` lets it issue values again, from the new `START`.

## Sequence position and exports

_(since v3.2.5)_

For each sequence, `INFO FOR DB STRUCTURE` shows a `start` and a `resume` value. `start` is the value that the definition declares. `resume` is the lowest value that no node has reserved yet. A node reserves values in batches of the sequence's `BATCH` size, so `resume` moves past a whole batch when a node reserves it.

```surql
DEFINE SEQUENCE seq BATCH 1 START 10;
sequence::nextval('seq');
sequence::nextval('seq');
sequence::nextval('seq');

LET $info = INFO FOR DB STRUCTURE;
RETURN $info.sequences;
```

```surql title="Output"
[
	{
		batch: '1',
		name: 'seq',
		resume: '13',
		start: '10',
		timeout: NONE
	}
]
```

An export writes each sequence with its `resume` value as `START`. After an import, the sequence continues from where it was and does not issue a value that the imported records already hold. Before 3.2.5 and 3.3.0, an export wrote the declared `START`, so the first `sequence::nextval()` after an import could repeat a value.

`resume` is not always the next value that `sequence::nextval()` returns. A node that still holds a batch it reserved earlier issues values from that batch, and those values are lower than `resume`. `resume` is the value that a sequence can safely restart from.

## See also

* [Sequence functions](/docs/reference/query-language/functions/database-functions/sequence.md)

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/table

# DEFINE TABLE

Declare a table, its type, schema mode and permissions.

The `DEFINE TABLE` statement allows you to declare your table by name, enabling you to apply strict controls to a table's schema by making it `SCHEMAFULL`, create a foreign table view, and set permissions specifying what operations can be performed on the table.

> [!NOTE]
> The fields of a table are not defined using `DEFINE TABLE`, but via individual [`DEFINE FIELD`](/docs/reference/query-language/statements/define/field.md) statements.

## Requirements

- You must be authenticated as a root owner or editor, namespace owner or editor, or database owner or editor before you can use the `DEFINE TABLE` statement.
- [You must select your namespace and database](/docs/reference/query-language/statements/use.md) before you can use the `DEFINE TABLE` statement.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
DEFINE TABLE [ OVERWRITE | IF NOT EXISTS ] @name
	[ DROP ]
	[ SCHEMAFULL | SCHEMALESS ]
	[ TYPE [ ANY | NORMAL | RELATION
		[ [ IN | FROM ] @table ] [ [ OUT | TO ] @table ]
		[ ENFORCED ] [ LIGHTWEIGHT ]]]
	[ AS SELECT @projections
		FROM @tables
		[ WHERE @condition ]
		[ GROUP [ BY @groups | ALL ] ]
	]
	[ CHANGEFEED @duration [ INCLUDE ORIGINAL ] ]
	[ INLINE EDGES @number ]
	[ INLINE REFERENCES @number ]
	[ PERMISSIONS [ NONE | FULL
		| FOR select @expression
		| FOR create @expression
		| FOR update @expression
		| FOR delete @expression
	] ]
    [ COMMENT @string ]
	[ GRAPHQL_ALIAS @string ]
	[ GRAPHQL_DEPRECATED @string ]
```

Each clause can be given once. From SurrealDB 4.0, a statement that repeats a clause, such as two `PERMISSIONS` clauses, or both `SCHEMAFULL` and `SCHEMALESS`, is a parse error that names both clauses: `Conflicting clause on this table definition`. Earlier versions kept the last of the repeated clauses.

## Example usage

Below shows how you can create a table using the `DEFINE TABLE` statement.

```surql
-- Declare the name of a table.
DEFINE TABLE reading;
```

### Comments

Add a `COMMENT` when the table's role is not obvious from the name alone. The text is returned by [`INFO`](/docs/reference/query-language/statements/info.md) and by agent-facing schema tools, so prefer operational detail (record-ID conventions, graph paths, invariants) over a one-line restatement of the table name. See [Comments on definitions](/docs/reference/query-language/statements/define/overview.md#comments-on-definitions) for a fuller pattern.

```surql
DEFINE TABLE person TYPE NORMAL SCHEMAFULL
	COMMENT "Deduplicated person. The record id is the canonical full name (person:`Alice Chen`); use record::id(id) to read it. Edges: person->attended->meeting.";
```

The following example uses the `DROP` portion of the `DEFINE TABLE` statement. Marking a table as `DROP` disallows creating or updating records.

`DROP` tables are useful in combination with events or foreign (view) tables, as you can compute a record and essentially drop the input.

```surql
-- By marking a table as DROP, you disallow any records to be created or updated.
-- Records that currently exist in the table will not automatically be deleted, you can still remove them manually.
DEFINE TABLE reading DROP;
```

The following expression shows how you can define a `CHANGEFEED` for a table. After creating, updating, and deleting records in the table as usual, using `SHOW CHANGES FOR` will show the changes that have taken place during this time.

If an entry holds a change to an existing record, the diff will show the operation needed to modify the record to the state immediately preceding its current state. In other words, the diff included is a reverse diff.

```surql
-- Define the changefeed and its duration
-- Optionally, append INCLUDE ORIGINAL to include info
-- on the current record before a change took place
DEFINE TABLE reading CHANGEFEED 3d;

-- Create some records in the reading table
CREATE reading SET story = "Once upon a time";
CREATE reading SET story = "there was a database";
UPDATE reading SET is_interesting = true;

-- Replay changes to the reading table since a certain date
-- Must be after the timestamp at which the changefeed began
SHOW CHANGES FOR TABLE reading SINCE d"2025-09-07T01:23:52Z" LIMIT 10;

-- Alternatively, show the changes for the table since a version number
SHOW CHANGES FOR TABLE reading SINCE 0 LIMIT 10;
```

```surql title="Output without INCLUDE ORIGINAL"
[
	{
		changes: [
			{
				define_table: {
					changefeed: {
						expiry: 3d,
						original: false
					},
					drop: false,
					id: 0,
					kind: {
						kind: 'ANY'
					},
					name: 'reading',
					permissions: {
						create: false,
						delete: false,
						select: false,
						update: false
					},
					schemafull: false
				}
			}
		],
		versionstamp: 116395447100768256
	},
	{
		changes: [
			{
				update: {
					id: reading:bqlejs8fx4phgbo6g5ve,
					story: 'Once upon a time'
				}
			}
		],
		versionstamp: 116395447100833792
	},
	{
		changes: [
			{
				update: {
					id: reading:fa8o65ccxykfxqqz91yo,
					story: 'there was a database'
				}
			}
		],
		versionstamp: 116395447100833793
	},
	{
		changes: [
			{
				update: {
					id: reading:bqlejs8fx4phgbo6g5ve,
					is_interesting: true,
					story: 'Once upon a time'
				}
			},
			{
				update: {
					id: reading:fa8o65ccxykfxqqz91yo,
					is_interesting: true,
					story: 'there was a database'
				}
			}
		],
		versionstamp: 116395447100833794
	}
]
```

```surql title="Output with INCLUDE ORIGINAL"
[
	{
		changes: [
			{
				define_table: {
					changefeed: {
						expiry: 3d,
						original: true
					},
					drop: false,
					id: 0,
					kind: {
						kind: 'ANY'
					},
					name: 'reading',
					permissions: {
						create: false,
						delete: false,
						select: false,
						update: false
					},
					schemafull: false
				}
			}
		],
		versionstamp: 116395448975818752
	},
	{
		changes: [
			{
				update: {
					id: reading:kypj876yubk4fnnja93b,
					story: 'Once upon a time'
				}
			}
		],
		versionstamp: 116395448975818753
	},
	{
		changes: [
			{
				update: {
					id: reading:0i2qwoi053nmrl4k2wm2,
					story: 'there was a database'
				}
			}
		],
		versionstamp: 116395448975818754
	},
	{
		changes: [
			{
				current: {
					id: reading:0i2qwoi053nmrl4k2wm2,
					is_interesting: true,
					story: 'there was a database'
				},
				update: [
					{
						op: 'remove',
						path: '/is_interesting'
					}
				]
			},
			{
				current: {
					id: reading:kypj876yubk4fnnja93b,
					is_interesting: true,
					story: 'Once upon a time'
				},
				update: [
					{
						op: 'remove',
						path: '/is_interesting'
					}
				]
			}
		],
		versionstamp: 116395448975818755
	}
]
```

## Schemafull tables

The following example demonstrates the `SCHEMAFULL` portion of the `DEFINE TABLE` statement. When a table is defined as schemafull, the database strictly enforces any schema definitions that are specified using the `DEFINE TABLE` statement. New fields can not be added to a `SCHEMAFULL` table unless they are defined via the [`DEFINE FIELD`](/docs/reference/query-language/statements/define/field.md) statement.

> [!NOTE]
> Schemafull tables are implicitly type [`NORMAL`](#table-with-specialized-type-clause) tables by default.

```surql
-- Create schemafull user table.
DEFINE TABLE user SCHEMAFULL;

-- Define some fields.
DEFINE FIELD firstName ON TABLE user TYPE string;
DEFINE FIELD lastName ON TABLE user TYPE string;
DEFINE FIELD email ON TABLE user TYPE string
  ASSERT string::is_email($value);
DEFINE INDEX userEmailIndex ON TABLE user FIELDS email UNIQUE;

-- SEE IT IN ACTION
-- 1: Try to add a user with an undefined field, 'photoURI'.
CREATE user CONTENT {
    firstName: 'Tobie',
    lastName: 'Hitchcock',
    email: 'Tobie.Hitchcock@surrealdb.com',
    photoURI: 'photo/yxCFi22Jw2.webp'
};
-- 2: The statement fails: a schemafull table rejects any field that has
--    not been defined. (Before version 3.0, the undefined field was
--    silently dropped instead.)

-- 3: Create the user with defined fields only.
CREATE user CONTENT {
    firstName: 'Tobie',
    lastName: 'Hitchcock',
    email: 'Tobie.Hitchcock@surrealdb.com'
};

-- 4: Query the data
SELECT * FROM user;
```

## Schemaless tables

The following example demonstrates the `SCHEMALESS` portion of the `DEFINE TABLE` statement. This allows you to explicitly state that the specified table has no schema.

```surql
-- Create schemaless user table.
DEFINE TABLE user SCHEMALESS;

-- Define some fields.
DEFINE FIELD firstName ON TABLE user TYPE string;
DEFINE FIELD lastName ON TABLE user TYPE string;
DEFINE FIELD email ON TABLE user TYPE string
  ASSERT string::is_email($value);
DEFINE INDEX userEmailIndex ON TABLE user FIELDS email UNIQUE;

-- SEE IT IN ACTION - Example 1
-- 1: Add a user with all required fields and an undefined one.
CREATE user:tobie SET firstName = 'Tobie', lastName = 'Hitchcock',
  email = 'Tobie.Hitchcock@surrealdb.com',
  photoURI = 'photo/yxCFi22Jw2.webp';
-- 2: Statement will succeed because user is a SCHEMALESS table.

-- SEE IT IN ACTION - Example 2
-- 1: Add a user with an invalid email address and include a new field that was never defined.
CREATE user:jaime SET firstName = 'Jamie', lastName = 'Hitchcock',
  email = 'Jamie.Hitchcock',
  photoURI = 'photo/yxCFi22Jw2.webp';
-- 2: Statement will fail because the value for email was not valid.
```

## Interaction between fields

While a `DEFINE TABLE` statement represents a template for any subsequent records to be created, a `DEFINE FIELD` statement pertains to concrete field data of a record. As such, a `DEFINE FIELD` statement gives access to the record's other fields through their names, as well as the current field through the [`$value`](/docs/reference/query-language/language-primitives/parameters.md#value) parameter.

```surql
DEFINE TABLE person SCHEMAFULL;

DEFINE FIELD first_name
  ON TABLE person TYPE string ASSERT string::len($value) < 20;
DEFINE FIELD last_name 
  ON TABLE person TYPE string ASSERT string::len($value) < 20;
DEFINE FIELD name      
  ON TABLE person             VALUE first_name + ' ' + last_name;

-- Creates a `person` with the name "Bob Bobson"
CREATE person SET first_name = "Bob", last_name = "Bobson";
```

## Pre-computed table views

In SurrealDB, like in other databases, you can create views. The way you create views is using the `DEFINE TABLE` statement like you would for any other table, then adding the `AS` clause at the end with your `SELECT` query.

```surql
DEFINE TABLE review DROP;
-- Define a table as a view which aggregates data from the review table
DEFINE TABLE avg_product_review TYPE NORMAL AS
SELECT
	count() AS number_of_reviews,
	math::mean(<float> rating) AS avg_review,
	->product.id AS product_id,
	->product.name AS product_name
FROM review
GROUP BY product_id, product_name;

-- Query the projection
SELECT * FROM avg_product_review;
```

Pre-computed table views differ from a typical relational database view in a few important ways, and have a few limitations to keep in mind.

Pre-computed table views are most similar to event-based, incrementally updating, materialised views:

- Event-based, meaning that when you add or remove data from the underlying table (in our example, the `review` table), it triggers a matching event on the `avg_product_review` table view.
- Materialised view, meaning that the first time we run the table view query, it will run the query like a normal `SELECT` statement, but then materialise the result. Normal views, by contrast, behave like bookmarked `SELECT` queries that only look like tables to the user.
- Incrementally updating, meaning that for any subsequent run, it will listen for the event trigger and perform the most efficient operation possible to always keep the result up to date, instead of just running the `SELECT` statement again.

While this functionality can be replicated in many other databases, it is usually only done by expert users as it can be very complicated to set up and maintain. Pre-computed table views make this functionality available through a single `DEFINE TABLE` statement.

As mentioned though, there are a few limitations to keep in mind.

- First, while subsequent runs are very efficient, the initial run of large analytical queries can be slow and use a lot of resources, because it is a normal `SELECT` statement. Therefore indexing and query optimisation are still very important.
- Second, while both graph relations and record links are supported, the table view update event is only triggered by the table in the `FROM` clause. In our case, that is the `review` table, not the `product` table that the query also uses. This means that if you delete a `review` the `avg_product_review`  will reflect that in near real-time. However if you delete a `product`, it will still show up in `avg_product_review`.
- Third, view tables are **read-only**. Since 3.2.0, `CREATE`, `INSERT`, `UPSERT`, `UPDATE`, `DELETE`, and `RELATE` against a view table are rejected - records are computed from the source query only. The one exception is import: records emitted for a view during export can be re-applied under `OPTION IMPORT`, to allow export → import round-trips to keep working.

<img src="~/assets/img/diagrams/light/table-view-updates-light.webp" darkSrc="~/assets/img/diagrams/table-view-updates.webp" alt="What updates the avg_product_review view. DEFINE TABLE AS SELECT runs the full query once to fill it. A write to review, the FROM table, updates the matching record. A write to product, which the query reads but which is not its FROM table, does not update the view, and neither does a write under OPTION IMPORT, after which DEFINE TABLE OVERWRITE refills the view." />

### Filling a view from existing records

Defining a view runs its query over the records already in the source table, so the view starts with their results rather than empty. After that, only writes to the source table update it.

A view defined with `GROUP ALL` has its one record from the moment it is defined, also when the source table is empty, with the aggregates of no records: `count()` is `0`. Deleting the last source record resets that record to the same values instead of deleting it. An event defined on such a view therefore receives `UPDATE` in `$event` for every change, and never `CREATE` or `DELETE`.

```surql
DEFINE TABLE sale;
DEFINE TABLE sales_total AS
	SELECT count() AS sales, math::sum(amount) AS total
	FROM sale GROUP ALL;
SELECT * FROM sales_total;
```

```surql title="Output"
[
	{
		id: sales_total:[],
		sales: 0,
		total: 0
	}
]
```

Writes made under `OPTION IMPORT`, which is how [`surreal db import`](/docs/reference/cli/db/commands/import.md) loads data, do not trigger the view. To bring a view up to date after an import, define it again with `OVERWRITE`, which runs the query over every record in the source table:

```surql
CREATE news:1 SET tags = ["fr"];
DEFINE TABLE fr_feed AS SELECT * FROM news WHERE "fr" IN tags;

-- An import skips the view, so news:2 does not appear in fr_feed
OPTION IMPORT;
CREATE news:2 SET tags = ["fr"];
```

```surql
-- Setup from the example above
CREATE news:1 SET tags = ["fr"];
DEFINE TABLE fr_feed AS SELECT * FROM news WHERE "fr" IN tags;
-- An import skips the view, so news:2 does not appear in fr_feed
OPTION IMPORT;
CREATE news:2 SET tags = ["fr"];

-- In a later query, rebuild the view from all of the news records
DEFINE TABLE OVERWRITE fr_feed AS SELECT * FROM news WHERE "fr" IN tags;
SELECT VALUE id FROM fr_feed;
```

```surql title="Output"
[fr_feed:1, fr_feed:2]
```

### Choosing the `id` of a view row

Each row of a view is keyed by the record it came from, or for a grouped view, by its group. A projection that sets `id` keys the rows by that value instead, which lets several source records feed one row, or gives a row a key that is meaningful on its own:

```surql
CREATE purchase:1 SET customer = 'ana', total = 10;
DEFINE TABLE spend AS SELECT customer AS id, total FROM purchase;

CREATE purchase:2 SET customer = 'ben', total = 25;
UPDATE purchase:1 SET total = 15;

SELECT * FROM spend;
```

```surql title="Output"
[
	{ id: spend:ana, total: 15 },
	{ id: spend:ben, total: 25 }
]
```

The value becomes the key of the view row, so it can be a string, number, array, object or UUID. A write whose projected `id` changes moves the row to the new key, and a projected `id` of `NONE` fails the write.

Before SurrealDB 4.0, only the initial fill used the projected `id`. Later writes keyed the row by the source record, so the same query left `spend:ana` at `10` beside rows keyed `spend:1` and `spend:2`, and an `id` that was not a record id failed the definition.

## Defining permissions

Table `PERMISSIONS` control what [record users](/docs/learn/security/authentication/users.md#record-users) (and [guests](/docs/learn/security/authorization/capabilities.md#guest-access), when guest access is enabled) may do with records in that table. They do not restrict [system users](/docs/learn/security/authentication/users.md#system-users) at the root, namespace, or database level, as those users are governed by roles instead.

If you omit the clause, SurrealDB stores `PERMISSIONS NONE`. That denies `SELECT`, `CREATE`, `UPDATE`, and `DELETE` for record users until you grant access explicitly. The opposite shorthand is `PERMISSIONS FULL`, which allows all four operations.

```surql
CREATE some_table;
DEFINE TABLE some_other_table;

INFO FOR DB;
```

```surql title="Output"
{
	accesses: {},
	analyzers: {},
	apis: {},
	buckets: {},
	compatibility: 4,
	configs: {},
	extensions: {},
	functions: {},
	models: {},
	params: {},
	sequences: {},
	tables: {
		some_other_table: 'DEFINE TABLE some_other_table TYPE ANY SCHEMALESS PERMISSIONS NONE',
		some_table: 'DEFINE TABLE some_table TYPE ANY SCHEMALESS PERMISSIONS NONE'
	},
	types: {},
	users: {}
}
```

You can also set independent rules for selecting, creating, updating, and deleting data. Each `FOR` clause is a SurrealQL expression, usually one that compares the record with [`$auth`](/docs/reference/query-language/language-primitives/parameters.md#auth).

```surql
-- Specify access permissions for the 'post' table
DEFINE TABLE post SCHEMALESS
	PERMISSIONS
		FOR select
			-- Published posts can be selected
			WHERE published = true
			-- A user can select all their own posts
			OR user = $auth.id
		FOR create, update
			-- A user can create or update their own posts
			WHERE user = $auth.id
		FOR delete
			-- A user can delete their own posts
			WHERE user = $auth.id
			-- Or an admin can delete any posts
			OR $auth.admin = true
;
```

A table or field `PERMISSIONS` clause reads data with the authority of the schema that defines it, not with the caller's permissions. `$auth` and the record being checked are the caller's, but any other record the clause reads is read without checking the caller's permissions. This applies to following a record id such as `$auth.admin`, a subquery, `record::exists()` or `.exists()`, a graph traversal, and a function that the clause calls. So a clause can test fields of the user's own record even when the user may not select it. A field's `VALUE`, `DEFAULT`, `ASSERT` and `COMPUTED` clauses, and a function called from a query, run with the caller's permissions instead.

In SurrealDB 3.3, `record::exists()` and `.exists()` inside a `FOR select` clause were checked against the caller's permissions, so they returned `false` for a record the caller could not select, and the clause denied access. From SurrealDB 4.0 they read the record in the same way as the other forms.

Each write is checked only against its own clause: `FOR create`, `FOR update` or `FOR delete`. If that clause allows it, the record is written. The statement's result is then filtered by `FOR select`, so a record user who may create records in a table but not select them receives `[]`, although the record was written. In the same way, `UPDATE` and `DELETE` with a `WHERE` clause can match records that the caller cannot select. To return a user's own writes to them, add a narrow select rule such as `FOR select WHERE owner = $auth`.

```surql
-- Defined by a system user: record users may create notes, but not select them
DEFINE TABLE note PERMISSIONS FOR create WHERE owner = $auth;

-- Run as a record user: the first note is written, the second is refused
CREATE note SET owner = $auth, text = 'Draft';
//- []

CREATE note SET owner = person:someone_else, text = 'Draft';
//- []
```

> [!WARNING]
> A write that its permission clause refuses does not raise an error. The statement returns `[]` with status `OK` (`CREATE ONLY` returns `NONE`), and the other statements in the transaction still commit. This result is the same as for a write that succeeded but that `FOR select` hides, and `RETURN NONE` gives the same result for both.

Field permissions work the same way but default to `PERMISSIONS FULL` instead of `NONE`. This is because the table is the main access gate, while field permissions only narrow further when you need to (for example hiding a password). With `FULL`, a field follows the table's rules without adding its own. See [`DEFINE FIELD`](/docs/reference/query-language/statements/define/field.md#setting-permissions-on-fields) and [Permissions & row-level security](/docs/learn/security/authorization/permissions-and-row-level-security.md).

### Writes inside a permission clause

A permission clause decides whether an operation is allowed, and must not write data itself, whether directly or through a custom function. This applies to every clause, `FOR create`, `FOR update` and `FOR delete` included. The definition is refused:

```surql
DEFINE FUNCTION fn::audit($id: record) -> bool { CREATE audit SET record = $id, at = time::now(); RETURN true; };

DEFINE TABLE post PERMISSIONS
	FOR create, update WHERE fn::audit($value.id) AND user = $auth.id;
```

```surql title="Error output"
'The PERMISSIONS clause must not have effects: it calls `fn::audit`, in whose body `CREATE` writes data'
```

Use [`DEFINE EVENT`](/docs/reference/query-language/statements/define/event.md) for a write that should follow a change, such as an audit log. An event runs [without permission checks](/docs/reference/query-language/statements/define/event.md#events-and-permissions), so it can write to a table such as `audit` that the caller cannot access. It also states the side effect where a reader expects to find it, and does not run on every access check:

```surql
DEFINE TABLE post PERMISSIONS FOR create, update WHERE user = $auth.id;

DEFINE EVENT audit ON post WHEN $event IN ['CREATE', 'UPDATE'] THEN {
	CREATE audit SET record = $after.id, at = time::now();
};
```

The full list of what a clause may not do is in [Clauses that must not have effects](/docs/reference/query-language/statements/define/field.md#clauses-that-must-not-have-effects).

> [!NOTE]
> This behaviour changed in 4.0. In 3.3, a `FOR create`, `FOR update` or `FOR delete` clause could write, and a `FOR select` clause that wrote was stored and failed the first time a read reached the write. A permission clause stored by 3.3 that writes now fails with the error above each time it is evaluated, and writes nothing.

## Using `IF NOT EXISTS` clause

The `IF NOT EXISTS` clause can be used to define a table only if it does not already exist. You should use the `IF NOT EXISTS` clause when defining a table in SurrealDB if you want to ensure that the table is only created if it does not already exist. If the table already exists, the `DEFINE TABLE` statement will return an error.

It's particularly useful when you want to safely attempt to define a table without manually checking its existence first.

On the other hand, you should not use the `IF NOT EXISTS` clause when you want to ensure that the table definition is updated regardless of whether it already exists. In such cases, you might prefer using the `OVERWRITE` clause, which allows you to define a table and overwrite an existing one if it already exists, ensuring that the latest version of the table definition is always in use.

```surql
-- Create a TABLE if it does not already exist
DEFINE TABLE IF NOT EXISTS reading;
```

## Using `OVERWRITE` clause

The `OVERWRITE` clause can be used to define a table and overwrite an existing one if it already exists. You should use the `OVERWRITE` clause when you want to modify an existing table definition. If the table already exists, the `DEFINE TABLE` statement will overwrite the existing table definition with the new one.

```surql
-- Create an TABLE and overwrite if it already exists
DEFINE TABLE OVERWRITE example;
```

## Table with specialized `TYPE` clause

When defining a table in SurrealDB, you can specify the type of data that can be stored in the table. This can be done using the `TYPE` clause, followed by either `ANY`, `NORMAL`, or `RELATION`.

With `TYPE ANY`, you can specify a table to store any type of data, whether it's a normal record or a relational record.

With `TYPE NORMAL`, you can specify a table to only store "normal" records, and not relations. When a table is defined as `TYPE NORMAL`, it will not be able to store relations. This can be useful when you want to restrict the type of data that can be stored in a table in schemafull mode.

Finally, with `TYPE RELATION`, you can specify a table to only store relational type content. This can be useful when you want to restrict the type of data that can be stored in a table.

```surql
-- TYPE ANY is the default, so these two tables have the same type
DEFINE TABLE person TYPE ANY;
DEFINE TABLE animal;
```

With `TYPE NORMAL`, you can specify a table to only store "normal" records, and not relations.

```surql
-- Since it's default, we can also omit the TYPE clause
DEFINE TABLE person TYPE NORMAL;
```

With `TYPE RELATION`, you can specify a table to only store relational type content, and restrict what kind of relations can be stored.

```surql
-- Just a RELATION table, no constraints on the type of table
DEFINE TABLE likes TYPE RELATION;

-- Define a relation table, and constrain the type of relation which can be stored
DEFINE TABLE wrote TYPE RELATION FROM user TO post;
-- OR use IN and OUT alternatively to FROM and TO
DEFINE TABLE edited TYPE RELATION IN user OUT post;
-- To allow a link to one of a possible set of record types, use the | operator
DEFINE TABLE shared TYPE RELATION FROM user TO post|video;
DEFINE TABLE viewed TYPE RELATION IN user OUT post|video;
```

```surql
-- Define a relation table, and constrain the type of relation which can be stored
DEFINE TABLE assigned_to SCHEMAFULL TYPE RELATION IN tag OUT sticky
    PERMISSIONS
        FOR create, select, update, delete
            WHERE in.owner == $auth.id AND out.author == $auth.id;
```

## Using ENFORCED to ensure that related records exist

As relations are represented by standalone tables, they can be constructed before any linked records exist.

```surql
RELATE city:one->road_to->city:two SET
    distance = 12.4,
    slope = 5.4;
```

```surql title="Output"
[
	{
		distance: 12.4f,
		id: road_to:pacwucj25a056hhs2s5h,
		in: city:one,
		out: city:two,
		slope: 5.4f
	}
]
```

As such, a query on the relation will return nothing until the records it has been defined upon are created.

```surql
-- Setup from the example above, and an empty city table
DEFINE TABLE city;
RELATE city:one->road_to->city:two SET
    distance = 12.4,
    slope = 5.4;

SELECT ->road_to->city FROM city;

CREATE city:one, city:two;
SELECT ->road_to->city FROM city;
```

```surql title="Output"
-------- Query --------

[]

-------- Query --------

[
	{
		"->road_to": {
			"->city": [
				city:two
			]
		}
	},
	{
		"->road_to": {
			"->city": []
		}
	}
]
```

If this behaviour is not desirable, the `ENFORCED` clause can be used on a table of `TYPE RELATION` to disallow a `RELATE` statement from working unless it points to existing data.

```surql
DEFINE TABLE road_to TYPE RELATION IN city OUT city ENFORCED;

RELATE city:one->road_to->city:three SET
    distance = 5.5,
    slope = 30.0;
```

```surql title="Error output"
"The record 'city:one' does not exist"
```

The endpoint check is an admission gate on the write path, so it is deferred during an [import](/docs/reference/cli/db/commands/import.md), alongside the field, event, view and changefeed checks that already defer there. An export writes tables in name order, which can place an enforced relation table before the tables it points at, and the check would otherwise reject every edge as its endpoints did not yet exist.

> [!WARNING]
> Before SurrealDB 3.3.0, restoring an export of a database containing an `ENFORCED` relation table silently dropped its edges whenever the relation table sorted before its endpoint tables - `knows` before `person`, for example. The vertices and their counts restored correctly, so the loss only showed up on a traversal. If you restored such an export on an earlier version, check the edge counts before relying on the result.

## Using LIGHTWEIGHT for relations without properties

_(since v3.3.0)_

A relation can be specified as `LIGHTWEIGHT`, in which it becomes an edge that stores nothing but the connection between its two endpoints. There is no edge record, so the edge cannot carry properties, and the table cannot take a `DEFINE FIELD`, a `DEFINE INDEX` or a `DEFINE EVENT`.

```surql
DEFINE TABLE follows TYPE RELATION IN person OUT person LIGHTWEIGHT;
```

The saving in storage is the reward for opting into these constraints. The reason is that **the edge's id becomes the pair of endpoints**, written `follows:[in, out]`, so identity and connection are the same value. That makes `RELATE` idempotent:

```surql
CREATE person:one, person:two RETURN NONE;
RELATE person:one->follows->person:two;
```

```surql title="Output"
[{ id: follows:[person:one, person:two], in: person:one, out: person:two }]
```

Running that `RELATE` again returns the same record, because the id it would write is the one already there. On a classic relation the same two statements produce two separate edges with two generated ids. Supplying your own non-canonical id on a lightweight table is rejected, so the guarantee holds however the edge is written.

This is the behaviour that the [unique-key pattern](/docs/reference/query-language/statements/relate.md#handling-duplicate-edge-record-ids) builds by hand on a classic relation, using a composite id or a field plus a unique index. `LIGHTWEIGHT` makes it a property of the table, with no index to define and keep in step.

`LIGHTWEIGHT` implies [`ENFORCED`](#using-enforced-to-ensure-that-related-records-exist), because a vertex deletion is the only cleanup a record-less edge has. `IN` and `OUT` are therefore required, and can be widened but not narrowed while the table holds edges. The pair renders canonically as `ENFORCED LIGHTWEIGHT` and parses in either order.

### What a lightweight relation rejects

The clause is a promise that the edge will never need a record, and everything that assumes one raises an error rather than failing quietly:

| Rejected | Why |
| --- | --- |
| A data clause on `RELATE`, and `CREATE` / `INSERT RELATION` / `UPDATE` / `UPSERT` | There is no record to write fields to |
| `DEFINE FIELD`, `DEFINE INDEX`, `DEFINE EVENT` on the table | Same, and an index has no record to point at |
| `SCHEMAFULL`, `CHANGEFEED`, `DROP`, and `AS` clauses | Each presumes stored records |
| A `LIVE SELECT` subscription on the table | Not supported on a record-less relation |
| Clearing the flag on a table that holds edges | The edges have no records to fall back to |
| Setting it on a table that already holds edges | The existing edges have non-canonical ids |
| Narrowing `IN` or `OUT` while edges exist | The endpoint tables are what make a full scan possible |
| `REMOVE TABLE` while edges exist | The edges live under the endpoint tables' keys, which a table wipe cannot reach |
| Using a lightweight edge as the endpoint of another relation | An edge on an edge would break the record-less scan |

Reads are unaffected, because the engine synthesizes the record a query expects. A point read by canonical id returns the endpoints as well as the id:

```surql
-- Setup from the examples above
DEFINE TABLE follows TYPE RELATION IN person OUT person LIGHTWEIGHT;
CREATE person:one, person:two RETURN NONE;
RELATE person:one->follows->person:two;

SELECT * FROM ONLY follows:[person:one, person:two];
```

```surql title="Output"
{ id: follows:[person:one, person:two], in: person:one, out: person:two }
```

Idiom access resolves against that same synthesized record, so `follows:[person:one, person:two].out.id` returns `person:two`, and `record::exists` answers as it would for a stored edge. Counts, [record ranges](/docs/reference/query-language/language-primitives/data-types/record-ids.md#record-ranges) and ordering all work, reading the relation from its endpoint tables, and table-level `PERMISSIONS` are enforced as they are on a classic relation.

`DELETE` works in every form: by id, by traversal, by whole table, and through a vertex cascade. Only writes are not permitted:

```surql
UPDATE follows:[person:one, person:two] SET weight = 1;
```

```surql title="Error output"
"a LIGHTWEIGHT relation's edges cannot be updated: they carry no data beyond `id`, `in` and `out`"
```

## Using INLINE EDGES and INLINE REFERENCES to cache adjacency

_(since v3.3.0)_

A graph traversal normally reads the edges of each record it starts from by scanning a range of keys, one scan per record. `INLINE EDGES @number` keeps a cache for every record of the table: one value that holds all of the record's edges in one direction, for records with at most that number of edges in that direction. A traversal that starts from many records then reads all of their caches in one batched lookup. `INLINE REFERENCES @number` does the same for the incoming [record references](/docs/reference/query-language/language-primitives/record-references.md) that a `<~` lookup reads.

The clauses go on the table of the records that the edges or references connect, not on the relation table:

```surql
DEFINE TABLE person INLINE EDGES 64 INLINE REFERENCES 32;
DEFINE TABLE likes TYPE RELATION IN person OUT post;
```

Here each `person` record caches up to 64 edges in each direction, such as the `likes` edges that a `person->likes->post` traversal reads, and up to 32 records that reference it. Queries return the same results with or without a cache, because every write that adds or removes an edge or a reference updates the cache in the same transaction.

A few details:

- A record's cache is built the first time one of its edges or references is written after the clause is set. Until then, the traversal scans the keys as it would without the clause.
- A record with more entries than the cap stops using its cache and goes back to the scan. It keeps using the scan even if entries are removed later, until the cap is changed.
- The cap can be from 0 to 256, and `0` turns the cache off in the same way as leaving the clause out. Each edge or reference written rewrites the record's whole cache value, so a larger cap costs more to maintain. A cap above 256 fails with `an INLINE cache cap cannot exceed 256`.
- Changing or removing a cap, with `DEFINE TABLE OVERWRITE` or [`ALTER TABLE`](/docs/reference/query-language/statements/alter/table.md#inline-edges-and-inline-references), discards the table's existing caches of that kind, which are then rebuilt as edges or references are written.
- A traversal over a range of edge record IDs (`->likes:a..b`), a `VERSION` query, and a filter on an [`INLINE` field](/docs/reference/query-language/statements/define/field.md#using-inline-to-filter-a-traversal-during-the-scan) read the keys rather than the cache.

Under `EXPLAIN ANALYZE`, a `GraphEdgeScan` or `ReferenceScan` reports how many lookups were served from a cache as `cache_hits`, and how many went back to the scan as `cache_misses`.

Separately from these caches, a background task packs recently written adjacency keys into blocks, which a traversal reads faster than separate keys. It runs when writes or reads queue work for it, and at least once in every interval set by the `--graph-fold-interval` option of `surreal db start` (`SURREAL_GRAPH_FOLD_INTERVAL`), which is 5 seconds by default. Under `EXPLAIN ANALYZE`, a `GraphEdgeScan` reports the entries it read from blocks as `block_hits` and from separate keys as `delta_hits`.

## Inserting data from undefined fields on a `SCHEMAFULL` table

_(since v3.0.0)_

Previously, an insert into a `SCHEMAFULL` table would work even if extra data was present. The query below shows this behaviour, in which the data inside `unneeded_data` is simply filtered out.

```surql notest
DEFINE TABLE user SCHEMAFULL;
DEFINE FIELD name ON user TYPE string;
DEFINE FIELD user_num ON user TYPE int;

CREATE ONLY user CONTENT { 
    name: "Billy", 
    user_num: 100,
    unneeded_data: {
        some: "other",
        needless: "data"
    }
};
```

```surql title="Output"
{
    id: user:r38bg4fnp9nurksd06nl,
    name: 'Billy',
    user_num: 100
}
```

While convenient, this led to the possibility of a typo leading to unexpected results.

```surql notest
DEFINE TABLE user SCHEMAFULL;
DEFINE FIELD name ON user TYPE string;
DEFINE FIELD user_num ON user TYPE option<int>;

CREATE ONLY user CONTENT { 
    name: "Billy", 
    User_num: 100 // Note: field is capitalized
};
```

The output shows that the `user` lacks a value for `user_num` even though the query above intended to provide this data.

```surql
{
	id: user:jn4762t7oyure86fe3qk,
	name: 'Billy'
}
```

The same query in SurrealDB 3.0 now returns an error.

```surql
"Found field 'User_num', but no such field exists for table 'user'"
```

To avoid an error when working with data that contains unneeded fields, use `.{}` (the destructuring operator) to pass on only the necessary fields.

```surql
DEFINE TABLE user SCHEMAFULL;
DEFINE FIELD name ON user TYPE string;
DEFINE FIELD user_num ON user TYPE int;

CREATE ONLY user CONTENT { 
    name: "Billy", 
    user_num: 100,
    unneeded_data: {
        some: "other",
        needless: "data"
    }
}.{
    -- Only pass on the name and user_num data
    name,
    user_num
};
```

## GraphQL names and deprecation

_(since v3.1.0)_

`GRAPHQL_ALIAS` sets the name that the [GraphQL schema](/docs/learn/querying/graphql/overview.md) uses for a table, in place of the table name. The alias replaces the table name in the query fields, the mutation fields and the connection types, so the example below gives `member`, `members`, `members_aggregate`, `membersConnection` and `createMember`. The object type, the input types and the filter and order types keep the table's own name. It must be a valid GraphQL name, matching `[_A-Za-z][_0-9A-Za-z]*`, and any other value is rejected when the table is defined.

`GRAPHQL_DEPRECATED` takes a reason, which the schema adds to the start of the description of the fetch and list queries and of the mutations as `[Deprecated: reason]`. The aggregate and connection queries do not carry it.

```surql
DEFINE TABLE person
	GRAPHQL_ALIAS "member"
	GRAPHQL_DEPRECATED "Use the account table instead";
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/type

# DEFINE TYPE

The DEFINE TYPE statement declares a named type: a union of strings ordered by declaration, an object shape, or a refined scalar with ASSERT checks and a DEFAULT, used by fields, functions and casts.

_(since v4.0.0)_

The `DEFINE TYPE` statement gives a type a name in the current database. A field, a function argument or return value, or a cast can then use that name in the same places as a built-in type such as `int` or `string`. A write is coerced to the type and checked against its `ASSERT` clauses. See [Named types](/docs/reference/query-language/language-primitives/data-types/named-types.md) for how a named type behaves in a query.

## Requirements

- You must be authenticated as a root owner or editor, namespace owner or editor, or database owner or editor before you can use the `DEFINE TYPE` statement.
- [You must select your namespace and database](/docs/reference/query-language/statements/use.md) before you can use the `DEFINE TYPE` statement.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
DEFINE TYPE [ OVERWRITE | IF NOT EXISTS ] @name AS @type
    [ [ CONSTRAINT @name ] ASSERT @expression ] ...
    [ DEFAULT @expression ]
    [ SQL TYPE POSTGRESQL @string ]
    [ COMMENT @string ]
    [ PERMISSIONS [ NONE | FULL | WHERE @condition ] ]
```

The body after `AS` is a type, in one of three forms:

| Body | Example | A value of the type |
| --- | --- | --- |
| A union of strings | `AS 'low' \| 'medium' \| 'high'` | Is one of the strings, and sorts in the order they are listed |
| An object | `AS { street: string, city: string }` | Is an object with those fields |
| Any other type | `AS int ASSERT $value > 0` | Is a value of that type that passes the checks |

The body can name another type defined with `DEFINE TYPE`. It cannot name a type that does not exist yet, and it cannot lead back to the type being defined, either directly or through other types. A type cannot take the name of a built-in type such as `string`. `PERMISSIONS` decides whether a record user can read the type, and defaults to `FULL`. A cast to a type that the session cannot read fails with `You don't have permission to read the type 'name'`, so the body and checks of the type stay hidden.

## Union types

A union of string literals defines a fixed list of values, from the lowest to the highest. A field of the type accepts only those values, and sorts and compares them in that order.

```surql
DEFINE TYPE priority AS 'low' | 'medium' | 'high' | 'urgent' COMMENT 'Ticket priority, lowest first';
DEFINE FIELD priority ON ticket TYPE priority DEFAULT 'medium';

(INFO FOR DB).types;
```

```surql title="Output"
{
	priority: "DEFINE TYPE priority AS 'low' | 'medium' | 'high' | 'urgent' COMMENT 'Ticket priority, lowest first' PERMISSIONS FULL"
}
```

A value listed twice is kept once, in its first position:

```surql
DEFINE TYPE status AS 'open' | 'closed' | 'open';
(INFO FOR DB).types.status;
```

```surql title="Output"
"DEFINE TYPE status AS 'open' | 'closed' PERMISSIONS FULL"
```

[`ALTER TYPE`](/docs/reference/query-language/statements/alter/type.md) adds values to a union at any position and renames them. The [enum functions](/docs/reference/query-language/functions/database-functions/enum.md) read the values of a union in order.

## Checks and defaults

`ASSERT` takes an expression over `$value`, which holds the value after it has been coerced to the body. A write fails when a check returns `false`, and the checks run in the order they are written. `CONSTRAINT` names the check that follows it, and an error then reports the name instead of the expression.

`DEFAULT` is the value that a field of the type takes when a record is created without a value for it. An update that leaves the field empty does not apply it. A `DEFAULT` on the field itself takes precedence over the type's `DEFAULT`, and a `VALUE` clause on the field reads the type's `DEFAULT` as `$value`.

```surql
DEFINE TYPE percent AS int
    CONSTRAINT in_range ASSERT $value >= 0 AND $value <= 100
    DEFAULT 50;

DEFINE TABLE survey SCHEMAFULL;
DEFINE FIELD score ON survey TYPE percent;

CREATE survey:1;
//- [{ id: survey:1, score: 50 }]

CREATE survey:2 SET score = 140;
```

```surql title="Error output"
"Couldn't coerce value for field `score` of `survey:2`: Expected `percent (constraint in_range failed)` but found `140`"
```

A type built on another type runs the checks of both, those of the inner type first:

```surql
DEFINE TYPE grade AS percent ASSERT $value % 10 = 0;

<grade> 45;
//- "Could not cast into `grade`: Expected `grade (ASSERT $value % 10 = 0 failed)` but found `45`"

<grade> 120;
//- "Could not cast into `grade`: Expected `percent (constraint in_range failed)` but found `120`"
```

## Object types

An object body lists the fields of an object, in the same way as an object literal type on a field. A field or a cast of the type checks each object against it, and refuses an object with a missing field or an extra one.

```surql
DEFINE TYPE address AS { street: string, city: string, postcode: option<string> };
DEFINE FIELD home ON person TYPE option<address>;

CREATE person:1 SET home = { street: '1 Main St' };
```

```surql title="Error output"
"Couldn't coerce value for field `home` of `person:1`: Expected `address ({ city: string, postcode: none | string, street: string })` but found `{ street: '1 Main St' }`"
```

## Using `IF NOT EXISTS` and `OVERWRITE`

Defining a type that already exists fails. With `IF NOT EXISTS`, the statement leaves the existing type unchanged and succeeds. With `OVERWRITE`, it replaces the type.

```surql
-- Uses the priority type defined above
DEFINE TYPE priority AS 'low' | 'high';
//- "The type 'priority' already exists"

DEFINE TYPE IF NOT EXISTS priority AS 'low' | 'high';
enum::values('priority');
//- ['low', 'medium', 'high', 'urgent']
```

`OVERWRITE` can change the body, the checks, the default, the comment and the permissions of a type that is in use. It checks the values that fields of the type already hold in the same way as a write, and fails if a stored value does not pass the new definition. It does not rewrite stored records.

The values of a union are the exception. `OVERWRITE` with a different list, or with the same values in another order, fails while a field or a function names the type. To add or rename a value while the type is in use, use [`ALTER TYPE`](/docs/reference/query-language/statements/alter/type.md).

```surql
DEFINE TYPE OVERWRITE priority AS 'low' | 'high';
```

```surql title="Error output"
"Invalid statement: Cannot change the values of the type 'priority': the field 'priority' on the table 'ticket' has a type that names it"
```

Once no field or function names the type, `OVERWRITE` can set any list of values.

A new body or check that a stored value does not pass is refused, and the error names the field and the value:

```surql
-- Uses the survey table and the percent type defined above
DEFINE TYPE OVERWRITE percent AS int ASSERT $value <= 40;
```

```surql title="Error output"
"Invalid statement: Cannot change the type 'percent': the field 'score' on the table 'survey' holds a value it does not admit: Expected `percent (ASSERT $value <= 40 failed)` but found `50`"
```

### Changing a type that is in use

A type and a field check a change in different ways. A change to a field compares the old definition with the new one, and needs [`MIGRATE EXISTING ROWS`](/docs/reference/query-language/statements/define/field.md#migrating-existing-records) when the new one does not accept everything the old one did, whatever the records hold. A change to a type checks the values that its fields hold, on every table that uses it, including a `SCHEMALESS` one. `DEFINE TYPE` has no `MIGRATE EXISTING ROWS` clause, and `OVERWRITE` converts nothing, so a value that would only pass after a cast still stops the change:

```surql
DEFINE TYPE code AS string;
DEFINE TABLE item SCHEMAFULL;
DEFINE FIELD c ON item TYPE code;
CREATE item:1 SET c = '100';
CREATE item:2 SET c = 'two hundred';

DEFINE TYPE OVERWRITE code AS int;
```

```surql title="Error output"
"Invalid statement: Cannot change the type 'code': the field 'c' on the table 'item' holds a value it does not admit: Expected `code (int)` but found `'100'`"
```

A change that every stored value passes, such as `string` to `string | int`, is accepted. To convert the values, define a new type and change the field to it with a migration, then remove the old type once nothing names it:

```surql
-- Setup from the example above
DEFINE TYPE code AS string;
DEFINE TABLE item SCHEMAFULL;
DEFINE FIELD c ON item TYPE code;
CREATE item:1 SET c = '100';
CREATE item:2 SET c = 'two hundred';

DEFINE TYPE code_int AS int;
ALTER FIELD c ON item TYPE code_int
    MIGRATE EXISTING ROWS AS code_to_int USING <int> $value FALLBACK 0;
REMOVE TYPE code;

SELECT * FROM item;
```

```surql title="Output"
[
	{ c: 100, id: item:1 },
	{ c: 0, id: item:2 }
]
```

To rename a value of a union of strings, use [`ALTER TYPE ... RENAME VALUE`](/docs/reference/query-language/statements/alter/type.md#renaming-values), which rewrites the records that hold it.

## Errors when defining a type

A type that names a type which does not exist, or that leads back to itself, is refused when it is defined. The same applies to a field or a function that names a missing type.

```surql
DEFINE TYPE node AS { next: option<node> };
//- "Invalid statement: The type 'node' cannot be defined: its body leads back to itself through the type 'node'"

DEFINE FIELD score ON survey TYPE missing;
//- "Invalid statement: The field 'score' on the table 'survey' cannot be defined: the type 'missing' it names does not exist"
```

[`REMOVE TYPE`](/docs/reference/query-language/statements/remove.md) fails while another definition names the type, such as a field, a function, an event, a view, a permission or another type.

## Listing types

`INFO FOR DB` lists each type under the `types` key as its `DEFINE TYPE` statement. `INFO FOR DB STRUCTURE` lists each type as an object, with the `labels` of a union in order, and each check with the `name` it was given:

```surql
-- In a database that has only the percent and priority types
(INFO FOR DB STRUCTURE).types;
```

```surql title="Output"
[
	{
		asserts: [
			{
				check: '$value >= 0 AND $value <= 100',
				name: 'in_range'
			}
		],
		default: '50',
		kind: 'int',
		name: 'percent',
		permissions: true
	},
	{
		asserts: [],
		comment: 'Ticket priority, lowest first',
		kind: "'low' | 'medium' | 'high' | 'urgent'",
		labels: ['low', 'medium', 'high', 'urgent'],
		name: 'priority',
		permissions: true
	}
]
```

## Declaring a PostgreSQL type

`SQL TYPE POSTGRESQL` records the type that a client of the [PostgreSQL wire protocol](/docs/reference/protocols/postgres-protocol.md) sees for the type. SurrealQL does not read it: a write or a cast checks only the body, the `ASSERT` clauses and the `DEFAULT`, and the string is stored as it is written. `POSTGRESQL` is the only dialect that `DEFINE TYPE` accepts, and `SQL TYPE MYSQL` is a parse error. A `CREATE DOMAIN` or a `CREATE TYPE` sent over the PostgreSQL protocol defines a type with this clause set. `INFO FOR DB STRUCTURE` shows the string as `sql_type`.

```surql
DEFINE TYPE price AS decimal ASSERT $value >= 0dec
    SQL TYPE POSTGRESQL 'numeric(10,2)';
```

## See also

* [Named types](/docs/reference/query-language/language-primitives/data-types/named-types.md)
* [`ALTER TYPE`](/docs/reference/query-language/statements/alter/type.md)
* [`REMOVE TYPE`](/docs/reference/query-language/statements/remove.md)
* [Enum functions](/docs/reference/query-language/functions/database-functions/enum.md)

---

Source: https://surrealdb.com/docs/reference/query-language/statements/define/user

# DEFINE USER

A DEFINE USER statement can be used to create system users on SurrealDB.

Use the `DEFINE USER` statement to create system users on SurrealDB.

> [!NOTE]
> While existing logins still function, the DEFINE LOGIN statement has been replaced with DEFINE USER.

## Requirements

- You must be authenticated with a user that has enough permissions. Only the OWNER built-in role grants permissions to create users.
- You must be authenticated with a user that has permissions on the level where you are creating the user:
  - Root users with owner permissions can create Root, Namespace and Database users.
  - Namespace users with owner permissions can create Namespace and Database users
  - Database users with owner permissions can create Database users.
- To select the level where you want to create the user, [you may need to select a namespace and/or database](/docs/reference/query-language/statements/use.md) before you can use the `DEFINE USER` statement for database or namespace tokens.

> [!NOTE]
> You cannot use the DEFINE USER statement to create a record user.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
DEFINE USER [ OVERWRITE | IF NOT EXISTS ] @name
	ON [ ROOT | NAMESPACE | DATABASE ]
	[ PASSWORD @pass | PASSHASH @hash ]
	[ PASSSCRAM @verifier ]
	[ ROLES @roles ]
	[ DURATION ( FOR TOKEN @duration [ , ] [ FOR SESSION @duration ] | FOR SESSION @duration [ , ] [ FOR TOKEN @duration ] ) ]
  [ COMMENT @string ]
```

## Example usage

The following example shows how you can create a `ROOT` user using the `DEFINE USER` statement.

```surql
-- Create the user with an owner role and some example durations
DEFINE USER username ON ROOT PASSWORD '123456' ROLES OWNER DURATION
  FOR SESSION 15m,
  FOR TOKEN 5s;
```

Note that even a root-level user can be given a limited role such as `VIEWER`. This can be useful for automated services that need to monitor each namespace and database, or for colleagues in non-technical roles.

```surql
DEFINE USER birthday_bot
  ON ROOT PASSWORD "botpassword9!" ROLES VIEWER;
DEFINE USER clumsy_ceo
  ON ROOT PASSWORD "password" ROLES VIEWER COMMENT "Don't let the CEO have more than VIEWER access";
```

The following example shows how you can create a `NAMESPACE` user using the `DEFINE USER` statement.

```surql
-- Specify the namespace
USE NS abcum;
-- Create the user with an editor role and some example durations
DEFINE USER username ON NAMESPACE PASSWORD '123456' ROLES EDITOR DURATION
  FOR SESSION 12h,
  FOR TOKEN 1m;
```

The following example shows how you can create a `DATABASE` user using the `DEFINE USER` statement.

```surql
-- Specify the namespace and database for the user
USE NS abcum DB app_vitalsense;
-- Create the user with a viewer role and some example durations
DEFINE USER username ON DATABASE PASSWORD '123456' ROLES VIEWER DURATION
  FOR SESSION 5d,
  FOR TOKEN 2h;
```

## Using `IF NOT EXISTS` clause

The `IF NOT EXISTS` clause can be used to define a user only if it does not already exist. You should use the `IF NOT EXISTS` clause when defining a user in SurrealDB if you want to ensure that the user is only created if it does not already exist. If the user already exists, the `DEFINE USER` statement will return an error.

It's particularly useful when you want to safely attempt to define a user without manually checking its existence first.

On the other hand, you should not use the `IF NOT EXISTS` clause when you want to ensure that the user definition is updated regardless of whether it already exists. In such cases, you might prefer using the `OVERWRITE` clause, which allows you to define a user and overwrite an existing one if it already exists, ensuring that the latest version of the user definition is always in use.

```surql
-- Create a USER if it does not already exist
DEFINE USER IF NOT EXISTS example
  ON ROOT PASSWORD "example" ROLES OWNER;
```

## Using `OVERWRITE` clause

The `OVERWRITE` clause can be used to define a user and overwrite an existing one if it already exists. You should use the `OVERWRITE` clause when you want to modify an existing user definition. If the user already exists, the `DEFINE USER` statement will overwrite the existing user definition with the new one.

```surql
-- Create an USER and overwrite if it already exists
DEFINE USER OVERWRITE example ON ROOT PASSWORD "example" ROLES OWNER;
```

## Roles

Currently, only the built-in roles OWNER, EDITOR and VIEWER are available.

<table>
<thead>
  <tr>
    <th>Role</th>
    <th>Description</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>OWNER</td>
    <td>Can view and edit any resource on the user's level or below, including user and token (IAM) resources.<br/>It also grants full permissions for child resources that support the `PERMISSIONS` clause (tables, fields, etc.)</td>
  </tr>
  <tr>
    <td>EDITOR</td>
    <td>Can view and edit any resource on the user's level or below, but not users or token (IAM) resources<br/>It also grants full permissions for child resources that support the `PERMISSIONS` clause (tables, fields, etc.)</td>
  </tr>
  <tr>
    <td>VIEWER</td>
    <td>Grants permissions to view any resource on the user's level or below, but not edit.<br/>It also grants view permissions for child resources that support the `PERMISSIONS` clause (tables, fields, etc.)</td>
  </tr>
</tbody>
</table>

A role applies to every table at the level the user is defined on, and cannot be limited to particular tables. For access to some tables only, use a [record access method](/docs/reference/query-language/statements/define/access/record.md) or a [bearer access method `FOR RECORD`](/docs/reference/query-language/statements/define/access/bearer.md#for-record), and grant the access in each table's [`PERMISSIONS`](/docs/reference/query-language/statements/define/table.md#defining-permissions) clause.

## Duration

The duration clause specifies the duration of the token returned after successful authentication with a password or passhash as well as the duration of the session established both using a password or passhash and the aforementioned token. A session established with the token also ends when the token expires, if that comes first. The difference between these concepts is explained in the [expiration](/docs/learn/security/authentication/users.md#expiration) documentation.

## SCRAM credentials for Postgres clients

_(since v3.3.0)_

When a system user is defined or updated with a plaintext **`PASSWORD`**, SurrealDB automatically derives and stores **SCRAM-SHA-256 verifier material** (PostgreSQL format, PBKDF2-HMAC-SHA-256 with 4096 iterations) alongside the existing Argon2 **`PASSHASH`**. This material is used by the [Postgres wire protocol](/docs/reference/protocols/postgres-protocol.md) listener for SASL challenge-response authentication. You do not call any crypto functions - derivation is entirely automatic.

| Clause | Argon2 hash | SCRAM verifier |
| --- | --- | --- |
| `PASSWORD '…'` | Derived and stored | Derived and stored |
| `PASSHASH '…'` | Stored as given | Not stored (no plaintext available) |
| `PASSSCRAM '…'` | Set by `PASSWORD` or `PASSHASH`, if given | Stored as given, in place of one derived from `PASSWORD` |

`ALTER USER … PASSWORD '…'` regenerates both the Argon2 hash and the SCRAM verifier. `ALTER USER … PASSHASH '…'` updates the hash and **clears** any existing SCRAM verifier, unless the same statement also sets one with `PASSSCRAM`.

Users created before this release, or defined with **`PASSHASH` only**, have no SCRAM material until you set a plaintext password or import a verifier with `PASSSCRAM`. Those users can still authenticate on the Postgres port via **cleartext password** fallback (prefer TLS in production).

### Importing a SCRAM verifier with `PASSSCRAM`

The `PASSSCRAM` clause stores a precomputed SCRAM-SHA-256 verifier, so a user keeps authenticating over SCRAM without the plaintext password being known. It is usually combined with `PASSHASH`, which carries the Argon2 hash in the same way. Both values below were derived from the password `secret`:

```surql
DEFINE USER reporting ON DATABASE
	PASSHASH '$argon2id$v=19$m=19456,t=2,p=1$1JHc8xcjlKQj3BFOY9aLCA$9FlIWQO6wPfQrwVElnWRyU9KBzckbB2EnGOLfGUEzHo'
	PASSSCRAM 'SCRAM-SHA-256$4096:W5weR6PS8IhuFMeyCTr10Q==$eoonh/q2pSTydVV3MZHbqeIlCKGKFOGQSiH7IwjeFpQ=:pYX8KKM1puBfPKyERDxRJ9fYjPxKBXw0Q9elBlpngRQ='
	ROLES VIEWER;
```

The verifier uses the format PostgreSQL stores for SCRAM-SHA-256 passwords, `SCRAM-SHA-256$<iterations>:<salt>$<StoredKey>:<ServerKey>`, where the salt and both keys are base64-encoded. The iteration count must be between 4096 and 16,777,216, the salt must not be empty, and each key must decode to 32 bytes. A verifier that does not meet these rules is rejected when the statement is parsed.

This is the clause that makes users round-trip through an [export](/docs/reference/cli/db/commands/export.md): the export writes each user's stored verifier as `PASSSCRAM` next to `PASSHASH`, so an import restores both. [`INFO`](/docs/reference/query-language/statements/info.md) statements show it as `PASSSCRAM '[REDACTED]'`, in the same way as the hash.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/delete

# DELETE

The DELETE statement can be used to delete records from the database.

The `DELETE` statement can be used to delete records from the database.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
DELETE [ FROM | ONLY ] @targets
	[ WHERE @condition ]
	[ RETURN NONE | RETURN BEFORE | RETURN AFTER | RETURN DIFF
	  | RETURN @statement_param, ... ]
	[ TIMEOUT @duration ]
	[ EXPLAIN [ FULL ]]
;
```

## Example usage

### Basic usage

The following queries show basic usage of the DELETE statement, which is used to delete records from a table or a graph edge.

Deleting records can be done in multiple ways.

Specifying only the table name will delete all the records from a table. Note that a `DELETE` statement returns nothing (i.e. an empty array) by default.

```surql
CREATE person:one, person:two;

-- Delete all records from a table
DELETE person;
```

```surql title="Output"
[]
```

A `DELETE` statement on a specific ID will delete a single record.

```surql
CREATE person:100, person:tobie;

-- Delete a record with a specific numeric id
DELETE person:100;

-- Delete a record with a specific string id
DELETE person:tobie;
```

The `ONLY` keyword unwraps the result, returning a single object instead of an array holding one object. It governs the shape of the output rather than the number of records the statement deletes.

A `DELETE` statement returns nothing by default, so `DELETE ONLY` returns `NONE` and deletes the record.

```surql
CREATE ONLY person:tobie;
DELETE ONLY person:tobie;
```

```surql title="Output"
NONE
```

A record that is already gone also returns `NONE`, so the statement is safe to repeat.

```surql
CREATE ONLY person:tobie;
DELETE ONLY person:tobie;
DELETE ONLY person:tobie;
```

```surql title="Output"
NONE
```

Before SurrealDB 3.0.2, `DELETE ONLY` without a `RETURN BEFORE` clause failed with `Expected a single result output when using the ONLY keyword`, because the empty default output did not match the single object that `ONLY` expected.

Add a `RETURN BEFORE` clause to return the deleted record as a single object.

```surql
CREATE ONLY person:tobie;
DELETE ONLY person:tobie RETURN BEFORE;
```

```surql title="Output"
{ id: person:tobie }
```

As `ONLY` checks the output and not the target, it raises an error when a `RETURN` clause yields more than one record.

```surql
CREATE person:one, person:two, person:three;
DELETE ONLY person RETURN BEFORE;
```

> [!WARNING]
> Without a `RETURN` clause there is no output to check, so `ONLY` places no limit on how many records are deleted. `DELETE ONLY person` removes every record in the `person` table and returns `NONE`. Target a record ID, or use the `LIMIT 1` pattern below, when a statement should reach at most one record.

A `DELETE` statement has no `LIMIT` clause, so pass a `SELECT` subquery with `LIMIT 1` as the target to cap it at a single record.

```surql
CREATE person:one, person:two, person:three;
DELETE ONLY (SELECT * FROM ONLY person LIMIT 1) RETURN BEFORE;
SELECT VALUE id FROM person;
```

To delete more than one record but not all of them, use the same pattern with a larger `LIMIT`. The subquery picks the records and `DELETE` removes them. Add `ORDER BY` so that the records chosen are the ones you intend, and run the statement again to delete the next batch.

```surql
INSERT INTO person [
	{ id: 1, age: 20 },
	{ id: 2, age: 30 },
	{ id: 3, age: 40 },
	{ id: 4, age: 50 },
	{ id: 5, age: 60 }
];

-- Delete the two youngest people over 20
DELETE (
	SELECT VALUE id FROM person WHERE age > 20 ORDER BY age LIMIT 2
) RETURN BEFORE;
```

```surql title="Output"
[{ age: 30, id: person:2 }, { age: 40, id: person:3 }]
```

The subquery here returns record IDs with `SELECT VALUE id`, which `DELETE` accepts as targets. Without `ORDER BY`, the records selected by `LIMIT` are not guaranteed to follow any particular order.

### Deleting records based on conditions

The delete statement supports conditional matching of records using a `WHERE` clause. If the expression in the `WHERE` clause evaluates to true, then the respective record will be deleted.

```surql
CREATE city:london SET name = 'London';

-- Delete all records which match the condition
DELETE city WHERE name = 'London';
```

By default, the delete statement does not return any data, returning only an empty array if the statement succeeds completely. Specify a `RETURN` clause to change the value which is returned for each document that is deleted.

```surql
INSERT INTO user [
    { id: user:one, age: 16, interests: ['gaming'] },
    { id: user:two, age: 30, interests: ['reading'] },
    { id: user:three, age: 45, interests: ['chess'] },
    { id: user:four, age: 60, interests: ['golf'] }
];

-- Don't return any result (the default)
DELETE user WHERE age < 18 RETURN NONE;

-- Return the changeset diff
DELETE user WHERE interests CONTAINS 'reading' RETURN DIFF;

-- Return the record before changes were applied
DELETE user WHERE interests CONTAINS 'chess' RETURN BEFORE;

-- Return the record after changes were applied
DELETE user WHERE interests CONTAINS 'golf' RETURN AFTER;
```

To find out how many records a `DELETE` removed, return them with `RETURN BEFORE` and take the length: `(DELETE user WHERE age < 18 RETURN BEFORE).len()`. See [Counting the records a statement changed](/docs/reference/query-language/statements/update.md#counting-the-records-a-statement-changed).

An important point to know when using a `WHERE` clause is that it performs a check on the [truthiness](/docs/reference/query-language/language-primitives/data-types/values.md#values-and-truthiness) of a value, namely whether a value exists and is not a default value like 0, an empty string, empty array, and so on.

As such, the `DELETE` query below that only specifies `WHERE age` essentially evaluates to "WHERE age exists" and will delete every cat in the database with an `age`.

```surql
CREATE cat:one SET age = 4;
CREATE cat:two;
DELETE cat WHERE age;
SELECT * FROM cat;
```

```surql title="Output"
[
	{
		id: cat:two
	}
]
```

This pattern is particularly useful when using SurrealDB's [literal types](/docs/reference/query-language/language-primitives/data-types/literals.md). A literal type containing objects that contain a single top-level field can easily be matched on through the field name.

```surql
DEFINE FIELD error_info ON TABLE information TYPE
      { continue: { message: "Continue" } }
    | { retry_with_id: { error: string  } }
    | { deprecated: { message: string   } };

CREATE information SET error_info = { continue: { message: "Continue" }};
CREATE information SET error_info = { continue: { message: "Continue" }};
CREATE information SET error_info = { deprecated: { message: "We don't use this anymore" }};

DELETE information WHERE error_info.continue;
SELECT * FROM information;
```

```surql title="Output"
[
	{
		error_info: {
			deprecated: {
				message: "We don't use this anymore"
			}
		},
		id: information:o0pmm7zos98iv03xliav
	}
]
```

### KNN operators in the `WHERE` clause

_(since v4.0.0)_

A KNN operator such as `<|1,COSINE|>` in the `WHERE` clause of a `DELETE` needs a [vector index](/docs/learn/data-models/vector-search/vector-indexes.md) on the field. Without one, the statement fails:

```surql
INSERT INTO article [
	{ id: article:1, embedding: [1.0, 0.0, 0.0] },
	{ id: article:2, embedding: [0.0, 1.0, 0.0] },
	{ id: article:3, embedding: [0.9, 0.1, 0.0] }
] RETURN NONE;
LET $q = [1.0, 0.0, 0.0];
DELETE article WHERE embedding <|1,COSINE|> $q;
```

```text title="Error output"
Invalid query: A KNN operator in the WHERE of an UPDATE or DELETE needs a vector index on the field; define one, or write `UPDATE (SELECT id FROM ... WHERE ...)`.
```

To delete the nearest records without a vector index, select them in a subquery and delete the result. With the records and `$q` above:

```surql
DELETE (SELECT id FROM article WHERE embedding <|1,COSINE|> $q)
	RETURN BEFORE;
```

```surql title="Output"
[
	{
		embedding: [1f, 0f, 0f],
		id: article:1
	}
]
```

### Using TIMEOUT duration records based on conditions
When processing a large result set with many interconnected records, it is possible to use the `TIMEOUT` keywords to specify a timeout duration for the statement. If the statement continues beyond this duration, then the transaction will fail, no records will be deleted from the database, and the statement will return an error.

```surql
CREATE person:one, person:two, person:three;
RELATE person:one->knows->person:two;
RELATE person:two->knows->person:three SET influencer = false;

DELETE person
  WHERE ->knows->person->(knows
  WHERE influencer = false) TIMEOUT 5s;
```

## Deleting graph edges

You can also delete graph edges between two records in the database by using the DELETE statement.

For example the graph edge below:

```surql
RELATE person:tobie->bought->product:iphone;
```

```surql title="Output"
[
	{
		id: bought:ctwsll49k37a7rmqz9rr,
		in: person:tobie,
		out: product:iphone
	}
]
```

Can be deleted by:

```surql
CREATE person:tobie, product:iphone;
RELATE person:tobie->bought->product:iphone;

DELETE person:tobie->bought WHERE out = product:iphone;
```

## Soft deletions

While soft deletions do not exist natively in SurrealDB, they can be simulated by [defining an event](/docs/reference/query-language/statements/define/event.md) that reacts whenever a deletion occurs.

The following example archives the data of a deleted record in another table. This can be combined with  [fewer permissions for the new table](/docs/reference/query-language/statements/define/table.md#defining-permissions) so that it can be accessed only by [system users](/docs/reference/query-language/statements/define/user.md) and not [record users](/docs/reference/query-language/statements/define/access/record.md).

```surql
DEFINE EVENT archive_person ON TABLE person WHEN $event = "DELETE" THEN {
    CREATE deleted_person SET
        data = $before,
        deleted_at = time::now()
};

CREATE |person:1..4|;
DELETE person:1;

-- Only two `person` records left
SELECT * FROM person;
//- [{ id: person:2 }, { id: person:3 }]
-- But the data of `person:1` is still here
SELECT * FROM deleted_person;
```

```surql title="Example output"
[
	{
		data: {
			id: person:1
		},
		deleted_at: d'2024-09-12T00:46:59.176Z',
		id: deleted_person:p3fpzhpxuu9jvjn8juyf
	}
]
```

## The `EXPLAIN` clause

When `EXPLAIN` is used:

1. The `DELETE` statement returns an explanation of its execution plan, which shows how the query will be performed.
2. The records are not deleted.

`EXPLAIN` can be followed by `FULL` to see the number of executed rows.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/explain

# EXPLAIN

The EXPLAIN statement is used to display the query planner for a following statement.

_(since v3.0.0)_

> [!NOTE]
> The output for the `EXPLAIN` statement is for informational purposes and subject to change. Be sure not to develop tools around it that rely on a single predictable output.

The `EXPLAIN` statement is used to display the query planner for a statement.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
EXPLAIN [ ANALYZE ] [ FORMAT TEXT | JSON ] @statement
```

## Example usage

An `EXPLAIN` statement is one that can be appended to another statement that does not modify database resources, i.e. a `SELECT` statement or another statement that returns a value.

The two main decisions to make when using an `EXPLAIN` statement are:

* Use default text format or add `FORMAT JSON` to output the format in JSON?
* Add the `ANALYZE` clause after `EXPLAIN`

The following example shows the four possible types of output when followed by a simple string.

```surql
EXPLAIN "yourself!";
EXPLAIN ANALYZE "yourself!";
EXPLAIN FORMAT JSON "yourself!";
EXPLAIN ANALYZE FORMAT JSON "yourself!";
```

As the output shows, the `ANALYZE` clause adds information on the metrics and total rows.

```surql title="Output"
-------- Query --------

"Expr [ctx: Rt] [expr: 'yourself!']"

-------- Query --------

"Expr [ctx: Rt] [expr: 'yourself!'] {rows: 0, batches: 0, elapsed: 0ns}

Total rows: 1"

-------- Query --------

{
	attributes: {
		expr: "'yourself!'"
	},
	context: 'Rt',
	expressions: [
		{
			role: 'expr',
			sql: "'yourself!'"
		}
	],
	operator: 'Expr'
}

-------- Query --------

{
	attributes: {
		expr: "'yourself!'"
	},
	context: 'Rt',
	expressions: [
		{
			role: 'expr',
			sql: "'yourself!'"
		}
	],
	metrics: {
		elapsed_ns: 0,
		output_batches: 0,
		output_rows: 0
	},
	operator: 'Expr',
	total_rows: 1
}
```

### Context

The `context` field in an `EXPLAIN` statement refers to the minimum context level for an operation: `Rt` (root), `Ns` (namespace), or `Db` (database) level.

### Operator types

The `operator` field in the output of an `EXPLAIN` statement is the most relevant area to take note of. Here is a list of many of the operator types you will see in the statement output.

```text
Aggregate
BitmapAnd
BitmapAndNot
BitmapFullTextScan
BitmapGraphScan
BitmapIndexScan
BitmapOr
BitmapResolve
Compute
CountScan
Explain
ExplainAnalyze
Expr
Fetch
Filter
Foreach
FullTextScan
GraphEdgeScan
IfElse
IndexCountScan
IndexScan
KnnScan
Let
Limit
ProjectValue
Project
SelectProject
ReferenceScan
Return
Scan
Sequence
Sleep
SourceExpr
Split
Union
UnwrapExactlyOne
InfoDatabase
InfoIndex
InfoNamespace
InfoRoot
InfoTable
InfoUser
ExternalSort
Sort
SortByKey
RandomShuffle
SortTopK
SortTopKByKey
```

The `Bitmap` operators appear from 3.3.0, when the planner answers a `WHERE` clause with several indexes at once instead of driving the query from one of them. `BitmapIndexScan`, `BitmapFullTextScan` and `BitmapGraphScan` each read one index into a bitmap of the matching records, `BitmapAnd`, `BitmapOr` and `BitmapAndNot` combine those bitmaps, and `BitmapResolve` fetches the records that remain. The same operators appear beneath `IndexCountScan` when a `count()` is answered from indexes alone, and beneath `KnnScan` when an index pre-filters a vector search.

This allows you to get an insight into exactly what sort of work is being performed by the database when a query is executed.

For example, take the following simple example in which one `person` record has a single friend. The final two queries return the same result, but one is a `SELECT...FROM ONLY` query while the other is a direct destructuring of the link from its record id.

```surql
CREATE person:one, person:two;
RELATE person:one->friend->person:two;

EXPLAIN SELECT ->friend->person AS friends FROM ONLY person:one;
EXPLAIN person:one.{ friends: ->friend->person };
```

The second query is faster, and the output shows why: the first query does more work, with four operations instead of one.

```surql title="Output"
-------- Query 1 --------

'UnwrapExactlyOne [ctx: Db]
    Project [ctx: Db]
          field.lookup: GraphEdgeScan [ctx: Db] [direction: ->, tables: person, output: TargetId]
                    GraphEdgeScan [ctx: Db] [direction: ->, tables: friend, output: TargetId]
                                  CurrentValueSource [ctx: Rt]
                                          RecordIdScan [ctx: Db] [record_id: person:one]'

-------- Query 2 --------

'Expr [ctx: Db] [expr: (person:one).{ friends: ->friend->person }]'
```

Here is an example of output for a query of a complexity more similar to those seen in production applications.

```surql
-- Setup
DEFINE TABLE is_comment_of TYPE RELATION;

EXPLAIN ANALYZE SELECT
  id as commentId,
  in.id as id,
  in.creationDate as creationDate
FROM is_comment_of
WHERE out = media_text_test:0
  AND in.creationDate < d'2026-01-09T00:00:00.000Z'
ORDER BY in.creationDate DESC
LIMIT 2;
```

```surql title="Example output"
"SelectProject [ctx: Db] [projections: commentId, id, creationDate] {rows: 0, batches: 0, elapsed: 21.25µs}
    Limit [ctx: Db] [limit: 2] {rows: 0, batches: 0, elapsed: 21.25µs}
        Sort [ctx: Db] [sort_keys: in.creationDate DESC, keep: 2] {rows: 0, batches: 0, elapsed: 21.25µs}
            TableScan [ctx: Db] [table: is_comment_of, direction: Forward, predicate: out = (media_text_test:0) AND in.creationDate < d'2026-01-09T00:00:00Z', pre_decode_filter: yes, topk_pushdown: yes] {rows: 0, batches: 0, elapsed: 21.25µs}

Total rows: 0"
```

### Filtered KNN and the `predicate` attribute on `KnnScan`

_(since v3.1.5)_

When a [K-nearest neighbours search](/docs/reference/query-language/language-primitives/operators.md#knn) over an indexed vector field is combined with an additional non-KNN condition, the planner pushes that residual condition *into* the index search. Non-matching candidates are rejected during the graph traversal, before they can occupy one of the `K` result slots, rather than being filtered out after the neighbours have been retrieved.

This behaviour can be seen by appending the `EXPLAIN` clause to the end of a query to show its plan. Here, the `KnnScan` operator surfaces this pushed-down condition as a `predicate` attribute, in the same way that `TableScan` exposes its own `predicate`.

```surql
DEFINE INDEX idx_pt ON pts FIELDS point HNSW DIMENSION 4;
INSERT INTO pts [
	{ point: [1, 2, 3, 4], flag: true },
	{ point: [4, 3, 2, 1], flag: false },
	{ point: [3, 3, 3, 3], flag: true }
];

EXPLAIN SELECT id, flag, vector::distance::knn() AS distance FROM pts
	WHERE flag = true AND point <|2,40|> [2, 3, 4, 5]
	ORDER BY distance;
```

```surql title="Output"
'SelectProject [ctx: Db] [projections: id, flag, distance]
    Sort [ctx: Db] [sort_keys: vector::distance::knn() ASC]
        Filter [ctx: Db] [predicate: flag = true]
            KnnScan [ctx: Db] [index: idx_pt, k: 2, ef: 40, dimension: 4, predicate: flag = true]
'
```

The `KnnScan` line shows that the index `idx_pt` is searched for `k: 2` neighbours with an exploration factor of `ef: 40` (the two values of the `<|2,40|>` operator), and that the `flag = true` condition is applied *inside* the search as a `predicate`. The same condition also appears on the `Filter` line above; the difference is that the `predicate` on `KnnScan` is what causes non-matching candidates to be discarded *during* the search rather than only afterwards. Without an extra condition the `predicate` attribute is absent. DISKANN indexes use the same `KnnScan` operator and render an identical line.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/for

# FOR

The FOR statement creates a loop that iterates over the values of an array.

The `FOR` statement can be used to iterate over the values of an array, and to perform certain actions with those values.

> [!NOTE]
> A `FOR` loop currently cannot modify items outside its own scope, such as variables declared before the loop.

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
FOR @item IN @iterable {
@block
};
```

## Example usage
The following query shows example usage of this statement.

```surql
-- Create a person for everyone in the array
FOR $name IN ['Tobie', 'Jaime'] {
	CREATE type::record('person', $name) CONTENT {
		name: $name
	};
};
```

The following query shows the `FOR` statement being used to update a property on every user matching certain criteria.

```surql
-- Set can_vote to true for every person over 18 years old.
FOR $person IN (SELECT VALUE id FROM person WHERE age >= 18) {
	UPDATE $person SET can_vote = true;
};
```

## Ranges in FOR loops

A `FOR` loop can also be made out of a [range](/docs/reference/query-language/language-primitives/data-types/ranges.md) of integers.

```surql
FOR $year IN 0..=2024 {
    CREATE historical_events SET
        for_year = $year,
        events = "To be added";
};
```

## Limitations of FOR loops

Parameters declared outside of a `FOR` loop can be used inside the loop.

```surql
LET $table1 = "person";
LET $table2 = "cat";

FOR $key in 0..4 {
    CREATE type::record($table1, $key);
	  CREATE type::record($table2, $key);
};
```

However, they currently cannot be modified inside a loop, making an operation like the following impossible.

```surql notest
LET $init = [];

FOR $num IN 1..=3 {
	$init += $num;
};
//- Parse error: Unexpected token `+=`, expected an operator
//- (assignment operators are only allowed in SET and DUPLICATE KEY UPDATE clauses)

RETURN $init;
```

In this case, the [`array::fold`](/docs/reference/query-language/functions/database-functions/array.md#arrayfold) and [`array::reduce`](/docs/reference/query-language/functions/database-functions/array.md#arrayreduce) functions can often be used to accomplish the intended behaviour.

```surql
(<array>1..=3).reduce(|$one, $two| $one + $two);
```

```surql title="Output"
6
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/if-else

# IF ELSE

The IF ELSE statement can be used as a main statement, or within a parent statement, to return a value depending on whether a condition, or a series of conditions match.

The `IF ELSE` statement can be used as a main statement, or within a parent statement, to return a value depending on whether a condition, or a series of conditions match. The statement allows for multiple `ELSE IF` expressions, and a final `ELSE` expression, with no limit to the number of `ELSE IF` conditional expressions.

> [!NOTE]
> As [THROW](/docs/reference/query-language/statements/throw.md), [CONTINUE](/docs/reference/query-language/statements/continue.md), and [BREAK](/docs/reference/query-language/statements/break.md) do not return an expression, they must be inside a separate code block inside an `IF ELSE` statement.

An `IF ELSE` syntax uses `{}` to open up a code block on each condition check which will be run when it evaluates as [truthy](/docs/reference/query-language/language-primitives/data-types/values.md#values-and-truthiness).

**Syntax**

```syntax title="Modern syntax"
IF @condition { @expression; .. }
   [ ELSE IF @condition { @expression; .. } ] ...
   [ ELSE { @expression; .. } ]
```

> [!NOTE]
> An older `IF @condition THEN @expression ELSE @expression END` form predates the block syntax introduced in 1.0.0 and is still accepted, so that definitions written against earlier versions keep parsing. A definition stored that way is also returned by `INFO FOR DB` in the same form. Use the block syntax in new queries: a `THEN` branch holds a single expression, which leaves no room for a `LET`, a `THROW`, a `BREAK`, a `CONTINUE`, or two statements separated by a semicolon.

## Example usage

### Basic usage

The following queries show example usage of this statement.

The smallest possible `IF` statement simply does something when a condition is true, and nothing otherwise.

```surql
IF 9 = 9 { 'Nine is indeed nine' };
```

As the last line of a scope is its return value, the `RETURN` keyword can also be placed before the entire `IF ELSE` statement. This is particularly convenient in long `IF ELSE` chains to avoid using the `RETURN` keyword at the end of every check for a condition.

```surql
LET $num = 100;

RETURN IF $num < 0 {
    "Negative"
} ELSE IF $num = 0 {
    "Zero"
} ELSE IF $num = 13 {
    "Thirteen"
} ELSE {
    "Positive uninteresting number"
};
```

The `RETURN` keyword can even be omitted, as the output at each point is the output of the entire expression if evaluated as truthy.

```surql
LET $num = 100;

IF $num < 0 {
    "Negative"
} ELSE IF $num = 0 {
    "Zero"
} ELSE IF $num = 13 {
    "Thirteen"
} ELSE {
    "Positive uninteresting number"
};
```

The `THROW` keyword inside `{}` braces can be used to break out of an `IF ELSE` statement early.

```surql
LET $badly_formatted_datetime = "2024-04TT08:08:08Z";

IF !type::is_datetime($badly_formatted_datetime) {
    THROW "Whoops, that isn't a real datetime"
};
```

```surql title="Output"
"An error occurred: Whoops, that isn't a real datetime"
```

`ELSE IF` branches and a final `ELSE` can be added into an `IF ELSE` statement:

```surql
RETURN
    IF $access = "admin" { (SELECT * FROM account) }
    ELSE IF $access = "user"  { (SELECT * FROM $auth.account) }
    ELSE { THROW "Access method hasn't been defined!" };
```

### Advanced usage

The output of an `IF ELSE` statement can be assigned to a parameter:

```surql
LET $num = 9;

LET $odd_even = 
    IF $num % 2 = 0 { "even" } 
    ELSE { "odd" };
```

If-else statements can also be used as subqueries within other statements.

```surql
UPSERT person SET railcard =
    IF age <= 10 { 'junior' }
    ELSE IF age <= 21 { 'student' }
    ELSE IF age >= 65 { 'senior' }
    ELSE { NULL };
```

You can also have nested conditions:

```surql
IF $access = 'admin'
	{
        CREATE admin_user_event SET 
            time = time::now(),
            info = "Admin user activity registered";
		SELECT * FROM admin_data WHERE access_level = 'full';
	}
ELSE IF $access = 'user'
	{
		IF $auth.role = 'premium'
			{
                CREATE premium_user_event SET 
                    time = time::now(),
                    info = "Premium user activity registered";

				IF $auth.subscription_status = 'active'
					{ SELECT * FROM premium_user_data WHERE active = 1 }
				ELSE IF $auth.subscription_status = 'trial'
					{ SELECT * FROM trial_user_data }
				ELSE
					{ SELECT * FROM basic_user_data }
			}
		ELSE IF $auth.role = 'standard'
			{ SELECT * FROM standard_user_data WHERE region = 'US' }
		ELSE IF $auth.role = 'standard' AND $auth.subscription_status = 'active'
			{ SELECT * FROM standard_user_data WHERE region = 'EU' }
		ELSE
			{ SELECT * FROM unauthorized_user_data }
	}
ELSE
	{ SELECT * FROM unknown_access_data };
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/info

# INFO

The INFO command outputs information about the setup of the SurrealDB system.

The `INFO` command outputs information about the setup of the SurrealDB system. There are a number of different `INFO` commands for retrieving the configuration at the different levels of the database.

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
INFO FOR [
	ROOT
	| NS | NAMESPACE
	| DB | DATABASE
	| TABLE @table
	| USER @user [ON @level]
    | INDEX @index ON @table
];
```

The information returned from an `INFO` command is an object containing items that almost always correspond to a matching [DEFINE](/docs/reference/query-language/statements/define/overview.md) statement. For example, the `INFO FOR NS` command returns the information on the access methods, databases and users of a namespace, which are defined with `DEFINE ACCESS`, `DEFINE DATABASE` and `DEFINE USER` statements.

> [!NOTE]
> Before SurrealDB v3.0.0, the output of an `INFO FOR` was only able to be used as a standalone statement and not in a dynamic context, such as inside other queries or as the value of a parameter.

> [!NOTE]
> From SurrealDB 3.2.2, `INFO FOR ROOT`, `INFO FOR NS`, `INFO FOR DB`, and `INFO FOR USER` always show password hashes as `PASSHASH '[REDACTED]'` (including for root). That keeps schema listings from exposing credential material to every role that can run `INFO`. The hash is still stored, while a privileged [export](/docs/reference/cli/db/commands/export.md) still includes the real `PASSHASH` so backups can restore users. Note that Argon2 hashes remain one-way and salted, so redaction is about who can read the PHC string, not about treating a hash as a plaintext password. From 3.3.0, a user's [SCRAM verifier](/docs/reference/query-language/statements/define/user.md#scram-credentials-for-postgres-clients) is shown the same way, as `PASSSCRAM '[REDACTED]'`, and an export includes the real verifier.

## Example usage

There are a number of different `INFO` commands for retrieving the configuration at the different levels of the database.

## System information

### Root information
The top-level ROOT command returns information regarding:
- The users and namespaces which exists within the SurrealDB system.
- The memory allocated by SurrealDB itself. Note that this may not match what the operating system reports, as it also includes memory consumed by third-party libraries or pre-allocated memory.
- The level of parallelism: This number indicates the number of available hardware threads.

> [!NOTE]
> You must be authenticated as a top-level root user to execute this command.

#### Examples

```surql
INFO FOR ROOT;
```

```surql title="Example output"
{
	accesses: {},
	buckets: {},
	namespaces: {
		ns: 'DEFINE NAMESPACE ns'
	},
	nodes: {
		"2d3b720d-f152-4c0d-8a16-26d1474ed3cd": 'NODE 2d3b720d-f152-4c0d-8a16-26d1474ed3cd SEEN 1745463977888 ACTIVE'
	},
	system: {
		available_parallelism: 14,
		cpu_usage: 0.3816290497779846f,
		load_average: [
			1.2734375f,
			1.68310546875f,
			1.9189453125f
		],
		memory_allocated: 13900485,
		memory_usage: 136314880,
		physical_cores: 14,
		threads: 32
	},
	users: {
		root: "DEFINE USER root ON ROOT PASSHASH '[REDACTED]' PASSSCRAM '[REDACTED]' ROLES OWNER DURATION FOR TOKEN 1h, FOR SESSION NONE"
	}
}
```

### Namespace information

The `NS` or `NAMESPACE` command returns information regarding the users, databases and access methods under the namespace in use. From SurrealDB 4.0, it also returns the namespace's [buckets](/docs/reference/query-language/statements/define/bucket.md#root-and-namespace-buckets), and `INFO FOR ROOT` returns the buckets defined at the root.

> [!NOTE]
> You must be authenticated as a top-level root user, or a namespace user to execute this command.

> [!NOTE]
> You must have a NAMESPACE selected before running this command.

#### Examples

```surql
INFO FOR NS;
```

```surql title="Example output"
{
    accesses: {},
    buckets: {},
    databases: {
        db: 'DEFINE DATABASE db'
    },
    users: {
        n: "DEFINE USER n ON NAMESPACE ROLES VIEWER DURATION FOR TOKEN 1h, FOR SESSION NONE",
        username: "DEFINE USER username ON NAMESPACE PASSHASH '[REDACTED]' PASSSCRAM '[REDACTED]' ROLES EDITOR DURATION FOR TOKEN 1m, FOR SESSION 12h"
    }
}
```

### Database information

The `DB` or `DATABASE` command returns information regarding the users, tables, params, models, functions, analyzers, access methods, sequences and extensions under the database in use. From SurrealDB 4.0, it also returns the database's [compatibility level](/docs/reference/query-language/statements/define/database.md#compatibility-level) as `compatibility`.

> [!NOTE]
> You must be authenticated as a top-level root user, a namespace user, or a database user to execute this command.

> [!NOTE]
> You must have a NAMESPACE and a DATABASE selected before running this command.

#### Examples

```surql
INFO FOR DB;
```

```surql title="Example output"
{
    accesses: {},
    analyzers: {},
    apis: {},
    buckets: {},
    compatibility: 4,
    configs: {},
    extensions: {},
    functions: {},
    models: {},
    params: {},
    sequences: {},
    tables: {
        person: 'DEFINE TABLE person TYPE ANY SCHEMALESS PERMISSIONS NONE'
    },
    types: {},
    users: {
        db_user: "DEFINE USER db_user ON DATABASE PASSHASH '[REDACTED]' PASSSCRAM '[REDACTED]' ROLES OWNER DURATION FOR TOKEN 1h, FOR SESSION NONE"
    }
}
```

### Table information

The `TABLE` command returns information regarding the events, fields, tables, and live statement configurations on a specific table.

> [!NOTE]
> You must be authenticated as a top-level root user, a namespace user, or a database user to execute this command.

> [!NOTE]
> You must have a NAMESPACE and a DATABASE selected before running this command.

#### Examples

```surql
INFO FOR TABLE user;
```

```surql title="Example output"
{
    events: {},
    fields: {
        name: 'DEFINE FIELD name ON user TYPE string PERMISSIONS FULL'
    },
    indexes: {},
    lives: {},
    tables: {}
}
```

### User information

The `USER` command returns information for a user [defined](/docs/reference/query-language/statements/define/user.md) on either the root, namespace, or database level.

> [!NOTE]
> You must be authenticated as a user equal to or greater than the level of the user you are attempting to obtain information for to execute this command.

#### Examples

```surql
-- Setup
DEFINE USER ns_user ON NAMESPACE PASSWORD 'secret' ROLES OWNER;
DEFINE USER db_user ON DATABASE PASSWORD 'secret' ROLES OWNER;

INFO FOR USER root ON ROOT;
INFO FOR USER ns_user ON NAMESPACE;
INFO FOR USER db_user ON DATABASE;
```

If a level after `ON` is not specified, the `INFO` command will default to the database level. Thus, the following two commands are equivalent.

```surql
-- Setup
DEFINE USER db_user ON DATABASE PASSWORD 'secret' ROLES OWNER;

INFO FOR USER db_user ON DATABASE;
INFO FOR USER db_user;
```

```surql title="Output"
"DEFINE USER db_user ON DATABASE PASSHASH '[REDACTED]' PASSSCRAM '[REDACTED]' ROLES OWNER DURATION FOR TOKEN 1h, FOR SESSION NONE"
```

### Index information

`INFO FOR INDEX` returns the status for an index: started, initial indexing, update indexing, built, or error.

The status is most useful when the [`CONCURRENTLY`](/docs/reference/query-language/statements/define/indexes.md#using-concurrently-clause) clause is used in a `DEFINE INDEX` command. Without this clause, the following statement will not be executed until the index is fully created, or fails, so `INFO FOR INDEX` reports an index that is already `ready`.

```surql
CREATE |user:50000| SET name = rand::uuid() RETURN NONE;
DEFINE INDEX unique_name ON TABLE user FIELDS name UNIQUE;
INFO FOR INDEX unique_name ON TABLE user;
```

```surql title="Output"
{
    building: {
        active: false,
        armed_shards: 0,
        compacting: false,
        initial: 50000,
        pending: 0,
        queued: false,
        status: 'ready',
        updated: 0
    }
}
```

However, when the `CONCURRENTLY` clause is used, the index will build in the background while other statements are permitted to run. In this case, the `INFO FOR INDEX` statement will provide the current status on the index. The following code sample shows such an example in which an index is defined on a large number of records. A [`SLEEP`](/docs/reference/query-language/statements/sleep.md) statement is run in between each `INFO FOR INDEX` command to show the progress after each 50 millisecond interval.

```surql
CREATE |user:50000| SET name = rand::uuid() RETURN NONE;
DEFINE INDEX unique_name ON TABLE user FIELDS name UNIQUE CONCURRENTLY;
INFO FOR INDEX unique_name ON user;
SLEEP 50ms;
INFO FOR INDEX unique_name ON user;
SLEEP 50ms;
INFO FOR INDEX unique_name ON user;
SLEEP 50ms;
INFO FOR INDEX unique_name ON user;
```

```surql title="Possible output"
-------- Query 1 --------
{
    building: {
        active: false,
        armed_shards: 0,
        compacting: false,
        queued: false,
        status: 'cleaning'
    }
}

-------- Query 2 --------
{
    building: {
        active: false,
        armed_shards: 0,
        compacting: false,
        initial: 8266,
        pending: 0,
        queued: false,
        status: 'indexing'
    }
}

-------- Query 3 --------
{
    building: {
        active: false,
        armed_shards: 0,
        compacting: false,
        initial: 16516,
        pending: 0,
        queued: false,
        status: 'indexing'
    }
}

-------- Query 4 --------
{
    building: {
        active: false,
        armed_shards: 0,
        compacting: false,
        initial: 24516,
        pending: 0,
        queued: false,
        status: 'indexing'
    }
}
```

Once the build has finished, the status is `ready`, as in the first example.

From SurrealDB 3.3, the `compacting` field is `true` while an HNSW or DISKANN index holds record updates that have not yet been merged into its graph. A KNN search reads those updates alongside the graph and computes their distances one by one, so after a large write, such as a bulk import, searches are slower until background index compaction has merged them and the field returns to `false`. Compaction runs after writes, and at least once in every interval set by the `--index-compaction-interval` option of `surreal db start`, which is 5 seconds by default. In `3.3`, the field is always `false` for every other kind of index. From `4.0`, it also covers full-text and count indexes, as described in [Compaction fields](#compaction-fields).

```surql
DEFINE INDEX idx_embedding ON document FIELDS embedding HNSW DIMENSION 2;
CREATE |document:2000| SET embedding = [rand::float(), rand::float()] RETURN NONE;
INFO FOR INDEX idx_embedding ON document;
```

```surql title="Output"
{
    building: {
        active: false,
        armed_shards: 32,
        compacting: true,
        initial: 0,
        pending: 0,
        queued: true,
        status: 'ready',
        updated: 0
    }
}
```

Note that `pending` reads `0` in that output. `pending` counts writes that arrived while a `CONCURRENTLY` build was running, which is a different queue of updates. It does not report how much is left to compact, so it cannot be used to tell whether a vector index has finished merging.

To wait until a vector index answers at its usual speed, check both fields:

```surql
-- Setup from the example above
DEFINE INDEX idx_embedding ON document FIELDS embedding HNSW DIMENSION 2;
CREATE |document:2000| SET embedding = [rand::float(), rand::float()] RETURN NONE;

LET $info = (INFO FOR INDEX idx_embedding ON document).building;
RETURN $info.status = 'ready' AND $info.compacting = false;
```

#### Compaction fields

_(since v4.0.0)_

From SurrealDB 4.0, `compacting` also covers full-text and count indexes, which keep their recent writes apart in the same way until compaction merges them. The `building` object also has three fields that show where compaction of the index stands:

| Field | Type | Description |
| --- | --- | --- |
| `queued` | `bool` | `true` when a compaction request for the index waits to be processed. A write to a count, full-text, HNSW or DiskANN index queues one. Other kinds of index always report `false`. |
| `active` | `bool` | `true` while a compaction pass over the index runs on the node that answers the statement. |
| `armed_shards` | `int` | For an HNSW or DiskANN index, how many of its 32 pending-write partitions hold writes that compaction has not merged. A KNN search checks these partitions for unmerged writes and skips the others. An HNSW index without the 4.0 index layout reports `0`, as do other kinds of index. An HNSW index built before `4.0` gets that layout when it is rebuilt with [`REBUILD INDEX`](/docs/reference/query-language/statements/rebuild.md); see [Indexes to rebuild](/docs/operate/upgrading/3x-to-4x.md#indexes-to-rebuild). |

The output of the HNSW example above, taken directly after the `CREATE`, shows `queued: true` and `armed_shards: 32`. When compaction has merged the changes, `compacting` and `queued` are `false` and `armed_shards` is `0`.

`active` describes only the node that runs the statement. In a cluster, one node compacts an index at a time, so `active` can be `false` on the node you ask while another node compacts the index. Use `queued` and `compacting` to see whether compaction work remains.

Inside a transaction that has written to an HNSW or DiskANN index and not yet committed, `armed_shards` counts only the partitions that this transaction wrote to.

> [!NOTE]
> A script that compares the whole `building` object with a fixed value fails after an upgrade to 4.0, because the object has more fields. Compare only the fields that the script needs, as the example above that waits for a vector index does.

To count compaction work across all indexes of a node, use the [index compaction metrics](/docs/operate/observability/metrics.md#index-compaction---surrealdbindex).

### Storage size

No `INFO` statement or function reports how much space a namespace, a database or a table takes up. To count the records in a table, use `SELECT count() FROM user GROUP ALL`, which a [count index](/docs/reference/query-language/statements/define/indexes.md#count-index) makes fast.

For the size of the datastore as a whole, measure its directory on disk. Before SurrealDB 4.0, the storage metrics at [`/metrics`](/docs/operate/observability/metrics.md#storage-backend---surrealdbstoragebackend) also gave it for RocksDB: `surrealdb_storage_rocksdb_total_sst_files_size` is the size of the data files, and `surrealdb_storage_rocksdb_cur_size_all_mem_tables` is the size of recent writes that are still in memory and not yet in those files.

### The `STRUCTURE` clause

> [!NOTE]
> This clause was created for internal use and is subject to change without notice.

Adding the `STRUCTURE` clause changes the structure of the statement from an object that contains objects into an object with fields that each contain an array and often extra info.

```surql
DEFINE TABLE user SCHEMAFULL;
DEFINE FIELD name ON user TYPE STRING;

INFO FOR TABLE user;
INFO FOR TABLE user STRUCTURE;
```

```surql title="Output"
-------- Query --------

{
	events: {},
	fields: {
		name: 'DEFINE FIELD name ON user TYPE string PERMISSIONS FULL'
	},
	indexes: {},
	lives: {},
	migrations: {
		generation: 2,
		guaranteed: [],
		migrations: []
	},
	tables: {}
}

-------- Query --------

{
	events: [],
	fields: [
		{
			kind: 'string',
			name: 'name',
			permissions: {
				create: true,
				select: true,
				update: true
			},
			readonly: false,
			table: 'user'
		}
	],
	indexes: [],
	lives: [],
	migrations: {
		generation: 2,
		guaranteed: [],
		migrations: []
	},
	tables: []
}
```

### Using the output of `INFO`

_(since v3.0.0)_

The output of an `INFO` statement, both with and without the `STRUCTURE` clause, can be used in other operations. As the output of the statement is always a single object, the SurrealQL [object functions](/docs/reference/query-language/functions/database-functions/object.md) can also be used on the output for such tasks as schema change tracking.

```surql
LET $cat = CREATE ONLY cat RETURN VALUE id;

LET $first_schema = {
    revision: rand::uuid(),
    schema: INFO FOR DB
};

$first_schema;

CREATE person SET feeds = [$cat];

LET $second_schema = {
    revision: rand::uuid(),
    schema: INFO FOR DB
};

$second_schema;

$first_schema.diff($second_schema);
```

```surql title="Example output"
-------- First schema --------

{
	revision: u'019665cc-f730-75f0-8251-894e11fee7d8',
	schema: {
		accesses: {},
		analyzers: {},
		apis: {},
		buckets: {},
		compatibility: 4,
		configs: {},
		extensions: {},
		functions: {},
		models: {},
		params: {},
		sequences: {},
		tables: {
			cat: 'DEFINE TABLE cat TYPE ANY SCHEMALESS PERMISSIONS NONE'
		},
		types: {},
		users: {}
	}
}

-------- Second schema --------

{
	revision: u'019665cc-f73b-7313-807f-dd22ad1a0685',
	schema: {
		accesses: {},
		analyzers: {},
		apis: {},
		buckets: {},
		compatibility: 4,
		configs: {},
		extensions: {},
		functions: {},
		models: {},
		params: {},
		sequences: {},
		tables: {
			cat: 'DEFINE TABLE cat TYPE ANY SCHEMALESS PERMISSIONS NONE',
			person: 'DEFINE TABLE person TYPE ANY SCHEMALESS PERMISSIONS NONE'
		},
		types: {},
		users: {}
	}
}

-------- Diff --------

[
	{
		op: 'replace',
		path: '/revision',
		value: u'019665cc-f73b-7313-807f-dd22ad1a0685'
	},
	{
		op: 'add',
		path: '/schema/tables/person',
		value: 'DEFINE TABLE person TYPE ANY SCHEMALESS PERMISSIONS NONE'
	}
]
```

As `INFO` statements return an object and objects can be turned into arrays using SurrealDB's [object functions](/docs/reference/query-language/functions/database-functions/object.md), all of the statements for a schema can be constructed using `INFO` statements alone. This query for example shows each of the statements found in a single database.

```surql
LET $db = INFO FOR DB;
  $db.tables.values() +
  $db.users.values() + 
  $db.tables.keys().map(|$t| {
    LET $i = INFO FOR TABLE $t;
    $i.fields.?.values() + $i.indexes.?.values()
  }).flatten().filter(|$v| !!$v);
```

### Default namespace and database output

_(since v3.0.0)_

A namespace and database with the name of `name` are generated by default when starting a SurrealDB instance unless the `SURREAL_NO_DEFAULTS` [environment variable](/docs/reference/cli/db/environment-variables.md) is set to false or the [`--no-defaults`](/docs/reference/cli/db/commands/start.md) flag is used.

The output of the `INFO` statement in this case includes a comment on how these two resources were defined.

```surql
[INFO FOR ROOT.namespaces, INFO FOR NS.databases];
```

```surql title="Output"
[
	{ main: "DEFINE NAMESPACE main COMMENT 'Default namespace generated by SurrealDB'" }, 
	{ main: "DEFINE DATABASE main COMPATIBILITY 4 COMMENT 'Default database generated by SurrealDB'" }
]
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/insert

# INSERT

The INSERT statement can be used to insert or update data into the database, using the same statement syntax as the traditional SQL Insert statement.

The `INSERT` statement can be used to insert or update data into the database, using the same statement syntax as the traditional SQL Insert statement. To compare it with the other statements that write records, see [Writing records that may already exist](/docs/reference/query-language/statements/overview.md#writing-records-that-may-already-exist).

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
INSERT [ RELATION ] [ IGNORE ] INTO @what
	[ @value
	  | (@fields) VALUES (@values)
		[ ON DUPLICATE KEY UPDATE @field = @value ... ]
	]
	[ RETURN NONE | RETURN BEFORE | RETURN AFTER | RETURN DIFF
	  | RETURN @statement_param, ... | RETURN VALUE @statement_param ]
;
```

## Example usage

The following query shows example usage of this statement.

```surql
INSERT INTO company {
	name: 'SurrealDB',
	founded: "2021-09-10",
	founders: [person:tobie, person:jaime],
	tags: ['big data', 'database']
};
```

The object comes directly after the table name, with no `CONTENT` keyword. `CREATE`, `UPDATE` and `RELATE` take one clause (`CONTENT`, `SET`, `MERGE` and so on) that applies the same change to every record they write. `INSERT` takes the data for each record instead, as one object or an array of objects that can each have different fields, so there is no clause to name. Writing `CONTENT` anyway fails with an error that does not mention it, because the parser reads `CONTENT` as the value to insert:

```surql notest
INSERT INTO company CONTENT { name: 'SurrealDB' };
```

```text title="Error output"
Parse error: Unexpected token `{`, expected Eof
```

Records can also be inserted by using the `VALUES` keyword. This keyword is preceded by the name of the fields in question, and followed by comma-separated values matching the number of fields specified.

```surql
-- Insert a single record
INSERT INTO
	company (name, founded)
	VALUES  ('SurrealDB', '2021-09-10');

-- Insert multiple records
INSERT INTO
	company (name, founded)
	VALUES  ('Acme Inc.', '1967-05-03'), ('Apple Inc.', '1976-04-01');
```

It is possible to update records which already exist or violate a unique index by specifying an `ON DUPLICATE KEY UPDATE` clause. This clause also allows incrementing and decrementing numeric values, and adding or removing values from arrays. To increment a numeric value, or to add an item to an array, use the `+=` operator. To decrement a numeric value, or to remove a value from an array, use the `-=` operator.

```surql
INSERT INTO product (name, url) VALUES ('Salesforce', 'salesforce.com')
ON DUPLICATE KEY UPDATE tags += 'crm';
```

Field names inside `ON DUPLICATE KEY UPDATE` refer to the fields of the existing record. To access the fields of the new record that was attempted to be inserted, prefix the field name with [`$input`](/docs/reference/query-language/language-primitives/parameters.md#input):

```surql
INSERT INTO city (id, population, at_year) VALUES ("Calgary", 1665000, 2024)
ON DUPLICATE KEY UPDATE
	population = $input.population,
	at_year = $input.at_year;
```

An example of `ON DUPLICATE KEY UPDATE` when a unique key is encountered shows the same behaviour as that with a duplicate record:

```surql
DEFINE FIELD data_for ON user_data TYPE record<user>;
DEFINE INDEX one_user ON user_data FIELDS data_for UNIQUE;

INSERT INTO user_data {
    data_for: user:one,
    some: "data"
} ON DUPLICATE KEY UPDATE times_updated += 1, last_edited = time::now();

INSERT INTO user_data {
    data_for: user:one,
    some_more: "data"
} ON DUPLICATE KEY UPDATE times_updated += 1, last_edited = time::now();
```

```surql title="Output"
-------- Query --------

[
	{
		data_for: user:one,
		id: user_data:kp78dubsxmp4f04x0de3,
		some: 'data'
	}
]

-------- Query --------

[
	{
		data_for: user:one,
		id: user_data:kp78dubsxmp4f04x0de3,
		last_edited: d'2025-07-14T05:15:52.146Z',
		some: 'data',
		times_updated: 1
	}
]
```

Using the insert statement, it is possible to copy records easily between tables. The records being copied will have the same id in the new table, but the record id will signify the new table name.

```surql
CREATE temperature:1 SET city = 'San Francisco', celsius = 18.5;

INSERT INTO recordings_san_francisco (SELECT * FROM temperature
  WHERE city = 'San Francisco');
```

Furthermore, it is possible to perform a bulk insert in a single query. The `@what` part of the syntax can be either a single object or an array of objects.

```surql
INSERT INTO person [
   { id: "jaime", name: "Jaime", surname: "Morgan Hitchcock" },
   { id: "tobie", name: "Tobie", surname: "Morgan Hitchcock" },
];
```

### Ignoring duplicates

While attempting to insert one or more records via the `INSERT` statement, if the record ID is already present in the table, the query will encounter an error and fail. If the `IGNORE` clause is supplied, records with an already existing or duplicate ID will be silently ignored.

```surql
INSERT IGNORE INTO person [
   { id: "jaime", name: "Jaime", surname: "Morgan Hitchcock" },
   { id: "tobie", name: "Tobie", surname: "Morgan Hitchcock" },

   -- will not throw an error
   { id: "jaime", name: "Jaime", surname: "Morgan Hitchcock" },
];
```

A unique index violation is skipped in the same way. A record that would break a `UNIQUE` index is ignored and the rest of the statement still runs, which gives an insert-if-not-exists pattern without a separate check. Without `IGNORE`, the same statement fails with an error.

```surql
DEFINE INDEX unique_email ON user FIELDS email UNIQUE;
INSERT INTO user { id: 'one', email: 'a@example.com' };

-- The first record repeats an existing email and is skipped
INSERT IGNORE INTO user [
	{ id: 'two', email: 'a@example.com' },
	{ id: 'three', email: 'b@example.com' }
];
```

```surql title="Output"
[{ email: 'b@example.com', id: user:three }]
```

Only the records that were inserted are returned, so an empty array means that every record was skipped.

_(since v3.3.4)_

`IGNORE` skips only a duplicate record ID or a unique index conflict. Any other failure for a record is still raised and fails the statement, for example a field type or `ASSERT` error, or an event that throws. Earlier releases also skipped these failures silently.

The pattern is also safe when two transactions insert the same record at the same time. `IGNORE` decides against the transaction's own snapshot, so it does not skip a record that another transaction has inserted but not yet committed. Instead, the transaction that commits second fails with a transaction conflict error and can be retried, and on the retry the record is skipped as usual. `ON DUPLICATE KEY UPDATE` behaves the same way. See [Unique indexes under concurrent writes](/docs/learn/querying/concepts-and-guides/transactions.md#unique-indexes-under-concurrent-writes).

From SurrealDB 4.0 (and 3.3.4), `IGNORE` skips only a duplicate record ID or a conflict with a `UNIQUE` index. Any other error still fails the statement, including a value that cannot be coerced to the type of its field, a failed `ASSERT`, and a `THROW` in an event.

```surql
DEFINE TABLE item SCHEMAFULL;
DEFINE FIELD n ON item TYPE int;
DEFINE INDEX unique_n ON item FIELDS n UNIQUE;

INSERT INTO item { id: 1, n: 1 };

-- A duplicate ID is skipped
INSERT IGNORE INTO item { id: 1, n: 2 };
//- []

-- So is a conflict with the unique index
INSERT IGNORE INTO item { id: 2, n: 1 };
//- []

-- A value of the wrong type still fails
INSERT IGNORE INTO item { id: 3, n: 'x' };
//- "Couldn't coerce value for field `n` of `item:3`: Expected `int` but found `'x'`"
```

### Return values

By default, the `INSERT` statement returns the record once it has been inserted. To change what is returned, we can use the `RETURN` clause, specifying either `NONE`, `BEFORE`, `AFTER`, `DIFF`, or a comma-separated list of specific fields to return.

`RETURN NONE` can be useful to avoid excess output:

```surql
-- Insert a record and return nothing
INSERT INTO company {
	name: 'SurrealDB',
	founded: "2021-09-10",
	founders: [person:tobie, person:jaime],
	tags: ['big data', 'database']
} RETURN NONE;
```

`RETURN DIFF` returns the changeset diff:

```surql
-- Insert a record and return the diff
INSERT INTO company {
	name: 'SurrealDB',
	founded: "2021-09-10",
	founders: [person:tobie, person:jaime],
	tags: ['big data', 'database']
} RETURN DIFF;
```

```surql title="Output"
-------- Query 1 --------

[
	[
		{
			op: 'replace',
			path: '',
			value: {
				founded: '2021-09-10',
				founders: [
					person:tobie,
					person:jaime
				],
				id: company:hu5o1wqbo29t10engbeo,
				name: 'SurrealDB',
				tags: [
					'big data',
					'database'
				]
			}
		}
	]
]
```

`RETURN BEFORE` inside an `INSERT` statement is essentially a synonym for `RETURN NONE`, while `RETURN AFTER` is the default behaviour for `INSERT`.

```surql
-- Before insert will always return NONE as it is the same as the record being inserted
INSERT INTO company {
	name: 'SurrealDB',
	founded: "2021-09-10",
	founders: [person:tobie, person:jaime],
	tags: ['big data', 'database']
} RETURN BEFORE;
```

```surql
-- Return the record after creation
INSERT INTO company {
	name: 'SurrealDB',
	founded: "2021-09-10",
	founders: [person:tobie, person:jaime],
	tags: ['big data', 'database']
} RETURN AFTER;
```

You can also return specific fields from a created record, the value of a single field using `VALUE`, as well as ad-hoc fields to modify the output as needed.

```surql
INSERT INTO person {
    age: 46,
    username : "john-smith",
    interests : ['skiing', 'music'] }
RETURN
    age,
    interests,
    age + 1 AS age_next_year;

INSERT INTO planet [
	{
		name: 'Venus',
        surface_temp: 462,
        temp_55_km_up: 27
	},
	{
		name: 'Earth',
        surface_temp: 15,
        temp_55_km_up: -55
	}
] RETURN VALUE temp_55_km_up;
```

```surql title="Output"
-------- Query --------

[
	{
		age: 46,
		age_next_year: 47,
		interests: [
			'skiing',
			'music'
		]
	}
]

-------- Query --------

[
	27,
	-55
]
```

## Bulk insert

The `INSERT` statement supports bulk insert, which allows multiple records to be inserted in a single query. The `@what` part of the syntax can be either a single object or an array of objects.

```surql
INSERT INTO person [
   { id: "jaime", name: "Jaime", surname: "Morgan Hitchcock" },
   { id: "tobie", name: "Tobie", surname: "Morgan Hitchcock" },
   -- ... 1000 more records
];
```

A bulk insert can also take an `ON DUPLICATE KEY UPDATE` clause. Each object in the array is inserted in turn, so when the same record ID appears more than once, the first object creates the record and each later one runs the update against the record as it stands at that point. The statement returns the record after each attempt, which shows the update applying once per duplicate. Counting page visits from a batch of events works this way:

```surql
INSERT INTO page [
	{ id: page:home, visits: 1 },
	{ id: page:home, visits: 1 },
	{ id: page:home, visits: 1 },
	{ id: page:home, visits: 1 },
	{ id: page:about, visits: 1 },
	{ id: page:about, visits: 1 }
] ON DUPLICATE KEY UPDATE visits += 1;
//- [{ id: page:home, visits: 1 }, { id: page:home, visits: 2 }, { id: page:home, visits: 3 }, { id: page:home, visits: 4 }, { id: page:about, visits: 1 }, { id: page:about, visits: 2 }]

SELECT * FROM page;
//- [{ id: page:about, visits: 2 }, { id: page:home, visits: 4 }]
```

## Choosing the table with a parameter

The table after `INTO` can be a parameter, which holds either a table name as a string or a table value. A function call cannot go there directly, so `INSERT INTO type::table($name)` is a parse error. Assign the result to a parameter first:

```surql
LET $name = "event_" + "2026";
INSERT INTO $name { kind: "signup" };

LET $table = type::table("person");
INSERT INTO $table { name: "Ann" };
```

To write records to different tables in one statement, leave out `INTO` and give each object a full record ID:

```surql
INSERT [
	{ id: person:ann, name: "Ann" },
	{ id: company:acme, name: "Acme" }
];
```

## Insert relation tables

The `INSERT` statement can also be used to add records into relation tables. The `@what` part of the syntax can be either a single object or an array of objects.

Learn more about creating relationships between tables in the [RELATE](/docs/reference/query-language/statements/relate.md) statement. For example:

```surql
-- Insert records into the person table
INSERT INTO person [
	{ id: 1 },
	{ id: 2 },
	{ id: 3 },
];
-- Insert a single relation
INSERT RELATION INTO likes {
	in: person:1,
	id: 'object',
	out: person:2,
};

-- Insert multiple relations
INSERT RELATION INTO likes [
	{
		in: person:1,
		id: 'array',
		out: person:2,
	},
	{
		in: person:2,
		id: 'array_two',
		out: person:3,
	}
];

-- Insert a relation and return the value of the likes field
INSERT RELATION INTO likes (in, id, out)
	VALUES (person:1, 'values', person:2);

-- Select the value of the likes field
SELECT VALUE ->likes FROM person;
```

From SurrealDB 3.1.5, when `INSERT RELATION` specifies an explicit edge `id` that already exists, SurrealDB returns a record-exists error instead of updating the edge in place. You can use `ON DUPLICATE KEY UPDATE` to merge into the existing relation, in the same way as a normal [`INSERT`](/docs/reference/query-language/statements/insert.md#example-usage):

```surql
CREATE person:one, post:one;

INSERT RELATION INTO likes {
  in: person:one,
  out: post:one,
  id: [person:one, post:one],
  note: 'first',
};

INSERT RELATION INTO likes {
  in: person:one,
  out: post:one,
  id: [person:one, post:one],
  note: 'second',
};

INSERT RELATION INTO likes {
  in: person:one,
  out: post:one,
  id: [person:one, post:one],
  note: 'third',
} ON DUPLICATE KEY UPDATE note = 'updated';
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/kill

# KILL

The KILL statement is used to terminate a running live query.

The `KILL` statement is used to terminate a running live query.

While the `KILL` statement does accept a value type, this value must resolve to a UUID. Consequently, it will accept a string literal of a UUID or a param.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
KILL @value;
```

## Example usage

### Basic usage

The `KILL` statement expects the UUID of a running [live select](/docs/reference/query-language/statements/live-select.md) query to be passed. This UUID can be found in the output of the `LIVE` statement, and can thereafter be passed into a `KILL` statement once it is no longer needed.

```surql
-- Possible output, as every live query is given its own id
LIVE SELECT DIFF FROM person;
//- u'0189d6e3-8eac-703a-9a48-d9faa78b44b9'

-- Some time later...
KILL u"0189d6e3-8eac-703a-9a48-d9faa78b44b9";
```

The `KILL` statement also allows for parameters to be used.

```surql
-- Define the parameter
LET $live_query_id = u"0189d6e3-8eac-703a-9a48-d9faa78b44b9";
-- Use the parameter
KILL $live_query_id;
```

Using the `KILL` statement on a UUID that does not correspond to a running live query will generate an error.

```surql
LET $rand = rand::uuid();
KILL $rand;
KILL u'9276b05b-e59a-49cd-9dd1-17c6fd15c28f';
```

```surql title="Output"
"Can not execute KILL statement using id '$rand'"
"Can not execute KILL statement using id 'u'9276b05b-e59a-49cd-9dd1-17c6fd15c28f''"
```

## Kill notifications

_(since v3.0.0)_

A separate notification is sent out when a `KILL` statement is enacted on a live query ID.

```surql
-- Possible output, as every live query is given its own id
LIVE SELECT * FROM person;
//- u'cf447091-9463-4d75-b32a-08513eb2a07c'

KILL u'cf447091-9463-4d75-b32a-08513eb2a07c';
```

```surql title="Output"
-- Query 1
NONE

-- Notification (action: Killed, live query ID: cf447091-9463-4d75-b32a-08513eb2a07c)
NONE
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/let

# LET

The LET statement sets and stores a value which can then be used in a subsequent query.

The `LET` statement allows you to create parameters to store any value, including the results of queries or the outputs of expressions. These parameters can then be referenced throughout your SurrealQL code, making your queries more dynamic and reusable.

## Syntax

The syntax for the `LET` statement is straightforward. The parameter name is prefixed with a `$` symbol.

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
LET $parameter [: @type_name] = @value;
```

## Example usage

### Basic parameter assignment

You can use the `LET` statement to store simple values or query results. For example, storing a string value and then using it in a `CREATE` statement:

```surql
-- Define the parameter
LET $name = "tobie";
-- Use the parameter
CREATE person SET name = $name;
```

### Storing query results

The `LET` statement is also useful for storing the results of a query, which can then be used in subsequent operations:

```surql
-- Define the parameter
LET $adults = SELECT * FROM person WHERE age > 18;
-- Use the parameter
UPDATE $adults SET adult = true;
```

### Conditional logic with `IF ELSE`

SurrealQL allows you to define parameters based on conditional logic using `IF ELSE` statements:

```surql
LET $num = 10;

LET $num_type =
         IF type::is_int($num)     { "integer" }
    ELSE IF type::is_decimal($num) { "decimal" }
    ELSE IF type::is_float($num)   { "float"   };

RETURN $num_type;
```

```surql title="Output"
'integer'
```

## Anonymous functions

You can define anonymous functions also known as closures using the `LET` statement. These functions can be used to encapsulate reusable logic and can be called from within your queries. Learn more about [anonymous functions](/docs/reference/query-language/language-primitives/data-types/closures.md) in the Data model section.

## Pre-defined and protected parameters

SurrealDB comes with [pre-defined parameters](/docs/reference/query-language/language-primitives/parameters.md) that are accessible in any context. However, parameters created using `LET` are not accessible within the scope of these pre-defined parameters.

Some pre-defined parameters are protected and cannot be set using `LET`: `$access`, `$auth`, `$token` and `$session`, which hold parts of the current session. Attempting to redefine them will result in an error:

```surql
LET $auth = 1;
LET $session = 10;
```

```surql title="Output"
-------- Query 1 --------

"'auth' is a protected variable and cannot be set"

-------- Query 2 --------

"'session' is a protected variable and cannot be set"
```

These four names cannot be used as a `FOR` variable, a closure parameter or the argument of a [defined function](/docs/reference/query-language/statements/define/function.md) either, and each of these fails with the same error.

Other names are bound by SurrealDB itself inside a statement or clause: `$this`, `$self`, `$parent`, `$value`, `$input`, `$before`, `$after` and `$event`. A `LET` that is a statement of its own can use one of these names, and the statement that binds the name shadows it, so the parameter keeps its value outside that statement:

```surql
LET $before = "Before!";

-- Returns "Before!"
RETURN $before;

-- Returns the `person` records before deletion
DELETE person RETURN $before;

-- Returns "Before!" again
RETURN $before;
```

_(since v4.0.0)_

A `LET` written inside a block, an `IF` branch, a function body or a closure body cannot use one of these names, because nothing would shadow it there. The whole statement is refused, and `DEFINE FUNCTION` refuses a function body that holds such a `LET`:

```surql
{ LET $value = 1; $value };
```

```surql title="Output"
"'value' is a protected variable and cannot be set"
```

From SurrealDB 4.0, a `LET` that no statement may hold is refused wherever it is written, even in code that never runs, such as after a `RETURN` or in an `IF` branch that is not taken. This covers a protected name, and a `LET` used as a value, such as `SELECT * FROM t WHERE (LET $x = 1)`, which fails with `LET statements can only appear at the top level of a query or inside a block expression`. A `VALUE` clause or other stored clause that holds such a `LET` is refused when it is defined.

## Typed LET statements

Type safety in a `LET` statement can be ensured by adding a `:` (a colon) and the type name after the `LET` keyword.

```surql
LET $number: int = "9";
```

```surql title="Output"
"Tried to set `$number`, but couldn't coerce value: Expected `int` but found `'9'`"
```

### Typed literal statements

Multiple possible types can be specified in a `LET` statement by adding a `|` (vertical bar) in between each possible type.

```surql
LET $number: int | string = "9";
```

Even complex types such as objects can be included in a typed `LET` statement.

```surql
LET $error_info: 
  string | { error: string } = 
  { 
    error: "Something went wrong plz help" 
  };
```

For more information on this pattern, see the page on [literals](/docs/reference/query-language/language-primitives/data-types/literals.md).

## Conclusion

The `LET` statement stores values, the results of subqueries, and anonymous functions in parameters that later statements can use.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/live-select

# LIVE SELECT

The LIVE SELECT statement can be used to initiate a real-time selection from a table, including the option to apply filters.

Live Queries is a feature that allows you to listen for creations, updates and deletions to specific records you are interested in or entire tables.

The `LIVE SELECT` statement can be used to initiate a real-time selection from a table, including the option to apply filters.

In practical terms, when you execute a `LIVE SELECT` query, it triggers an ongoing session that captures any subsequent changes to the data in real-time. These changes are then immediately transmitted to the client, ensuring that the client is consistently updated with the latest data modifications.

> [!NOTE]
> Errors while evaluating a live query's `WHERE` clause or projection (for example a type mismatch) skip that notification; they do not roll back the write that triggered the live query. Live subscriptions are ended when the session is invalidated or its TTL expires, when you [`KILL`](/docs/reference/query-language/statements/kill.md) the live query, or when the underlying table is removed. Built-in live parameters (`$value`, `$before`, `$after`, `$event`, and related names) always take precedence over user variables captured at registration time.

> [!IMPORTANT]
> In SurrealDB Community, a live query only receives changes made on the node that holds its subscription, so it suits single-node deployments. Live queries that receive changes from every node in a cluster are part of [Enterprise Edition](/docs/operate/enterprise/product/database-enterprise.md), as distributed live queries.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
LIVE SELECT
	[
		[ VALUE ] @fields ... [ AS @alias ]
		| DIFF
	]
	FROM @targets
	[ WHERE @conditions ]
	[ FETCH @fields ... ]
;
```

## Example usage

### Basic usage

By default, SurrealDB will push the entire record over the websocket when it is created or updated. When a record is deleted, the notification carries the record as it was before deletion.

```surql
LIVE SELECT * FROM person;
```

```surql title="Example output"
u'b1f1d115-ad0f-460d-8cbf-dbc7ce48851c'
```

The result of the above query will be a UUID. This UUID is the Live Query Unique ID, and is used to differentiate between different Live Queries. You will want to keep track of this ID, so that you can differentiate between different notifications being received after this query. You can also use this UUID to [KILL](/docs/reference/query-language/statements/kill.md) (stop) the Live Query. The protocol will then send messages that are of a Notification format.

You can find an example of such a message in the [Live Query WebSocket protocol](/docs/reference/protocols/rpc-protocol.md#live) description.

### Diff

When using the `DIFF` mode, updates will be sent in the form of an array with [JSON Patch](https://jsonpatch.com/) messages.

```surql
LIVE SELECT DIFF FROM person;
```

```surql title="Example output"
u\'b87cbb0d-ca15-4f0a-8f86-caa680672aa5\'
```

### Filter the live query

You can optionally apply filters with the `WHERE` clause.

```surql
LIVE SELECT * FROM person WHERE age > 18;
```

A live query filter is evaluated against the record after the change, so a record that stops matching the filter produces no notification. The `$before` and `$after` parameters hold the record as it was before and after the change, and can be used in the `WHERE` clause to compare the two. The following live query also notifies when a task stops being open, because `$before` still matches:

```surql
DEFINE TABLE task;
LIVE SELECT * FROM task WHERE status = 'open' OR $before.status = 'open';
```

With this live query, `CREATE task:1 SET status = 'open'` and then `UPDATE task:1 SET status = 'done'` each send a notification, the second one carrying the record with `status: 'done'`. A further update from `'done'` to `'archived'` sends nothing, because neither the old nor the new value is `'open'`.

### Filter by event

The `$event` parameter holds the kind of change that triggered the notification: `'CREATE'`, `'UPDATE'` or `'DELETE'`. Use it in the `WHERE` clause to receive only some kinds of change.

```surql
LIVE SELECT * FROM person WHERE $event = 'CREATE';
```

To receive several kinds, compare against an array.

```surql
LIVE SELECT * FROM person WHERE $event IN ['UPDATE', 'DELETE'];
```

Over a WebSocket connection, the first query above delivers a notification for each created record and none for updates or deletes. The second delivers notifications for updates and deletes only.

### Relation tables

A live query on a [relation table](/docs/reference/query-language/statements/define/table.md) sends a notification each time an edge is created, updated or deleted, so a client can watch for new relationships.

```surql
DEFINE TABLE wrote TYPE RELATION;
LIVE SELECT * FROM wrote;

RELATE person:a->wrote->person:b SET at = 1;
```

```json title="Sample notification"
{
	"action": "CREATE",
	"id": "8fcb4c22-b4f6-4f6d-9eca-80f872146ad9",
	"record": "wrote:7exf5ouot5pw40ekjnfi",
	"result": {
		"at": 1,
		"id": "wrote:7exf5ouot5pw40ekjnfi",
		"in": "person:a",
		"out": "person:b"
	}
}
```

A live query takes a table, so graph traversal such as `LIVE SELECT ->wrote FROM person:a` is not supported and returns `Cannot execute LIVE statement using value: person:a`. To follow the edges of one record, filter the relation table on its `in` or `out` field instead:

```surql
LIVE SELECT * FROM wrote WHERE in = person:a;
```

A live query on a node table such as `person` sends a notification only when a `person` record changes. `RELATE` writes to the edge table, and so does deleting an edge, so neither sends a notification to that live query. A projection such as `<-wrote<-person` shows the edges as they were when the `person` record last changed, and a `WHERE` clause that depends on edges is not checked again on `RELATE`. To follow relationships as they are added and removed, run the live query on the edge table: `LIVE SELECT in, out FROM wrote` sends `CREATE` for each `RELATE`, and `DELETE` when an edge is removed, including when deleting a node removes its edges.

<img src="~/assets/img/diagrams/light/live-query-relation-light.webp" darkSrc="~/assets/img/diagrams/live-query-relation.webp" alt="RELATE person:a->wrote->person:b writes one record, to the wrote table. A live query on wrote is notified with action CREATE and the edge's in and out. A live query on person is not notified, because no person record changed. Notifications are sent only after the transaction commits." />

## Consistency guarantees

When using Live Queries, it is important to understand the ordering of messages and events when many clients and transactions are running in parallel. Notifications on live queries are only published for committed transactions. From SurrealDB 4.0, this includes a transaction that a client opens and commits itself, such as one started with an SDK's `begin()` method: its notifications are sent when it commits, and none are sent if it is cancelled or its commit fails. In earlier versions, a write inside such a transaction sent no notification.

Ordering is kept correct on a best-effort basis, but it is not yet strictly guaranteed. As such, some messages may be received out of order from their commit order. However, transactions that are committed from the same client will always be in order.

Security enforcement is always evaluated per notification and will reflect the value of authorisation at the time of publishing the notification. This means that if a transaction is committed, after which the authorisation immediately changes for the live query receiver, the receiver will get the notification under the new rules.

The `WHERE` clause, the projection and the `FETCH` clause of a live query cannot change data when a notification is evaluated. A subquery in them that creates, updates or deletes records is refused at that point, and so is a function that changes state or waits, such as `sequence::nextval()` or `sleep()`. The live query still registers, but sends no notification for a change that reaches such an expression. Reads are not affected, so a subquery that selects from another table still works.

```surql
-- Registers, but sends no notification: the projection tries to write
LIVE SELECT *, (CREATE audit SET seen = time::now()) AS logged FROM person;
```

### Changing a session's authentication ends its live queries

A live query records the authentication principal of the session that registered it. If that session becomes a different principal - through `signin`, `signup`, `authenticate`, `invalidate`, or a token refresh that resolves to a different identity - the session's live queries are ended and receive no further notifications. They must be registered again under the new principal if they are still needed.

A token refresh for the same identity does not change the principal, so its live queries continue.

> [!NOTE]
> Before SurrealDB 3.3.0, embedded engines (`mem://`, `rocksdb://`, `surrealkv://`) did not end live queries when the session's principal changed, so a subscription kept sending notifications under the access controls of the previous principal. Connections over `ws://` and `http://` behaved as described above.

### Live queries end with their connection

A live query belongs to the WebSocket connection that started it. When the connection closes, whether the client closes it or the network drops it, the server ends every live query that the connection started, so a client that disconnects without running [`KILL`](/docs/reference/query-language/statements/kill.md) leaves nothing running. The RPC [`reset`](/docs/reference/protocols/rpc-protocol.md#reset) method also ends the connection's live queries.

A client that reconnects gets a new connection, so it has to start its live queries again. The JavaScript SDK does this for live queries created with [`.live()`](/docs/reference/javascript/concepts/live-queries.md#automatic-restart-on-reconnect), but not for a `LIVE SELECT` statement sent as a query.

## Fetching inside live queries

The `FETCH` clause can be used inside live queries as well.

```surql
LIVE SELECT * FROM person WHERE age > 18 FETCH friends;
```

## Other notes

Since SurrealDB 3.0, parameters can be used inside a `LIVE SELECT` statement, including in the `WHERE` clause (see [Parameters in `LIVE SELECT` statements](#parameters-in-live-select-statements) below). Parameter values are captured when the live query is registered; changing a parameter afterwards does not affect an already-registered live query - re-register the live query to apply a new value.

Note that a bare parameter cannot be used as the table reference. Use `type::table()` instead:

```surql
-- Does not work: bare parameter as the table reference
-- LIVE SELECT * FROM $table WHERE field > 50;

-- Works:
LIVE SELECT * FROM type::table($table) WHERE field > 50;
```

## Parameters in `LIVE SELECT` statements

_(since v3.0.0)_

Parameters can also be used inside a `LIVE SELECT` statement.

```surql
LET $table = 'measurement';
LET $location = 'Tallinn';
LIVE SELECT * FROM type::table($table) WHERE location == $location;
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/overview

# Statements

Reference overview: SurrealQL statements for resources, control flow, transactions and CRUD or data operations.

SurrealDB provides statements to configure resources, control execution flow, and read or write data. The categories below group them by role.

## Types of statements

SurrealDB has a large variety of statements. They can be divided into three types:

* Statements that define and access database resources,
* Statements used for control flow and handling manual transactions,
* Statements used in the context of queries, usually in CRUD (create, read, update, delete) operations.

### Database resource statements

These statements pertain to defining, removing, altering, and rebuilding database resources. They are:

* [`DEFINE`](/docs/reference/query-language/statements/define/overview.md) statements to define database resources,
* [`ALTER`](/docs/reference/query-language/statements/alter/overview.md) statements to alter certain resources,
* [`REMOVE`](/docs/reference/query-language/statements/remove.md) statements to remove resources,
* [`REBUILD`](/docs/reference/query-language/statements/rebuild.md) to rebuild an index,
* [`ACCESS`](/docs/reference/query-language/statements/access.md) to manage access grants.

Some other statements pertain to using defined resources. They are:

* [`USE`](/docs/reference/query-language/statements/use.md) to move from one namespace or database to another,
* [`INFO`](/docs/reference/query-language/statements/info.md) statements to see the definitions for resources,
* [`SHOW`](/docs/reference/query-language/statements/show.md) to see the changefeed for a table or database.

### Control flow statements

These statements are used to describe how query execution should progress.

Some control flow statements only pertain to manual transactions. While all statements in SurrealDB are conducted inside their own transaction, these statements can be used to manually set up a larger transaction composed of multiple statements. They are:

* [`BEGIN`](/docs/reference/query-language/statements/begin.md) to begin a manual transaction,
* [`COMMIT`](/docs/reference/query-language/statements/commit.md) to commit a transaction,
* [`CANCEL`](/docs/reference/query-language/statements/cancel.md) to cancel a transaction.

Other control flow statements are used in the same manner as in other programming languages. They are:

* [`FOR`](/docs/reference/query-language/statements/for.md) to begin a for loop,
* [`CONTINUE`](/docs/reference/query-language/statements/continue.md) to continue to the next iteration of a loop,
* [`BREAK`](/docs/reference/query-language/statements/break.md) to break out of a for loop, internal scope, function, etc.,
* [`IF` and `ELSE`](/docs/reference/query-language/statements/if-else.md) to describe what to do depending on a condition,
* [`SLEEP`](/docs/reference/query-language/statements/sleep.md) to halt all execution for a certain length of time,
* [`RETURN`](/docs/reference/query-language/statements/return.md) to break and return a value,
* [`THROW`](/docs/reference/query-language/statements/throw.md) to cancel execution and return an error.

### Query statements

These statements are used to execute queries, most often but not always in the context of a CRUD operation.

The statements that pertain to the handling of records are:

* [`CREATE`](/docs/reference/query-language/statements/create.md) to create one or more records of one or more types of tables,
* [`INSERT`](/docs/reference/query-language/statements/insert.md) to create one or more regular records or graph edges,
* [`RELATE`](/docs/reference/query-language/statements/relate.md) to create a single graph edge between two records,
* [`UPDATE`](/docs/reference/query-language/statements/update.md) to update records,
* [`UPSERT`](/docs/reference/query-language/statements/upsert.md) to update a record and create a new one if it does not exist,
* [`SELECT`](/docs/reference/query-language/statements/select.md) to select records (but also ad-hoc values),
* [`LIVE SELECT`](/docs/reference/query-language/statements/live-select.md) to stream all the changes to a table,
* [`DELETE`](/docs/reference/query-language/statements/delete.md) to delete one or more records,
* [`KILL`](/docs/reference/query-language/statements/kill.md) to cancel a `LIVE SELECT`.

The other statements used when executing a query are:

* [`LET`](/docs/reference/query-language/statements/let.md) to assign a value to a parameter for later use,
* [`RETURN`](/docs/reference/query-language/statements/return.md) when used in front of a value or expression, in which case it has no effect but is often used for readability.

The following flowchart can be used to get a sense of when it makes sense to use `CREATE`, `INSERT`, `UPDATE`, `UPSERT`, and `RELATE`.

<img src="~/assets/img/surrealql/statements/statement_flowchart-light.png" darkSrc="~/assets/img/surrealql/statements/statement_flowchart.png" alt="A flowchart that explains in which cases to use the statements CREATE, INSERT, UPDATE, UPSERT, and RELATE." />

## Statement parameters

A number of parameters prefixed with `$` are automatically available within a statement that provide access to relevant context inside the statement. These are known as reserved variable names. For example:

* [$before](/docs/reference/query-language/language-primitives/parameters.md#before-after) and [$after](/docs/reference/query-language/language-primitives/parameters.md#before-after) can be accessed in statements that mutate values to see the values before and after an update,
* [$session](/docs/reference/query-language/language-primitives/parameters.md#session) provides context on the current session,
* [$parent](/docs/reference/query-language/language-primitives/parameters.md#parent-this) provides access to the value in a primary query while inside a subquery.

For a full list of these automatically generated parameters, see the [parameters](/docs/reference/query-language/language-primitives/parameters.md#reserved-variable-names) page.

## Output when resource not defined

_(since v3.0.0)_

Many but not all statements in versions before 3.0 returned an empty array when a resource was not defined.

```surql
SELECT * FROM person;
DELETE person;
REMOVE TABLE person;
```

```surql title="Output before 3.0"
-------- Query 1 --------

[]

-------- Query 2 --------

[]

-------- Query 3 --------

"The table 'person' does not exist"
```

All statements return an error if this is the case, making it clear that the resource is not defined as opposed to defined and empty.

```surql
SELECT * FROM person;
DELETE person;
```

```surql title="Output"
-------- Query --------

"The table 'person' does not exist"

-------- Query --------

"The table 'person' does not exist"
```

However, statements that create a resource will not return an error unless the [database is defined](/docs/reference/query-language/statements/define/database.md) as `STRICT`. Instead, they will automatically define the needed table (and even use the [`$session`](/docs/learn/security/authentication/users.md#session) parameter to define the database and namespace if necessary) so that the query will work.

Note the output of the following queries, in which the value `[]` is returned after deleting the records of a defined table to show that zero records were returned. However, the final `REMOVE TABLE` statement returns a simple `NONE` to indicate that the statement succeeded.

```surql
SELECT * FROM person; -- Error
DELETE person;        -- Error
CREATE person:one;    -- Succeeds
DELETE person;        -- Empty array
REMOVE TABLE person;  -- NONE
```

The following chart can help to remember which output to expect depending on your SurrealDB version and database strictness.

| Example of statement  | STRICT database      | Non-STRICT database behaviour (default)                     | Behaviour in versions < 3.0       |
|-----------------------|----------------------|------------------------------------------------------------|----------------------------------|
| CREATE                | Error if not defined | Succeeds (defines table, database, namespace if necessary) | Identical                        |
| SELECT / UPDATE / DELETE | Error if not defined | Returns error if table not defined                      | Empty array if table not defined |

## Writing records that may already exist

`CREATE`, `INSERT`, `UPSERT`, `UPDATE` and `RELATE` all write records, and they differ in what they do when the record ID is already in use. The table below compares them for a statement that names a record ID, such as `person:one`.

| Statement | Record does not exist | Record already exists |
| --- | --- | --- |
| [`CREATE`](/docs/reference/query-language/statements/create.md) | Creates it | Error: ``Database record `person:one` already exists`` |
| [`INSERT`](/docs/reference/query-language/statements/insert.md) | Creates it | Error, as for `CREATE` |
| `INSERT IGNORE` | Creates it | Leaves the record unchanged, and returns nothing for it |
| `INSERT ... ON DUPLICATE KEY UPDATE` | Creates it | Updates it with the `ON DUPLICATE KEY UPDATE` clause |
| [`UPSERT`](/docs/reference/query-language/statements/upsert.md) | Creates it | Updates it |
| [`UPDATE`](/docs/reference/query-language/statements/update.md) | Does nothing, and returns `[]` | Updates it |
| [`RELATE`](/docs/reference/query-language/statements/relate.md) with an edge ID | Creates the edge | Updates the edge and logs a warning. Use `RELATE OR UPDATE` to update on purpose, or define a `UNIQUE` index to get an error instead |
| `INSERT RELATION` | Creates the edge | Error, as for `CREATE`. `INSERT RELATION IGNORE` leaves the edge unchanged |

A `RELATE` without an edge ID always creates a new edge with a random ID, so relating the same two records twice gives two edges. A [`UNIQUE` index](/docs/reference/query-language/statements/define/indexes.md#unique-index) on the edge table's `in` and `out` fields prevents that.

```surql
CREATE person:one SET name = 'one';

-- Error: the record already exists
CREATE person:one SET name = 'new';
//- 'Database record `person:one` already exists'

-- Unchanged, and returns []
INSERT IGNORE INTO person { id: person:one, name: 'new' };

-- Updated
UPSERT person:one SET name = 'new';

SELECT * FROM person;
```

```surql title="Output"
[{ id: person:one, name: 'new' }]
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/rebuild

# REBUILD

The REBUILD statement is used to rebuild indexes.

The `REBUILD` statement is used to rebuild indexes in SurrealDB. It is usually used in relation to a specified [Index](/docs/reference/query-language/statements/define/indexes.md) to optimise performance. It is useful to rebuild indexes because sometimes [HNSW](/docs/reference/query-language/statements/define/indexes.md#hnsw-hierarchical-navigable-small-world) index performance can degrade due to frequent updates.

Rebuilding the index will ensure the index is fully optimised.

> [!NOTE]
> By default, `REBUILD INDEX` waits until the rebuild finishes before the statement returns (the same behaviour as `DEFINE INDEX` without `CONCURRENTLY`). Adding `CONCURRENTLY` on the rebuild statement will cause it to return immediately, after which progress can be monitored via [`INFO FOR INDEX`](/docs/reference/query-language/statements/info.md#index-information). Whether the index was originally created with `CONCURRENTLY` does not affect rebuilds. See the [`CONCURRENTLY` clause](/docs/reference/query-language/statements/define/indexes.md#using-concurrently-clause) on `DEFINE INDEX` for the same blocking vs non-blocking distinction when creating an index.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
REBUILD [
	INDEX [ IF EXISTS ] @name ON [ TABLE ] @table [ CONCURRENTLY ]
]
```

> [!NOTE]
> The `IF EXISTS` and TABLE clauses are optional.

## Example usage

For example, if you have a table called `book` and you have an index called `uniq_isbn` on the `isbn` field, you can rebuild the index using the following query:

```surql
-- Setup
CREATE book:1 SET title = 'Rust Web Programming', isbn = '978-1803234694', author = 'Jon Doe';
DEFINE INDEX uniq_isbn ON book FIELDS isbn UNIQUE;

REBUILD INDEX uniq_isbn ON book;
```

```surql
CREATE book:1 SET title = 'Rust Web Programming', isbn = '978-1803234694', author = 'Jon Doe';
// Define a unique index on the isbn field
DEFINE INDEX uniq_isbn ON book FIELDS isbn UNIQUE;
// Rebuild this index incase of more updates
REBUILD INDEX IF EXISTS uniq_isbn ON book;
// Check that the index has been created
INFO FOR TABLE book;
REBUILD INDEX IF EXISTS idx_author ON book;
REBUILD INDEX IF EXISTS ft_title ON book;
// Define index on the author field
DEFINE INDEX idx_author ON book FIELDS author;
// Define an analyzer which has blank and class Tokenizers and converts the tokens to lowercase
DEFINE ANALYZER simple TOKENIZERS blank,class FILTERS lowercase;
DEFINE INDEX ft_title ON book FIELDS title FULLTEXT ANALYZER simple BM25 HIGHLIGHTS;
REBUILD INDEX uniq_isbn ON book;
REBUILD INDEX idx_author ON book;
REBUILD INDEX ft_title ON book;
// Check that the index has been created
INFO FOR TABLE book;
//Checks whether the term RUST IS found in a full-text indexed field.
SELECT * FROM book WHERE title @@ 'Rust';
```

### Using if exists clause

The following queries show an example of how to rebuild resources using the `IF EXISTS` clause, which will only rebuild the resource if it exists.

```surql
REBUILD INDEX IF EXISTS uniq_isbn ON book;
```

## When to rebuild after an upgrade

An upgrade to a new release does not rewrite existing indexes. Most keep working as they are, and a few need `REBUILD INDEX` to repair results or to use a faster query plan. Rebuild them once every node in a cluster runs the new version. The indexes that apply to the move from `3.x` to `4.0` are listed in [Upgrading from 3.x to 4.0](/docs/operate/upgrading/3x-to-4x.md#indexes-to-rebuild).

## Rebuilding a large index

Run `REBUILD INDEX` as its own statement for an index with many records, not inside `BEGIN ... COMMIT`, a block or a function. From SurrealDB 4.0, a standalone `REBUILD INDEX` commits the change to the index definition first and then waits for the build. A build that outlasts the query timeout keeps running, and the statement reports that the timeout was exceeded rather than that the rebuild failed. Check progress with [`INFO FOR INDEX`](/docs/reference/query-language/statements/info.md#index-information) and leave the build to finish.

A rebuild inside a transaction still waits within that transaction, and on a large index the final commit can fail with a transaction conflict.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/relate

# RELATE

The RELATE statement can be used to generate graph edges between two records in the database.

The `RELATE` statement can be used to generate graph edges between two records in the database. This allows you to traverse related records efficiently without needing to pull data from multiple tables and merge that data together using SQL JOINs.

For what `RELATE` does when an edge with the same ID already exists, and how it compares with the other statements that write records, see [Writing records that may already exist](/docs/reference/query-language/statements/overview.md#writing-records-that-may-already-exist).

Edges created using the RELATE statement are nearly identical to tables created using other statements, and can contain data. The key differences are that:

- Edge tables are deleted once there are no existing relationships left.
- Edge tables have two required fields `in` and `out`, which specify the directions of the relationships. These cannot be modified in schema declarations except to specify that they must be of a certain record type or to [add assertions](/docs/reference/query-language/statements/define/field.md#asserting-rules-on-fields).

Otherwise, edge tables behave like normal tables in terms of [updating](/docs/reference/query-language/statements/update.md), [defining a schema](/docs/reference/query-language/statements/define/table.md) or [indexes](/docs/reference/query-language/statements/define/indexes.md).

Another option for connecting data is using [record links](/docs/reference/query-language/language-primitives/record-links.md). Record links consist of a field with record IDs that serve as unidirectional links by default, or bidirectional links if reference tracking is used. The key differences are that graph relations have the following benefits over record links:

- Graph relations are kept in a separate table as opposed to a field inside a record.
- Graph relations allow you to store data alongside the relationship.
- Graph relations have their own syntax that makes it easy to build and visualise edge queries.

Graph relations offer built-in bidirectional querying and referential integrity. Record links also offer these two advantages if they are defined inside a [`DEFINE FIELD`](/docs/reference/query-language/statements/define/field.md) statement using the `REFERENCES` clause. For more information, see [the page on record references](/docs/reference/query-language/language-primitives/record-references.md).

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
RELATE [ ONLY ] [ OR UPDATE ] @from_record -> @table | @edge_record -> @to_record
	[ CONTENT @value
	  | SET @field = @value ...
	]
	[ RETURN NONE | RETURN BEFORE | RETURN AFTER | RETURN DIFF
	  | RETURN @statement_param, ... | RETURN VALUE @statement_param ]
	[ TIMEOUT @duration ]
;
```

> [!NOTE]
> `RELATE` will create a relation regardless of whether the records to relate to exist or not. As such, it is advisable to [create the records](/docs/reference/query-language/statements/create.md) you want to relate to before using `RELATE`, or to at least ensure that they exist before making a query on the relation. If the records to relate to don't exist, a query on the relation will still work but will return an empty array. To override this behaviour and return an error if no records exist to relate, you can use a [`DEFINE TABLE`](/docs/reference/query-language/statements/define/table.md) statement that includes the `ENFORCED` keyword.

> [!NOTE]
> If a `RELATE` on the create path sets `id` to an **existing** edge record (for example `RELATE a->edge->b SET id = edge:existing`), SurrealDB returns a record-exists error instead of overwriting that edge. Use [`UPDATE`](/docs/reference/query-language/statements/update.md) when you intend to modify an existing relation.

## Example usage

### Basic usage

The following query shows the basic structure of the `RELATE` statement, which creates a relationship between a record in the `person` table and a record in the `article` table.

```surql
CREATE person:aristotle, article:on_sleep_and_sleeplessness;
RELATE person:aristotle->wrote->article:on_sleep_and_sleeplessness;
```

```surql title="Output"
[
	{
		id: wrote:bpbrj5kd7smu3ahlf55r,
		in: person:aristotle,
		out: article:on_sleep_and_sleeplessness
	}
]
```

There is no relationship information stored in either the `person` or `article` table.

```surql
-- Setup from the example above
CREATE person:aristotle, article:on_sleep_and_sleeplessness;

SELECT * FROM person, article;
```

```surql title="Output"
[
	{
		id: person:aristotle
	},
	{
		id: article:on_sleep_and_sleeplessness
	}
]
```

Instead, an edge table (in this case a table called `wrote`) stores the relationship information.

```surql
-- Setup from the example above
CREATE person:aristotle, article:on_sleep_and_sleeplessness;
RELATE person:aristotle->wrote->article:on_sleep_and_sleeplessness;

SELECT * FROM wrote;
```

The structure `in -> id -> out` mirrors the record IDs from the `RELATE` statement, with the addition of the automatically generated ID for the `wrote` edge table.

```surql title="Output"
[
	{
		id: wrote:bpbrj5kd7smu3ahlf55r,
		in: person:aristotle,
		out: article:on_sleep_and_sleeplessness
	}
]
```

The same structure can be used in a `SELECT` query, as well as directly from a record ID.

```surql
-- Setup from the example above
CREATE person:aristotle, article:on_sleep_and_sleeplessness;
RELATE person:aristotle->wrote->article:on_sleep_and_sleeplessness;

-- Aristotle's id and the articles he wrote
SELECT id, ->wrote->article FROM person:aristotle;
-- Every `person`'s id and written articles
-- Same output as above as the database has a single `person` record
SELECT id, ->wrote->article FROM person;
-- Directly follow the path from Aristotle to his written articles
RETURN person:aristotle->wrote->article;
```

```surql title="Output"
-------- Query --------

[
	{
		"->wrote": {
			"->article": [
				article:on_sleep_and_sleeplessness
			]
		},
		id: person:aristotle
	}
]

-------- Query --------

[
	article:on_sleep_and_sleeplessness
]
```

By default, the edge table gets created as a schemaless table when you execute the `RELATE` statement. You can make the table schemafull by [defining a schema](/docs/reference/query-language/statements/define/table.md).

### Unique relationships

A common use case is to make sure only unique relationships get created. You can do that by [defining an index](/docs/reference/query-language/statements/define/indexes.md).

```surql
DEFINE INDEX unique_relationships
    ON TABLE wrote
    FIELDS in, out UNIQUE;
```

Relating the same two records a second time then fails:

```text title="Error output"
Database index `unique_relationships` already contains [person:aristotle, article:on_sleep_and_sleeplessness], with record `wrote:usdo1cyf3dbt0sk0iawm`
```

For a relationship with no direction, such as `friends_with`, where `a->b` and `b->a` are the same relationship, see [Bidirectional relation querying](#bidirectional-relation-querying), which builds a unique key from the two records in sorted order.

As edge tables are bidirectional by default, there is nothing stopping a query like the following in which an article writes a person instead of the other way around.

```surql
RELATE article:on_sleep_and_sleeplessness->wrote->person:aristotle;
```

To enforce unidirectional relationships, you can restrict the type definition using a [`DEFINE FIELD`](/docs/reference/query-language/statements/define/field.md) definition.

```surql
DEFINE FIELD in  ON TABLE wrote TYPE record<person>;
DEFINE FIELD out ON TABLE wrote TYPE record<article>;
```

### Always two records there are - no more, no less

An edge table will always include exactly one record for the `in` field and one record for the `out` field.

Knowing this, one would assume that a `RELATE` statement like the following would fail as it seems to be attempting to insert two `cat` records at the `in` field.

```surql
CREATE cat:mr_meow, cat:mrs_meow, cat:kitten;
RELATE [cat:mr_meow, cat:mrs_meow]->parent_of->cat:kitten;
```

However, the query works just fine. Instead of trying to create a single `parent_of` graph edge, it will create one for each record in the first array: one between `cat:mr_meow` and `cat:kitten`, and another between `cat:mrs_meow` and `cat:kitten`.

```surql title="Output"
[
	{
		id: parent_of:uahudi4qr68k640fcjbg,
		in: cat:mr_meow,
		out: cat:kitten
	},
	{
		id: parent_of:hi79yfazjppv8b3kyi36,
		in: cat:mrs_meow,
		out: cat:kitten
	}
]
```

Similarly, a `RELATE` statement that involves two arrays will return a number of graph edges equal to their product (2 * 2 in this case):

```surql
CREATE cat:kitten2;
RELATE [cat:mr_meow, cat:mrs_meow]->parent_of->[cat:kitten, cat:kitten2];
```

```surql title="Output"
[
	{
		id: parent_of:ysbab20nv5568ogba6ns,
		in: cat:mr_meow,
		out: cat:kitten
	},
	{
		id: parent_of:0ltm6xr94pkblyxf0m6c,
		in: cat:mr_meow,
		out: cat:kitten2
	},
	{
		id: parent_of:71cfl0nvj5frve0r1npv,
		in: cat:mrs_meow,
		out: cat:kitten
	},
	{
		id: parent_of:4gbid7nzo6cwr1t8k090,
		in: cat:mrs_meow,
		out: cat:kitten2
	}
]
```

### Relating a record to an edge

An edge is a record, so it can be the `in` or `out` of another edge. This suits an edge that describes something other records need to point at. In the example below, an `offer` edge holds the price at which a shop sells a material, and a `uses` edge records how much of that offer a project used:

```surql
CREATE shop:hardware, material:timber, project:shed;

-- offer:one is an edge
RELATE shop:hardware->offer:one->material:timber SET price = 12;
-- Relate that edge to another edge
RELATE project:shed->uses->offer:one SET quantity = 10;

SELECT
	->uses->offer.{ price, shop: in, material: out } AS offers,
	math::sum(->uses.map(|$u| $u.quantity * $u.out.price)) AS cost
FROM project:shed;
```

```surql title="Output"
[
	{
		cost: 120,
		offers: [
			{ material: material:timber, price: 12, shop: shop:hardware }
		]
	}
]
```

Traversals continue through the edge in both directions, so `->uses->offer->material` reaches the material from the project, and `offer:one<-uses<-project` reaches the projects from the offer. A `TYPE RELATION` table can name an edge table as its endpoint, as in `DEFINE TABLE uses TYPE RELATION IN project OUT offer`.

Deletes cascade through both levels. Deleting `shop:hardware` deletes the `offer:one` edge, because one of its ends no longer exists, and that deletes every `uses` edge that points to the offer.

## Adding data using `SET` and `CONTENT`

Graph edges are standalone tables that can hold other fields besides the default `in`, `out`, and `id`. These can be added during a `RELATE` statement or during an `UPDATE` in the same manner as any other SurrealDB table.

There are two ways to add record data in the `RELATE` statement. Both of these queries will produce the same result. Use `CONTENT` to pass the record data as a single object, and `SET` to assign or compute each field on its own line.

```surql
RELATE person:l19zjikkw1p1h9o6ixrg->wrote->article:8nkk6uj4yprt49z7y3zm
	CONTENT {
		metadata: {
			time_written: time::now(),
			location: "Tallinn"
		}
	};

RELATE person:l19zjikkw1p1h9o6ixrg->wrote->article:8nkk6uj4yprt49z7y3zm
    SET 
		metadata.time_written = time::now(),
		metadata.location = "Tallinn";
```

```surql title="Output"
[
	{
		id: wrote:rva8hentypdu8lcgwjmf,
		in: person:l19zjikkw1p1h9o6ixrg,
		metadata: {
			location: 'Tallinn',
			time_written: d'2024-11-26T01:52:01.169Z'
		},
		out: article:8nkk6uj4yprt49z7y3zm
	}
]
```

Here is an example of the graph edge being updated in the same way as any other SurrealDB record:

```surql
-- Setup from the example above
RELATE person:l19zjikkw1p1h9o6ixrg->wrote->article:8nkk6uj4yprt49z7y3zm
	CONTENT {
		metadata: {
			time_written: time::now(),
			location: "Tallinn"
		}
	};

-- Add a small synopsis composed of the table name and article ID
UPDATE wrote SET
    metadata.description = record::tb(out) + ' written by ' + <string>in;
```

```surql title="Output"
[
	{
		id: wrote:k9d8ynbfxgb8jqjv2ob5,
		in: person:l19zjikkw1p1h9o6ixrg,
		metadata: {
			description: 'article written by person:l19zjikkw1p1h9o6ixrg',
			location: 'Tallinn',
			time_written: d'2024-11-26T01:53:51.350Z'
		},
		out: article:8nkk6uj4yprt49z7y3zm
	}
]
```

## Passing variables in `CONTENT` and `SET`

You can also pass variables in the `CONTENT` block. This is useful when you want to pass a variable that is not a record ID.

```surql
LET $time = time::now();
RELATE person:l19zjikkw1p1h9o6ixrg->wrote->article:8nkk6uj4yprt49z7y3zm
    CONTENT {
        time: {
            written: $time
        }
    };
```

```surql title="Example output"
[
	{
		id: wrote:ctwsll49k37a7rmqz9rr,
		in: person:l19zjikkw1p1h9o6ixrg,
		out: article:8nkk6uj4yprt49z7y3zm,
		time: {
			written: d'2021-09-29T14:00:00Z'
		}
	}
]
```

Below is an example of how you can pass a variable in the `SET` block:

```surql
LET $time = time::now();

RELATE person:l19zjikkw1p1h9o6ixrg->wrote->article:8nkk6uj4yprt49z7y3zm
    SET time.written = $time;
```

```surql title="Example output"
[
	{
		id: wrote:ctwsll49k37a7rmqz9rr,
		in: person:l19zjikkw1p1h9o6ixrg,
		out: article:8nkk6uj4yprt49z7y3zm,
		time: {
			written: d'2021-09-29T14:00:00Z'
		}
	}
]
```

## Creating a single relation with the `ONLY` keyword

Using the ONLY keyword returns just an object for the relation in question, instead of an array with a single object.

```surql
RELATE ONLY person:l19zjikkw1p1h9o6ixrg->wrote->article:8nkk6uj4yprt49z7y3zm;
```

```surql title="Output"
{
	id: wrote:k9f1rqn3oikolr1560u3,
	in: person:l19zjikkw1p1h9o6ixrg,
	out: article:8nkk6uj4yprt49z7y3zm
}
```

## Using [`LET`](/docs/reference/query-language/statements/let.md) parameters in RELATE statements

You can also use [parameters](/docs/reference/query-language/language-primitives/parameters.md) to specify the record IDs.

```surql
-- Setup from the example above
CREATE person:aristotle, article:on_sleep_and_sleeplessness;

-- These two statements store the result of the subquery in a parameter
-- The subquery returns an array of IDs
LET $person =  SELECT VALUE id FROM person;
LET $article = SELECT VALUE id FROM article;

-- This statement creates a relationship record for every combination of Record IDs
-- Such that if we have 10 records each in the person and article table
-- We get 100 records in the wrote edge table (10*10 = 100)
-- In this case it would mean that each article would have 10 authors
RELATE $person->wrote->$article SET time.written = time::now();
```

### Expressions at the ends of a relation

A record ID, an array of record IDs and a parameter can stand at either end of a `RELATE` as they are. Any other expression has to be wrapped in parentheses, which includes a field path, a function call and a subquery:

| Expression | Without parentheses | With parentheses |
| --- | --- | --- |
| `person:ann`, `[person:ann, person:bob]`, `$person` | Works | Works |
| A field path, such as `$after.from` | Parse error: ``Unexpected token `.`, expected a relation arrow`` | `($after.from)` |
| A function call, such as `type::record("person", "ann")` | Parse error: ``Unexpected token `::`, expected :`` | `(type::record("person", "ann"))` |
| A subquery | Parse error, with a message that points at the end of the statement | `(SELECT VALUE id FROM person WHERE name = "Ann")` |

The edge table can be an expression in parentheses as well, such as `->(type::table("knows"))->`.

This comes up most often in an [event](/docs/reference/query-language/statements/define/event.md), which builds a relation from the fields of the record that triggered it. Where those fields hold the keys of the records rather than record IDs, [`type::record()`](/docs/reference/query-language/functions/database-functions/type.md#typerecord) turns them into record IDs:

```surql
DEFINE EVENT follow_made ON follow_request WHEN $event = "CREATE" THEN {
	RELATE (type::record("member", $after.from))->follows->(type::record("member", $after.to))
		SET since = time::now();
};

CREATE member:ann, member:bob;
CREATE follow_request SET from = "ann", to = "bob";

SELECT in, out FROM follows;
```

```surql title="Output"
[
	{
		in: member:ann,
		out: member:bob
	}
]
```

[`INSERT RELATION`](/docs/reference/query-language/statements/insert.md#insert-relation-tables) needs no parentheses, because `in` and `out` are ordinary fields of the object it inserts:

```surql
INSERT RELATION INTO follows {
	in: type::record("member", $after.from),
	out: type::record("member", $after.to)
};
```

## Modifying output with the [`RETURN`](/docs/reference/query-language/statements/return.md) clause

By default, the relate statement returns the record value once the changes have been made. To change the return value of each record, specify a RETURN clause, specifying either `NONE`, `BEFORE`, `AFTER`, `DIFF`, or a comma-separated list of specific fields to return.

```surql
-- Don't return any result
RELATE person:l19zjikkw1p1h9o6ixrg->wrote->article:8nkk6uj4yprt49z7y3zm
    SET time.written = time::now()
    RETURN NONE;

-- Return the changeset diff
RELATE person:l19zjikkw1p1h9o6ixrg->wrote->article:8nkk6uj4yprt49z7y3zm
    SET time.written = time::now()
    RETURN DIFF;

-- Return the record before changes were applied
RELATE person:l19zjikkw1p1h9o6ixrg->wrote->article:8nkk6uj4yprt49z7y3zm
    SET time.written = time::now()
    RETURN BEFORE;

-- Return the record after changes were applied (the default)
RELATE person:l19zjikkw1p1h9o6ixrg->wrote->article:8nkk6uj4yprt49z7y3zm
    SET time.written = time::now()
    RETURN AFTER;

-- Return a specific field only from the updated records
RELATE person:l19zjikkw1p1h9o6ixrg->wrote->article:8nkk6uj4yprt49z7y3zm
    SET time.written = time::now()
    RETURN time;

-- Return only the value of a specific field without the field name
RELATE person:l19zjikkw1p1h9o6ixrg->wrote->article:8nkk6uj4yprt49z7y3zm
    SET time.written = time::now()
    RETURN VALUE time;
```

## Using the `TIMEOUT` clause

Adding the `TIMEOUT` keyword to specify a timeout duration for the statement can be useful when processing a large result set with many interconnected records. If the statement continues beyond this duration, then the transaction will fail, and the statement will return an error.

```surql
CREATE person:one, person:two, person:three;
RELATE person:one->knows->person:two;
RELATE person:two->knows->person:three SET influencer = true;

-- Cancel this conditional filtering based on graph edge properties
-- if not finished within 5 seconds
SELECT * FROM person
  WHERE ->knows->person->(knows
  WHERE influencer = true) TIMEOUT 5s;
```

Using a `TIMEOUT` is particularly useful when experimenting with complex queries with an extent that is difficult to imagine, especially if the query [is recursive](#recursive-graph-queries).

## Deleting graph edges

SurrealQL has no `UNRELATE` statement. An edge is a record in its edge table, so removing a relationship means deleting that record with the [`DELETE` statement](/docs/reference/query-language/statements/delete.md).

For example the graph edge below:

```surql
RELATE person:tobie->bought->product:iphone;
```

```surql title="Output"
[
	{
		id: bought:ctwsll49k37a7rmqz9rr,
		in: person:tobie,
		out: product:iphone
	}
]
```

Can be deleted by:

```surql
DELETE person:tobie->bought WHERE out=product:iphone RETURN BEFORE;
```

As mentioned above, a graph edge will also automatically be deleted if it is no longer connected to a record at both `in` and `out`.

```surql
-- Create three people
CREATE person:one, person:two, person:three;

-- And a love triangle involving them all
RELATE person:one  ->likes->person:two;
RELATE person:two  ->likes->person:three;
RELATE person:three->likes->person:one;

-- Person two moves to Venus permanently, so delete
DELETE person:two;

-- Only one `likes` relationship is left
SELECT * FROM likes;
```

```surql title="Output"
[
	{
		id: likes:55szjin5yfqwl4sbmy1f,
		in: person:three,
		out: person:one
	}
]
```

## Using RELATE on non-existent records

As mentioned at the top of the page, `RELATE` can be used for records that do not yet exist. While this behaviour can be overridden by using the `ENFORCED` keyword, it can be useful in certain situations.

For example, the `VALUE` clause inside a [`DEFINE FIELD`](/docs/reference/query-language/statements/define/field.md) statement is calculated every time a record is altered (that is, every time it is created or updated). If this value depends on a graph edge, creating the record first will cause `VALUE` to calculate it based on a nonexistent path.

In the following example, a `house` table has a field called `has_road_access` that depends on whether any `->has_road` paths return an output that is not empty. Meanwhile, the city has a new road under construction but no houses are present and their details have not been set yet.

```surql
-- Returns true if $this->has_road path is not empty
DEFINE FIELD has_road_access ON TABLE house VALUE !!$this->has_road->road;
CREATE road SET name = "Dalhurst Way", length = 10.5;
```

As the addresses of the upcoming houses have been decided, the `->has_road` path can be set ahead of time by giving the `house` records an ID based on their exact address.

```surql
-- Setup from the example above
-- Returns true if $this->has_road path is not empty
DEFINE FIELD has_road_access ON TABLE house VALUE !!$this->has_road->road;
CREATE road SET name = "Dalhurst Way", length = 10.5;

LET $road = SELECT * FROM ONLY road WHERE name = "Dalhurst Way" LIMIT 1;
RELATE [
    house:["Dalhurst Way", 218],
    house:["Dalhurst Way", 222],
    house:["Dalhurst Way", 226],
]->has_road->$road;
```

Later on, two new houses are completed in the city and registered in the database. As the path to `house:["Dalhurst Way", 218]` has already been set up, the `has_road_access` field will evaluate to `true`, while the other house in the middle of nowhere will evaluate to `false`.

```surql
CREATE house:["Dalhurst Way", 218] SET floors = 2, bedrooms = 5;
CREATE house:["Middle of nowhere", 0] SET floors = 4, bedrooms = 12;
```

```surql
-------- Query --------

[
	{
		bedrooms: 5,
		floors: 2,
		id: house:[
			'Dalhurst Way',
			218
		],
		street: []
	}
]

-------- Query --------

[
	{
		bedrooms: 12,
		floors: 4,
		id: house:[
			'Middle of nowhere',
			0
		],
		street: []
	}
]
```

## Handling duplicate edge record IDs

_(since v3.1.5)_

You can supply the edge record ID directly in the `RELATE` path instead of letting SurrealDB generate one. This is useful when the ID should act like a built-in unique key for the relationship, for example a composite of the `in` and `out` records:

```surql
RELATE person:one->likes:[person:one, post:one]->post:one
  SET liked_at = time::now();

RELATE person:one->likes:[person:one, post:one]->post:one
  SET liked_at = time::now();
```

As of SurrealDB 3.1.5, redoing a `RELATE` statement on an existing ID will update the edge, but emit a warning. This will become a hard error in a later version of SurrealDB.

To specifically opt in to update semantics on an existing edge and not emit a warning, you can add `OR UPDATE` after `RELATE`.

```surql
RELATE person:one->likes:[person:one, post:one]->post:one
  SET liked_at = time::now();

-- Has `OR UPDATE`: will not emit a warning
RELATE OR UPDATE person:one->likes:[person:one, post:one]->post:one
  SET liked_at = time::now();
```

If you prefer a hard error at this point, [`INSERT RELATION`](/docs/reference/query-language/statements/insert.md#insert-relation-tables) can be used:

```surql
INSERT RELATION INTO likes {
  in: person:two,
  out: post:one,
  id: [person:two, post:one]
};

-- Returns an error
INSERT RELATION INTO likes {
  in: person:two,
  out: post:one,
  id: [person:two, post:one]
};
//- 'Database record `likes:[person:two, post:one]` already exists'
```

## Querying graphs

### Different ways to reach similar results

For the questions below, each of the queries will give you largely the same answer. Note that whether `->` and `<-` are parsed as `in` or `out` depends on their direction in relation to the graph edge `wrote`. An arrow pointing towards `wrote` corresponds to `in`, and vice versa.

The following examples show how to make similar queries in a number of different ways, in the context of a database with one person who wrote two articles.

```surql
CREATE 
	person:aristotle,
	article:on_sleep_and_sleeplessness,
	article:on_dreams;
RELATE person:aristotle->wrote->[
		article:on_sleep_and_sleeplessness,
		article:on_dreams
	]
	-- Written sometime around the year 330 BC
	SET time_written = d"-0330-01-01";
```

Who wrote the articles?

```surql
-- Setup from the example above
CREATE 
	person:aristotle,
	article:on_sleep_and_sleeplessness,
	article:on_dreams;
RELATE person:aristotle->wrote->[
		article:on_sleep_and_sleeplessness,
		article:on_dreams
	]
	-- Written sometime around the year 330 BC
	SET time_written = d"-0330-01-01";

-- All queries lead to `person:artistotle` twice,
-- via different paths and thus different field names
-- and/or structure

-- Directly from the `wrote` table
SELECT in FROM wrote;

-- From a single `person` record
SELECT ->wrote.in FROM person;
SELECT ->wrote<-person FROM person;

-- From two `article` records
SELECT <-wrote.in FROM article;
SELECT <-wrote<-person FROM article;
```

Which articles did the person write?

```surql
-- Setup from the example above
CREATE 
	person:aristotle,
	article:on_sleep_and_sleeplessness,
	article:on_dreams;
RELATE person:aristotle->wrote->[
		article:on_sleep_and_sleeplessness,
		article:on_dreams
	]
	-- Written sometime around the year 330 BC
	SET time_written = d"-0330-01-01";

SELECT out FROM wrote;

SELECT ->wrote.out FROM person;
SELECT ->wrote->article FROM person;

SELECT <-wrote.out FROM article;
SELECT <-wrote->article FROM article;
```

When was the article written?

```surql
-- Setup from the example above
CREATE 
	person:aristotle,
	article:on_sleep_and_sleeplessness,
	article:on_dreams;
RELATE person:aristotle->wrote->[
		article:on_sleep_and_sleeplessness,
		article:on_dreams
	]
	-- Written sometime around the year 330 BC
	SET time_written = d"-0330-01-01";

SELECT time_written FROM wrote;
SELECT ->wrote.time_written as time_written FROM person;
SELECT <-wrote.time_written as time_written FROM article;
```

### Parsing graph queries

For a more complicated query like the one below you can use a simple rule of thumb:
Place the subject in front of the graph selection, then read it backward.

```surql notest
-- This query
SELECT ->purchased->product<-purchased<-person->purchased->product
  FROM person:tobie

-- Then becomes
person:tobie->purchased->product<-purchased<-person->purchased->product
  SELECT
```

Reading this backwards then makes more sense:

> Select every product that was purchased by a person who purchased a product that was also purchased by person Tobie.

Alternatively, you can break it down into steps over multiple lines.

```surql
-- Starting with Tobie
person:tobie
-- move on to his purchased products
->purchased->product
-- that were also purchased by persons...
<-purchased<-person
-- what are all of those persons' purchased products?
->purchased->product
```

Putting it all together it would be: based on all the products Tobie purchased, which person also purchased those products and what did they purchase? This sort of query could be used on a social network site to recommend to the user `person:tobie` a list of people that have similar interests.

### Using parentheses to refine graph query logic

Parentheses can be added at any step of a graph query to refine the logic, such as filtering relations based on specific conditions using the `WHERE` clause.

For example, suppose we want to limit the query to only take recent purchases into account. We can filter `purchased` graph edge to only include purchases made in last 3 weeks:

```surql
-- Setup
CREATE person:tobie, person:jaime, product:iphone, product:case;
RELATE person:tobie->purchased->product:iphone SET created_at = time::now();
RELATE person:jaime->purchased->[product:iphone, product:case]
	SET created_at = time::now();

-- Select products purchased by people in the last 3 weeks who have purchased the same products that tobie purchased
SELECT 
	->purchased->product
	<-purchased<-person->(purchased WHERE created_at > time::now() - 3w)
	->product
FROM person:tobie;
```

If the `purchased` graph table can lead to both a `product` or a `subscription`, they can both be added to the query.

```surql
-- Setup
CREATE person:tobie, person:jaime, product:iphone, product:case,
	subscription:music;
RELATE person:tobie->purchased->product:iphone SET created_at = time::now();
RELATE person:jaime->purchased->[product:iphone, product:case]
	SET created_at = time::now();
RELATE person:jaime->purchased->subscription:music SET created_at = time::now();

SELECT 
	->purchased->(product, subscription)
	<-purchased<-person
	->purchased->(product, subscription)
FROM person:tobie;
```

The `?` wildcard operator can also be used to search for any and all linked records. The following query will allow purchased `product`, `subscription`, `insurance`, or any other linked records to show up.

```surql
-- Setup
CREATE person:tobie, person:jaime, product:iphone, product:case,
	subscription:music;
RELATE person:tobie->purchased->product:iphone SET created_at = time::now();
RELATE person:jaime->purchased->[product:iphone, product:case]
	SET created_at = time::now();
RELATE person:jaime->purchased->subscription:music SET created_at = time::now();

SELECT 
	->purchased->(?)
	<-purchased<-person
	->purchased->(?)
FROM person:tobie;
```

The `?` operator on its own can thus be used to see all of the relations that a record has.

```surql
CREATE person:hermann_hesse, person:abigail, city:calw, book:demian;
RELATE person:hermann_hesse->wrote->book:demian SET written_in = d'1919-01-01';
RELATE person:hermann_hesse->born_in->city:calw;
RELATE person:abigail->likes->person:hermann_hesse;

SELECT 
	-- all tables in which the record is at `in`
    ->(?).* AS what_hesse_did,
	-- all tables in which the record is at `out`
    <-(?).* AS what_others_did_to_hesse
FROM person:hermann_hesse;
```

```surql title="Output"
[
	{
		what_hesse_did: [
			{
				id: born_in:k3adylof24a2r5kio8l5,
				in: person:hermann_hesse,
				out: city:calw
			},
			{
				id: wrote:ncbo9w0d8t3xd7lvl4dx,
				in: person:hermann_hesse,
				out: book:demian,
				written_in: d'1919-01-01T00:00:00Z'
			}
		],
		what_others_did_to_hesse: [
			{
				id: likes:6gubmldm14gzasoyypay,
				in: person:abigail,
				out: person:hermann_hesse
			}
		]
	}
]
```

The `?` operator can also be used to find all the relations between one record and another. To do this, use the [`<-> operator`](#bidirectional-relation-querying) to see all relations in which the record ID in question is either at the `in` or the `out` of the graph edge. Follow this with `(?)` to avoid filtering by graph table name, then use a [`WHERE`](/docs/reference/query-language/language-primitives/data-types/arrays.md#mapping-and-filtering-on-arrays) filter on the output (an array of record IDs) to see if the record ID is present in either the `in` or the `out` field of the graph edge.

A small example of this using some of the relations between Anakin Skywalker (Darth Vader), Palpatine (the Emperor), and Luke Skywalker:

```surql
CREATE person:anakin_skywalker, person:luke_skywalker, person:the_emperor;
RELATE person:anakin_skywalker->served->person:the_emperor;
RELATE person:anakin_skywalker->attacked->person:the_emperor SET won = true;
RELATE person:the_emperor->attacked->person:luke_skywalker SET won = false;
RELATE person:luke_skywalker->son_of->person:anakin_skywalker;
RELATE person:the_emperor->fooled->person:anakin_skywalker SET date = "19 BBY";

-- As a SELECT statement
SELECT VALUE <->(?)[WHERE person:the_emperor IN [in, out]]
  FROM ONLY person:anakin_skywalker;
SELECT VALUE <->(?)[WHERE person:luke_skywalker IN [in, out]]
  FROM ONLY person:anakin_skywalker;

-- Or returned directly from the record ID
person:anakin_skywalker<->(?)[WHERE person:the_emperor IN [in, out]];
person:anakin_skywalker<->(?)[WHERE person:luke_skywalker IN [in, out]];
```

```surql title="Example output"
-------- Anakin and Emperor relations --------

[
	fooled:irm2w6jvd1dmppjr7kh2,
	attacked:r8b4z5yr627wy9i73jkh,
	served:30oyjvv5uutnj255w4oy
]

-------- Anakin and Luke relations --------

[
	son_of:h8oosl7s27n21kh3c2iq
]
```

Parentheses can be used at each point of a graph query. The example below includes `person` records (authors) connected to `book` records by the `wrote` table. As both the `person` and `book` tables have fields that can be useful when filtering, they can be isolated with parentheses at this point of the graph query in order to filter using the `WHERE` clause.

```surql
CREATE person:j_r_r_tolkien SET
	name = "J.R.R. Tolkien",
	born = pd'1891-01-03';
-- Very approximate date of birth
CREATE person:plato SET 
	name = "Plato", 
	born = pd'-0428-06-01';

CREATE book:fotr SET 
	name = "The Fellowship of the Ring";
CREATE book:republic SET 
	name = "The Republic",
	original_name = "Πολιτεία";

RELATE person:j_r_r_tolkien->wrote->book:fotr SET written_at = "North Oxford";
RELATE person:plato->wrote->book:republic SET written_at = "Athens";

SELECT 
	name,
	-- Isolate 'wrote' to use WHERE
	->(wrote WHERE written_at = "Athens")->book.* AS books_written_in_athens
FROM person;

SELECT 
	name, 
	-- Isolate 'book' to use WHERE
	->wrote->(book WHERE "Ring" IN name).* AS books_about_rings
FROM person;
```

```surql title="Output"
-------- Query --------

[
	{
		books_written_in_athens: [],
		name: 'J.R.R. Tolkien'
	},
	{
		books_written_in_athens: [
			{
				id: book:republic,
				name: 'The Republic',
				original_name: 'Πολιτεία'
			}
		],
		name: 'Plato'
	}
]

-------- Query --------

[
	{
		books_about_rings: [
			{
				id: book:fotr,
				name: 'The Fellowship of the Ring'
			}
		],
		name: 'J.R.R. Tolkien'
	},
	{
		books_about_rings: [],
		name: 'Plato'
	}
]
```

[Destructuring](/docs/reference/query-language/language-primitives/idioms.md#destructuring) can also be used to pick and choose which fields to access inside a graph query. The following query will return the same output as above, except that `original_name: 'Πολιτεία'` will no longer show up.

```surql
-- Setup from the example above
CREATE person:j_r_r_tolkien SET
	name = "J.R.R. Tolkien",
	born = pd'1891-01-03';
-- Very approximate date of birth
CREATE person:plato SET 
	name = "Plato", 
	born = pd'-0428-06-01';

CREATE book:fotr SET 
	name = "The Fellowship of the Ring";
CREATE book:republic SET 
	name = "The Republic",
	original_name = "Πολιτεία";

RELATE person:j_r_r_tolkien->wrote->book:fotr SET written_at = "North Oxford";
RELATE person:plato->wrote->book:republic SET written_at = "Athens";

SELECT 
	name, 
	->(wrote WHERE written_at = "Athens")->book.{ name, id } AS books_written_in_athens
FROM person;
```

### Bidirectional relation querying

All of the queries up to now have been clear about what sort of record is found at the `in` and `out` fields: `in` is the record that is doing something, while `out` is the record that has something done to it:

* A `person` who writes an `article`: the person **writes**, the article **is written**.
* A `person` who purchases a `product`: the person **purchases**, the product **is purchased**.

However, sometimes a relation is such that it is impossible to determine which record is located at the `in` part of a graph table, and which is located at the `out` part. This is the case when a relationship is truly bidirectional and equal, such as a friendship, marriage, or sister cities:

```surql
CREATE city:calgary, city:daejeon;
RELATE city:calgary->sister_of->city:daejeon;
```

This relation could just as well have been established with the statement `RELATE city:daejeon->sister_of->city:calgary`.

In such a case, a query on the relationship makes it appear as if one city has a twin city but the other does not.

```surql
-- Setup from the example above
CREATE city:calgary, city:daejeon;
RELATE city:calgary->sister_of->city:daejeon;

SELECT id, ->sister_of->city AS sister_cities FROM city;
```

```surql title="Output"
[
	{
		id: city:calgary,
		sister_cities: [
			city:daejeon
		]
	},
	{
		id: city:daejeon,
		sister_cities: []
	}
]
```

To solve this, we can use the `<->` operator instead of `->`. Using `<->` will access both the `in` and `out` fields, instead of just one.

```surql
-- Setup from the example above
CREATE city:calgary, city:daejeon;
RELATE city:calgary->sister_of->city:daejeon;

SELECT id, <->sister_of<->city AS sister_cities FROM city;
```

This brings up another issue in which a city now appears to be a sister city of itself.

```surql
[
	{
		id: city:calgary,
		sister_cities: [
			city:calgary,
			city:daejeon
		]
	},
	{
		id: city:daejeon,
		sister_cities: [
			city:calgary,
			city:daejeon
		]
	}
]
```

Here we can use the [`array::complement`](/docs/reference/query-language/functions/database-functions/array.md#arraycomplement) function to return only items from one array that are not present in another array.

```surql
-- Setup from the example above
CREATE city:calgary, city:daejeon;
RELATE city:calgary->sister_of->city:daejeon;

SELECT id, array::complement(<->sister_of<->city, [id]) AS sister_cities
  FROM city;
```

```surql title="Output"
[
	{
		id: city:calgary,
		sister_cities: [
			city:daejeon
		]
	},
	{
		id: city:daejeon,
		sister_cities: [
			city:calgary
		]
	}
]
```

Adding a unique key is a good practice for this sort of relation, as it will prevent it from being created twice. This can be done by [defining a field](/docs/reference/query-language/statements/define/field.md) as a unique key based on the ordered record IDs involved, followed by a [`DEFINE INDEX`](/docs/reference/query-language/statements/define/field.md) statement.

```surql
DEFINE FIELD key ON TABLE sister_of VALUE <string>array::sort([in, out]);
DEFINE INDEX only_one_sister_city ON TABLE sister_of FIELDS key UNIQUE;
```

With the index in place, a relation set from one record to the other now cannot be created a second time.

```surql
RELATE city:calgary->sister_of->city:daejeon; -- OK
RELATE city:daejeon->sister_of->city:calgary;
```

```surql title="Output"
"Database index `only_one_sister_city` already contains '[city:calgary, city:daejeon]', with record `sister_of:npab0uoxogmrvpwsvfoa`"
```

### Refining the `in` and `out` fields of a relation

As mentioned above, the `in` and `out` fields of a graph table are mandatory but can be modified to specify their record type or make assertions.

Thus, the following field declarations will work:

```surql
DEFINE FIELD in ON TABLE wrote TYPE record<author>;
DEFINE FIELD out ON TABLE wrote TYPE record<book>;
```

But any attempt to outright redefine the `in` or `out` fields as a different type will be ignored.

```surql
DEFINE FIELD in ON TABLE wrote TYPE string;
DEFINE FIELD out ON TABLE wrote TYPE int;
```

An example of an assertion on one of the fields of a record table for a library which is not yet ready to handle non-English books:

```surql
DEFINE FIELD out
  ON TABLE wrote TYPE record<book> ASSERT $value.language = "English";

CREATE book:demian SET title = "Demian. Die Geschichte von Emil Sinclairs Jugend", language = "German";
CREATE author:hesse SET name = "Hermann Hesse";

RELATE author:hesse->wrote->book:demian;
```

```surql title="Error output"
"Found book:demian for field `out`, with record `wrote:l4xjcgqkgm7vmqqt4iah`, but field must conform to: $value.language = 'English'"
```

### Structure of queries on relations

Using an alias is a common practice in both regular and relation queries in SurrealDB to make output more readable and collapse nested structures. You can create an alias using the `AS` clause.

```surql
CREATE cat:one, cat:two, cat:three;

RELATE cat:one->friends_with->cat:two;
RELATE cat:two->friends_with->cat:three;

SELECT ->friends_with->cat->friends_with->cat FROM cat:one;
-- create an alias for the result using the `AS` clause.
SELECT ->friends_with->cat->friends_with->cat AS friends_of_friends
  FROM cat:one;
```

```surql title="Output"
-- Output without alias
[
	{
		"->friends_with": {
			"->cat": {
				"->friends_with": {
					"->cat": [
						cat:three
					]
				}
			}
		}
	}
]

-- Output with alias
[
	{
		friends_of_friends: [
			cat:three
		]
	}
]
```

However, an alias might not be preferred in a case where you have multiple graph queries that resolve to the fields of a large nested structure. Take the following data for example:

```surql
CREATE country:usa SET name = "USA";
CREATE state:pennsylvania SET population = 12970000;
CREATE state:michigan SET population = 10030000;
CREATE city:philadelphia, city:pittsburgh, city:detroit, city:grand_rapids;

RELATE country:usa->contains->[state:pennsylvania, state:michigan];
RELATE state:pennsylvania->contains->[city:philadelphia, city:pittsburgh];
RELATE state:michigan->contains->[city:detroit, city:grand_rapids];
```

A query on the states and cities of these records using aliases would return the data in a structure remade to fit the aliases declared in the query.

```surql
-- Setup from the example above
CREATE country:usa SET name = "USA";
CREATE state:pennsylvania SET population = 12970000;
CREATE state:michigan SET population = 10030000;
CREATE city:philadelphia, city:pittsburgh, city:detroit, city:grand_rapids;

RELATE country:usa->contains->[state:pennsylvania, state:michigan];
RELATE state:pennsylvania->contains->[city:philadelphia, city:pittsburgh];
RELATE state:michigan->contains->[city:detroit, city:grand_rapids];

SELECT
    name,
    ->contains->state AS states,
    ->contains->state->contains->city AS cities
FROM country:usa;
```

```surql title="Possible output"
[
	{
		cities: [
			city:philadelphia,
			city:pittsburgh,
			city:grand_rapids,
			city:detroit
		],
		name: 'USA',
		states: [
			state:pennsylvania,
			state:michigan
		]
	}
]
```

However, opting to not use an alias will return the original graph structure which makes the levels of depth of the query clearer. In addition, the `population` field is clearly the population for the states.

```surql
-- Setup from the example above
CREATE country:usa SET name = "USA";
CREATE state:pennsylvania SET population = 12970000;
CREATE state:michigan SET population = 10030000;
CREATE city:philadelphia, city:pittsburgh, city:detroit, city:grand_rapids;

RELATE country:usa->contains->[state:pennsylvania, state:michigan];
RELATE state:pennsylvania->contains->[city:philadelphia, city:pittsburgh];
RELATE state:michigan->contains->[city:detroit, city:grand_rapids];

SELECT
    id,
    ->contains->state.id,
    ->contains->state.population,
    ->contains->state->contains->city.id
FROM country:usa;
```

The [destructuring syntax](/docs/reference/query-language/language-primitives/idioms.md#destructuring) can be used to reduce some typing. Here is the same query as the last using destructuring syntax instead of one line for each field.

```surql
-- Setup from the example above
CREATE country:usa SET name = "USA";
CREATE state:pennsylvania SET population = 12970000;
CREATE state:michigan SET population = 10030000;
CREATE city:philadelphia, city:pittsburgh, city:detroit, city:grand_rapids;

RELATE country:usa->contains->[state:pennsylvania, state:michigan];
RELATE state:pennsylvania->contains->[city:philadelphia, city:pittsburgh];
RELATE state:michigan->contains->[city:detroit, city:grand_rapids];

SELECT
    id,
	-- access id and population on a single line
    ->contains->state.{id, population},
    ->contains->state->contains->city.id
FROM country:usa;
```

```surql title="Output"
[
	{
		"->contains": {
			"->state": {
				"->contains": {
					"->city": {
						id: [
							city:philadelphia,
							city:pittsburgh,
							city:grand_rapids,
							city:detroit
						]
					}
				},
				id: [
					state:pennsylvania,
					state:michigan
				],
				population: [
					12970000,
					10030000
				]
			}
		},
		id: country:usa
	}
]
```

As the query that uses aliases does not maintain the original graph structure, adding `population` would require clever renaming such as `->contains->state.population AS state_populations` to make it clear that the numbers represent state and not city populations.

### Multiple graph tables vs. fields

Being able to set fields on graph tables opens up a large variety of custom query methods, one of which is explored here.

Imagine a database that holds detailed information on the relations between NPCs in a game that are made to be as realistic as possible. Two of the characters have a rocky past but finally end up married. During this period, we might have tracked their relationship by adding and removing graph edges between the two of them as they move from a stage of being friends, to dating, to hating each other, to finally ending up married.

```surql
CREATE person:one, person:two;
-- These three relations would end up deleted
RELATE person:one->friends_with->person:two;
RELATE person:one->dating->person:two;
RELATE person:one->hates->person:two;
-- Finally this would be the graph edge connecting the two
RELATE person:one->married->person:two;
```

This works well to track the current state of the relationship, but creating a more general table such as `knows` along with a number of fields can be a better method to track the changing relationship over time. The following shows the relationship between the two `person` records, along with a third record called `person:three` who went to the same school and once dated `person:one`.

```surql
CREATE person:one, person:two, person:three;
RELATE person:one->knows->person:two SET
    has_been_friends = true,
    has_dated = true,
    has_hated = true,
    married_to = true;

RELATE person:one->knows->person:three SET
    same_high_school = true,
    has_dated = true;
```

With these fields in place, a `WHERE` clause inside the arrows does refined searches on relationships of a certain type. The condition sits in parentheses, as part of the path, so it becomes the edge scan's own predicate and the edges that fail it are never followed.

```surql
-- Setup from the example above
CREATE person:one, person:two, person:three;
RELATE person:one->knows->person:two SET
    has_been_friends = true,
    has_dated = true,
    has_hated = true,
    married_to = true;

RELATE person:one->knows->person:three SET
    same_high_school = true,
    has_dated = true;

SELECT 
	->knows->person AS knows,
	->(knows WHERE has_dated)->person AS has_dated,
	->(knows WHERE same_high_school
	  AND has_dated)->person AS dated_and_same_school
 FROM person:one;
```

The same condition can be written in square brackets - `->knows[WHERE has_dated]->person` - but that is the generic [array filter](/docs/reference/query-language/language-primitives/data-types/arrays.md#filtering-and-mapping-with-array-functions) applied after walking every edge. Both return the same records, and on a record with many edges only the parenthesised form stays fast.

```surql title="Output"
[
	{
		dated_and_same_school: [
			person:three
		],
		has_dated: [
			person:two,
			person:three
		],
		knows: [
			person:two,
			person:three
		]
	}
]
```

Because the `WHERE` clause simply checks for [truthiness](/docs/reference/query-language/language-primitives/data-types/values.md#values-and-truthiness) (whether a value is present and not empty), these fields do not necessarily need to be booleans and can even be complex objects.

```surql
RELATE person:one->knows->person:two SET
	same_high_school = false,
    has_been_friends = true,
    has_dated = {
		from: pd'2020-12-25',
		to: pd'2023-12-25'
	},
    has_hated = {
		from: pd'2023-12-25',
		to: pd'2024-03-01'
	},
    married_to = {
		since: pd'2024-03-01'
	};

RELATE person:one->knows->person:three SET
    same_high_school = true,
    has_dated = {
		from: pd'2019-09-10',
		to: pd'2020-12-31'
	};
```

With these objects, a jealous `person:two` could do a check on `person:one` to see how many relationships with `has_dated` have an end time that overlaps with the `has_dated` period of `person:one` and `person:two`.

```surql
-- Setup from the examples above
CREATE person:one, person:two, person:three;
RELATE person:one->knows->person:two SET
	same_high_school = false,
    has_been_friends = true,
    has_dated = {
		from: pd'2020-12-25',
		to: pd'2023-12-25'
	},
    has_hated = {
		from: pd'2023-12-25',
		to: pd'2024-03-01'
	},
    married_to = {
		since: pd'2024-03-01'
	};

RELATE person:one->knows->person:three SET
    same_high_school = true,
    has_dated = {
		from: pd'2019-09-10',
		to: pd'2020-12-31'
	};

SELECT id, ->(knows WHERE same_high_school
  AND has_dated.to > pd'2020-12-25')->person FROM person:one;
```

### Recursive graph queries

Graph edges can also be queried recursively. For a full explanation of this syntax, see the page on [recursive paths](/docs/reference/query-language/language-primitives/idioms.md#recursive-paths).

Take the following example which creates five cities, each of which is connected to the next by some type of road of random length.

```surql
-- Note: 1..6 used to be inclusive until SurrealDB 3.0.0
-- Now creates 1 up to but not including 6
CREATE |city:1..6|;
UPDATE city SET name = <string>id.id() + 'ville';
FOR $pair IN (<array>(1..=5)).windows(2) {
  	LET $city1 = type::record("city", $pair[0]);
    LET $city2 = type::record("city", $pair[1]);
    RELATE $city1->to->$city2 SET 
        type = rand::enum(["train", "road", "bike path"]),
        distance = <int>(rand::float() * 100).ceil()
};
```

While it is possible to manually move three levels down this road network, it involves a good deal of manual typing.

```surql
-- Setup from the example above
-- Note: 1..6 used to be inclusive until SurrealDB 3.0.0
-- Now creates 1 up to but not including 6
CREATE |city:1..6|;
UPDATE city SET name = <string>id.id() + 'ville';
FOR $pair IN (<array>(1..=5)).windows(2) {
  	LET $city1 = type::record("city", $pair[0]);
    LET $city2 = type::record("city", $pair[1]);
    RELATE $city1->to->$city2 SET 
        type = rand::enum(["train", "road", "bike path"]),
        distance = <int>(rand::float() * 100).ceil()
};

SELECT ->to->city->to->city->to->city AS fourth_city FROM city:1;
```

```surql title="Output"
[
	{
		fourth_city: [
			city:4
		]
	}
]
```

This can be replaced by a `@` to refer to the current record, followed by `.{3}` to represent three levels down the `to` graph edge. A level between 1 and 256 can be specified here.

```surql
-- Setup from the example above
-- Note: 1..6 used to be inclusive until SurrealDB 3.0.0
-- Now creates 1 up to but not including 6
CREATE |city:1..6|;
UPDATE city SET name = <string>id.id() + 'ville';
FOR $pair IN (<array>(1..=5)).windows(2) {
  	LET $city1 = type::record("city", $pair[0]);
    LET $city2 = type::record("city", $pair[1]);
    RELATE $city1->to->$city2 SET 
        type = rand::enum(["train", "road", "bike path"]),
        distance = <int>(rand::float() * 100).ceil()
};

SELECT @.{3}->to->city AS fourth_city FROM city:1;
```

A traditional query to show the final road info from `city:1` to the city three stops away would look like this.

```surql
-- Setup from the example above
-- Note: 1..6 used to be inclusive until SurrealDB 3.0.0
-- Now creates 1 up to but not including 6
CREATE |city:1..6|;
UPDATE city SET name = <string>id.id() + 'ville';
FOR $pair IN (<array>(1..=5)).windows(2) {
  	LET $city1 = type::record("city", $pair[0]);
    LET $city2 = type::record("city", $pair[1]);
    RELATE $city1->to->$city2 SET 
        type = rand::enum(["train", "road", "bike path"]),
        distance = <int>(rand::float() * 100).ceil()
};

SELECT ->to->city->to->city->to.* AS third_journey FROM city:1;
```

```surql title="Possible output"
[
	{
		third_journey: [
			{
				distance: 80,
				id: to:sw2pery99jomfhibzfrh,
				in: city:3,
				out: city:4,
				type: 'train'
			}
		]
	}
]
```

To use the same query recursively, wrap the part that must be repeated (`->to->city`) inside parentheses. This will ensure that the `.{2}` part of the query only repeats `->to->city` twice, and not the final `->to.*` portion.

```surql
-- Setup from the example above
-- Note: 1..6 used to be inclusive until SurrealDB 3.0.0
-- Now creates 1 up to but not including 6
CREATE |city:1..6|;
UPDATE city SET name = <string>id.id() + 'ville';
FOR $pair IN (<array>(1..=5)).windows(2) {
  	LET $city1 = type::record("city", $pair[0]);
    LET $city2 = type::record("city", $pair[1]);
    RELATE $city1->to->$city2 SET 
        type = rand::enum(["train", "road", "bike path"]),
        distance = <int>(rand::float() * 100).ceil()
};

SELECT @.{2}(->to->city)->to.* AS third_journey FROM city:1;
```

A range can be added inside the `{}` braces. The following query that uses a range of 1 to 20 will follow the `->to->city` path up to 20 times, but will stop at the 5th and final depth because the next level returns an empty array.

```surql
-- Setup from the example above
-- Note: 1..6 used to be inclusive until SurrealDB 3.0.0
-- Now creates 1 up to but not including 6
CREATE |city:1..6|;
UPDATE city SET name = <string>id.id() + 'ville';
FOR $pair IN (<array>(1..=5)).windows(2) {
  	LET $city1 = type::record("city", $pair[0]);
    LET $city2 = type::record("city", $pair[1]);
    RELATE $city1->to->$city2 SET 
        type = rand::enum(["train", "road", "bike path"]),
        distance = <int>(rand::float() * 100).ceil()
};

city:1.{1..20}->to->city;
```

```surql title="Output"
[
	city:5
]
```

Ranges can be followed with the destructuring operator to collect fields on each depth, returning them in a single response. The following query goes five depths down the `to` graph table, returning each city and road along the way. The `.@` after `->to->city` repeats the destructuring at each city it reaches, so the result is a tree that nests each city inside the one before it.

```surql
-- Setup from the example above
-- Note: 1..6 used to be inclusive until SurrealDB 3.0.0
-- Now creates 1 up to but not including 6
CREATE |city:1..6|;
UPDATE city SET name = <string>id.id() + 'ville';
FOR $pair IN (<array>(1..=5)).windows(2) {
  	LET $city1 = type::record("city", $pair[0]);
    LET $city2 = type::record("city", $pair[1]);
    RELATE $city1->to->$city2 SET 
        type = rand::enum(["train", "road", "bike path"]),
        distance = <int>(rand::float() * 100).ceil()
};

city:1.{1..5}.{
	id,
	next_roads: ->to.*,
	next_cities: ->to->city.@
};
```

```surql title="Possible output"
{
	id: city:1,
	next_cities: [
		{
			id: city:2,
			next_cities: [
				{
					id: city:3,
					next_cities: [
						{
							id: city:4,
							next_cities: [
								{
									id: city:5,
									next_cities: [],
									next_roads: []
								}
							],
							next_roads: [
								{
									distance: 68,
									id: to:iscpuvgwy74ivuj0vcde,
									in: city:4,
									out: city:5,
									type: 'train'
								}
							]
						}
					],
					next_roads: [
						{
							distance: 25,
							id: to:ebymkcrbl4kwc9yeoddj,
							in: city:3,
							out: city:4,
							type: 'road'
						}
					]
				}
			],
			next_roads: [
				{
					distance: 40,
					id: to:6fc02frsd0pa41mtk06c,
					in: city:2,
					out: city:3,
					type: 'train'
				}
			]
		}
	],
	next_roads: [
		{
			distance: 96,
			id: to:yxyy8m7e6u9u62v1jrpg,
			in: city:1,
			out: city:2,
			type: 'road'
		}
	]
}
```

As noted above, a `TIMEOUT` can be set for queries that may be computationally intensive. This is particularly useful when experimenting with recursive queries, which, if care is not taken, can run all the way to the maximum possible depth of 256.

Take the following example with two `person` records that like each other. Following the `likes` edge will run until the query recurses 256 times and gives up.

```surql
CREATE person:one, person:two;
RELATE person:one->likes->person:two;
RELATE person:two->likes->person:one;
-- Open-ended range
person:one.{..}->likes->person;
```

```surql title="Error output"
'Exceeded the idiom recursion limit of 256.'
```

Take the following example in which three `person` records are created, each of which likes the other two `person` records. A query on the `->likes->person` path shows that the number of records doubles each time.

```surql
CREATE |person:1..4|;
FOR $person IN (SELECT * FROM person) {
  LET $others = (SELECT * FROM person WHERE id != $person.id);
    FOR $other IN $others {
        RELATE $person->likes->$other;
    }
};
RETURN [
	person:1.{2}->likes->person,
	person:1.{3}->likes->person,
	person:1.{4}->likes->person
];
```

```surql title="Output"
[
	[
		person:1,
		person:2,
		person:1,
		person:3
	],
	[
		person:3,
		person:2,
		person:1,
		person:3,
		person:3,
		person:2,
		person:1,
		person:2
	],
	[
		person:1,
		person:2,
		person:1,
		person:3,
		person:3,
		person:2,
		person:1,
		person:2,
		person:1,
		person:2,
		person:1,
		person:3,
		person:3,
		person:2,
		person:1,
		person:3
	]
]
```

Since an open-ended range can be specified in a recursive query, this would result in a full 256 attempts to recurse, multiplying the number of results by two each time for a total of 115792089237316195423570985008687907853269984665640564039457584007913129639936 records by the end.

When experimenting with recursive queries, especially open-ended ranges, it is thus recommended to use a timeout.

```surql
-- Setup from the example above
CREATE |person:1..4|;
FOR $person IN (SELECT * FROM person) {
  LET $others = (SELECT * FROM person WHERE id != $person.id);
    FOR $other IN $others {
        RELATE $person->likes->$other;
    }
};

SELECT @.{..}.{ id, likes: ->likes->person.@ } FROM person TIMEOUT 1s;
```

### Graph clauses

The same clauses available to a `SELECT` statement can be used inside a graph query. Take the following relations for example:

```surql
CREATE person:one, person:two, person:three;
RELATE person:one->knows->person:two SET
	friends = true,
    dated = true,
    married_to = true;

RELATE person:one->knows->person:three SET
    dated = true;

RELATE person:two->knows->person:three SET
	friends = true;
```

At the `knows` path, parentheses can be used to insert clauses or an entirely new SELECT statement based on the records turned up at this point. In the following example, the `FROM knows` portion applies to all the records that a `person` knows, not the `knows` table as a whole.

```surql
-- Setup from the example above
CREATE person:one, person:two, person:three;
RELATE person:one->knows->person:two SET
	friends = true,
    dated = true,
    married_to = true;

RELATE person:one->knows->person:three SET
    dated = true;

RELATE person:two->knows->person:three SET
	friends = true;

SELECT 
	id, 
	->(SELECT out.id AS counterpart, !!dated AS dated
	  FROM knows) AS acquaintances
FROM person;
```

```surql title="Output"
[
	{
		acquaintances: [
			{
				counterpart: person:three,
				dated: true
			},
			{
				counterpart: person:two,
				dated: true
			}
		],
		id: person:one
	},
	{
		acquaintances: [],
		id: person:three
	},
	{
		acquaintances: [
			{
				counterpart: person:three,
				dated: false
			}
		],
		id: person:two
	}
]
```

In some cases, the dot or destructuring operator can produce the same output. The following queries are equivalent.

```surql
-- Setup from the example above
CREATE person:one, person:two, person:three;
RELATE person:one->knows->person:two SET
	friends = true,
    dated = true,
    married_to = true;

RELATE person:one->knows->person:three SET
    dated = true;

RELATE person:two->knows->person:three SET
	friends = true;

SELECT ->(SELECT * FROM knows) FROM person:one;
SELECT ->knows.* FROM person:one;
```

```surql title="Output"
[
	{
		"->knows": [
			{
				dated: true,
				id: knows:2tsz3aomelegp060ii7d,
				in: person:one,
				out: person:three
			},
			{
				dated: true,
				friends: true,
				id: knows:g54z9zapdkssxb4p4pjc,
				in: person:one,
				married_to: true,
				out: person:two
			}
		]
	}
]
```

However, clauses available in [`SELECT` statements](/docs/reference/query-language/statements/select.md) such as `WHERE`, `LIMIT`, `GROUP BY`, aliases and so on can be used, making a graph clause the most flexible option.

```surql
-- Setup from the example above
CREATE person:one, person:two, person:three;
RELATE person:one->knows->person:two SET
	friends = true,
    dated = true,
    married_to = true;

RELATE person:one->knows->person:three SET
    dated = true;

RELATE person:two->knows->person:three SET
	friends = true;

SELECT ->(SELECT *, time::now() AS queried_at
  FROM knows LIMIT 1)
  FROM person:one;
```

```surql title="Output"
[
	{
		"->knows": [
			{
				dated: true,
				id: knows:2tsz3aomelegp060ii7d,
				in: person:one,
				out: person:three,
				queried_at: d'2025-01-24T02:16:31.811Z'
			}
		]
	}
]
```

Some other examples of possible graph clauses:

```surql
CREATE |person:1..4|;

RELATE person:1->likes->person:2 SET like_strength = 20, know_in_person = true;
RELATE person:1->likes->person:3 SET like_strength = 5,  know_in_person = false;
RELATE person:2->likes->person:1 SET like_strength = 10, know_in_person = true;
RELATE person:2->likes->person:3 SET like_strength = 12, know_in_person = false;
RELATE person:3->likes->person:1 SET like_strength = 2,  know_in_person = false;
RELATE person:3->likes->person:2 SET like_strength = 9,  know_in_person = false;

SELECT ->likes AS likes FROM person;
SELECT ->(SELECT like_strength FROM likes) AS likes FROM person;
SELECT ->(SELECT like_strength FROM likes
  WHERE like_strength > 10) AS likes FROM person;
SELECT ->(likes WHERE like_strength > 10) AS likes FROM person;
SELECT ->(SELECT like_strength, know_in_person
  FROM likes ORDER BY like_strength DESC) AS likes
  FROM person;
SELECT ->(SELECT count() as count, know_in_person
  FROM likes GROUP BY know_in_person) AS likes
  FROM person;
SELECT ->(likes LIMIT 1) AS likes FROM person;
SELECT ->(likes START 1) AS likes FROM person;
```

The short form `->(likes ...)` takes `WHERE`, `LIMIT` and `START`. Sorting needs the full `SELECT` form, and the path can continue after it to the records at the other end, in the order of the edges:

```surql
CREATE plan:p, workout:a, workout:b, workout:c;
RELATE plan:p->contain->workout:b SET index = 2;
RELATE plan:p->contain->workout:a SET index = 3;
RELATE plan:p->contain->workout:c SET index = 1;

-- Parse error: ORDER BY needs the SELECT form
-- SELECT VALUE ->(contain ORDER BY index)->workout FROM ONLY plan:p;

SELECT VALUE ->(SELECT * FROM contain ORDER BY index)->workout FROM ONLY plan:p;
```

```surql title="Output"
[workout:c, workout:b, workout:a]
```

Multiple graph tables can be selected by separating each table with a comma, in the same way as in any other `SELECT` statement. In addition, all tables can be selected by using `?` as a wildcard operator.

```surql
CREATE person:one SET name = "Þor";
CREATE dog:one SET name = "Fenrir";
CREATE cat:one SET name = "Jólakötturinn";
RELATE person:one->feeds->cat:one SET at = time::now();
RELATE dog:one->plays_with->cat:one SET at = time::now();

-- Select from both 'feeds' and 'plays_with'
SELECT <-(SELECT * FROM feeds, plays_with ORDER BY at) FROM cat:one;
-- Or any graph table
SELECT <-(SELECT * FROM ? ORDER BY at) FROM cat:one;
```

### Ranges inside graph queries

_(since v2.3.0)_

Range syntax can also be used on the edges of a graph query.

```surql
CREATE person:one, person:two, person:three, person:four;

RELATE person:one->likes:1->person:two;
RELATE person:one->likes:2->person:three;
RELATE person:one->likes:3->person:four;

person:one->likes:2..=4->person;
```

```surql title="Output"
[
	person:three,
	person:four
]
```

A common usage of range syntax on edges is when their ID has been defined as a ULID, making the `id` field random yet sortable and significant in terms of time.

```surql
RELATE character:one->speaks_to:ulid()->character:two SET content = "Greetings, adventurer!";
RELATE character:one->speaks_to:ulid()->character:two SET content = "Can you please help me? My sheep have run amok.";

SELECT
	-- Grab the latter part of the record ID, turn it into a datetime
    time::from_ulid(id.id()) AS at,
    content
FROM
    -- ULID from 2025-04-25, well before today's date
    character:one->speaks_to:01JSNG0KZSY3HJ5QSZ7JSMQMGR..;
```

```surql title="Example output"
[
	{
		at: d'2025-04-25T03:37:53.246Z',
		content: 'Greetings, adventurer!'
	},
	{
		at: d'2025-04-25T03:37:53.248Z',
		content: 'Can you please help me? My sheep have run amok.'
	}
]
```

Array-based record IDs also work well inside range queries on edges.

```surql
CREATE planet:venus, telescope:one;

RELATE telescope:one->observed:[d'2025-04-24T02:02:18.204Z']->planet:venus CONTENT { 
      temperature_profile: {
        surface: 735.0,
        upper_atmosphere: 300.0
      },
      composition: {
        CO2: 96.5,
        N2: 3.5,
        SO2: 0.015
      },
};

RELATE telescope:one->observed:[d'2025-04-25T02:02:18.204Z']->planet:venus CONTENT {
      temperature_profile: {
        surface: 737.0,
        upper_atmosphere: 298.5
      },
      composition: {
        CO2: 96.6,
        N2: 3.4,
        SO2: 0.015
    }
};

SELECT id, (<-observed:[d'2025-04-24']..).{
    at: id[0], 
    surface: temperature_profile.surface,
    atmosphere: temperature_profile.upper_atmosphere
} AS observations FROM planet;
```

```surql title="Output"
[
	{
		id: planet:venus,
		observations: [
			{
				at: d'2025-04-24T02:02:18.204Z',
				atmosphere: 300,
				surface: 735
			},
			{
				at: d'2025-04-25T02:02:18.204Z',
				atmosphere: 298.5f,
				surface: 737
			}
		]
	}
]
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/remove

# REMOVE

The REMOVE statement is used to remove resources such as databases, tables, indexes, events and more.

The `REMOVE` statement is used to remove resources such as databases, tables, indexes, events and more.
Similar to an SQL DROP statement.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
REMOVE [
    ACCESS    [ IF EXISTS ] @name ON [ NAMESPACE | DATABASE ]
  | ANALYZER  [ IF EXISTS ] @name
  | API       [ IF EXISTS ] @name
  | BUCKET    [ IF EXISTS ] @name [ ON [ ROOT | NAMESPACE | DATABASE ] ]
  | CONFIG    [ IF EXISTS ] [ GRAPHQL | API | DEFAULT ]
  | DATABASE  [ AND EXPUNGE ] [ IF EXISTS ] @name
  | EVENT     [ IF EXISTS ] @name ON [ TABLE ] @table
  | FIELD     [ IF EXISTS ] @name ON [ TABLE ] @table
  | FUNCTION  [ IF EXISTS ] @name
  | INDEX     [ IF EXISTS ] @name ON [ TABLE ] @table
  | NAMESPACE [ AND EXPUNGE ] [ IF EXISTS ] @name
  | PARAM     [ IF EXISTS ] @name
  | TABLE     [ AND EXPUNGE ] [ IF EXISTS ] @name
  | TYPE      [ IF EXISTS ] @name
  | USER      [ IF EXISTS ] @name ON [ ROOT | NAMESPACE | DATABASE ]
]
```

**Railroad Diagram**

export const removeAst = {
  type: "Diagram",
  padding: [10, 20, 10, 20],
  children: [
    { type: "Sequence", children: [
      { type: "Terminal", text: "REMOVE" },
      { type: "Choice", index: 1, children: [

        { type: "Sequence", children: [ { type: "Terminal", text: "ACCESS" }, { type: "Optional", child: { type: "Sequence", children: [ { type: "Terminal", text: "IF" }, { type: "Terminal", text: "EXISTS" } ] } }, { type: "NonTerminal", text: "@name" }, { type: "Terminal", text: "ON" }, { type: "Choice", index: 1, children: [ { type: "Terminal", text: "NAMESPACE" }, { type: "Terminal", text: "DATABASE" } ] } ] },

        { type: "Sequence", children: [ { type: "Terminal", text: "ANALYZER" }, { type: "Optional", child: { type: "Sequence", children: [ { type: "Terminal", text: "IF" }, { type: "Terminal", text: "EXISTS" } ] } }, { type: "NonTerminal", text: "@name" } ] },

        { type: "Sequence", children: [ { type: "Terminal", text: "API" }, { type: "Optional", child: { type: "Sequence", children: [ { type: "Terminal", text: "IF" }, { type: "Terminal", text: "EXISTS" } ] } }, { type: "NonTerminal", text: "@name" } ] },

        { type: "Sequence", children: [ { type: "Terminal", text: "BUCKET" }, { type: "Optional", child: { type: "Sequence", children: [ { type: "Terminal", text: "IF" }, { type: "Terminal", text: "EXISTS" } ] } }, { type: "NonTerminal", text: "@name" }, { type: "Optional", child: { type: "Sequence", children: [ { type: "Terminal", text: "ON" }, { type: "Choice", index: 1, children: [ { type: "Terminal", text: "ROOT" }, { type: "Terminal", text: "NAMESPACE" }, { type: "Terminal", text: "DATABASE" } ] } ] } } ] },

        { type: "Sequence", children: [ { type: "Terminal", text: "CONFIG" }, { type: "Optional", child: { type: "Sequence", children: [ { type: "Terminal", text: "IF" }, { type: "Terminal", text: "EXISTS" } ] } }, { type: "Choice", index: 1, children: [ { type: "Terminal", text: "GRAPHQL" }, { type: "Terminal", text: "API" }, { type: "Terminal", text: "DEFAULT" } ] } ] },

        { type: "Sequence", children: [ { type: "Terminal", text: "DATABASE" }, { type: "Optional", child: { type: "Sequence", children: [ { type: "Terminal", text: "IF" }, { type: "Terminal", text: "EXISTS" } ] } }, { type: "NonTerminal", text: "@name" } ] },

        { type: "Sequence", children: [ { type: "Terminal", text: "EVENT" }, { type: "Optional", child: { type: "Sequence", children: [ { type: "Terminal", text: "IF" }, { type: "Terminal", text: "EXISTS" } ] } }, { type: "NonTerminal", text: "@name" }, { type: "Terminal", text: "ON" }, { type: "Optional", child: { type: "Terminal", text: "TABLE" } }, { type: "NonTerminal", text: "@table" } ] },

        { type: "Sequence", children: [ { type: "Terminal", text: "FIELD" }, { type: "Optional", child: { type: "Sequence", children: [ { type: "Terminal", text: "IF" }, { type: "Terminal", text: "EXISTS" } ] } }, { type: "NonTerminal", text: "@name" }, { type: "Terminal", text: "ON" }, { type: "Optional", child: { type: "Terminal", text: "TABLE" } }, { type: "NonTerminal", text: "@table" } ] },

        { type: "Sequence", children: [ { type: "Terminal", text: "FUNCTION" }, { type: "Optional", child: { type: "Sequence", children: [ { type: "Terminal", text: "IF" }, { type: "Terminal", text: "EXISTS" } ] } }, { type: "NonTerminal", text: "@name" } ] },

        { type: "Sequence", children: [ { type: "Terminal", text: "INDEX" }, { type: "Optional", child: { type: "Sequence", children: [ { type: "Terminal", text: "IF" }, { type: "Terminal", text: "EXISTS" } ] } }, { type: "NonTerminal", text: "@name" }, { type: "Terminal", text: "ON" }, { type: "Optional", child: { type: "Terminal", text: "TABLE" } }, { type: "NonTerminal", text: "@table" } ] },

        { type: "Sequence", children: [ { type: "Terminal", text: "NAMESPACE" }, { type: "Optional", child: { type: "Sequence", children: [ { type: "Terminal", text: "IF" }, { type: "Terminal", text: "EXISTS" } ] } }, { type: "NonTerminal", text: "@name" } ] },

        { type: "Sequence", children: [ { type: "Terminal", text: "PARAM" }, { type: "Optional", child: { type: "Sequence", children: [ { type: "Terminal", text: "IF" }, { type: "Terminal", text: "EXISTS" } ] } }, { type: "Terminal", text: "$" }, { type: "NonTerminal", text: "@name" } ] },

        { type: "Sequence", children: [ { type: "Terminal", text: "TABLE" }, { type: "Optional", child: { type: "Sequence", children: [ { type: "Terminal", text: "IF" }, { type: "Terminal", text: "EXISTS" } ] } }, { type: "NonTerminal", text: "@name" } ] },

        { type: "Sequence", children: [ { type: "Terminal", text: "TYPE" }, { type: "Optional", child: { type: "Sequence", children: [ { type: "Terminal", text: "IF" }, { type: "Terminal", text: "EXISTS" } ] } }, { type: "NonTerminal", text: "@name" } ] },

        { type: "Sequence", children: [ { type: "Terminal", text: "USER" }, { type: "Optional", child: { type: "Sequence", children: [ { type: "Terminal", text: "IF" }, { type: "Terminal", text: "EXISTS" } ] } }, { type: "NonTerminal", text: "@name" }, { type: "Terminal", text: "ON" }, { type: "Choice", index: 1, children: [ { type: "Terminal", text: "ROOT" }, { type: "Terminal", text: "NAMESPACE" }, { type: "Terminal", text: "DATABASE" } ] } ] }
      ] }
    ]}
  ]
};

## Example usage
### Basic usage

The following queries show an example of how to remove resources.

```surql
-- Setup
DEFINE NAMESPACE surrealdb;
DEFINE DATABASE blog;
DEFINE USER writer ON NAMESPACE PASSWORD 'secret';
DEFINE USER writer ON DATABASE PASSWORD 'secret';
DEFINE ACCESS token ON NAMESPACE TYPE JWT ALGORITHM HS512 KEY 'secret';
DEFINE ACCESS user ON DATABASE TYPE RECORD;
DEFINE BUCKET my_bucket BACKEND "memory";
DEFINE BUCKET shared ON ROOT BACKEND "memory";
DEFINE TABLE article SCHEMAFULL;
DEFINE EVENT new_post ON TABLE article WHEN $event = "CREATE" THEN {};
DEFINE FIELD tags ON TABLE article TYPE array<string>;
DEFINE FIELD author ON TABLE article TYPE string;
DEFINE INDEX authors ON TABLE article FIELDS author;
DEFINE ANALYZER example_ascii TOKENIZERS class FILTERS ascii;
DEFINE FUNCTION fn::update_author() -> none {};
DEFINE PARAM $author VALUE 'Ann';
DEFINE TYPE priority AS 'low' | 'high';

REMOVE NAMESPACE surrealdb;

REMOVE DATABASE blog;

REMOVE USER writer ON NAMESPACE;

REMOVE USER writer ON DATABASE;

REMOVE ACCESS token ON NAMESPACE;

REMOVE ACCESS user ON DATABASE;

-- Without ON, removes a bucket defined on the database
REMOVE BUCKET my_bucket;

REMOVE BUCKET shared ON ROOT;

REMOVE EVENT new_post ON TABLE article;

-- Only works for Schemafull tables (i.e. tables with a schema)
REMOVE FIELD tags ON TABLE article;

REMOVE INDEX authors ON TABLE article;

-- Fails if a full-text index still references this analyzer (remove the index first)
REMOVE ANALYZER example_ascii;

REMOVE FUNCTION fn::update_author;

REMOVE PARAM $author;

REMOVE TABLE article;

-- Fails while another definition, such as a field or a function, names the type
REMOVE TYPE priority;
```

### Using if exists clause

The following queries show an example of how to remove resources using the `IF EXISTS` clause, which will only remove the resource if it exists.

```surql
REMOVE NAMESPACE IF EXISTS surrealdb;

REMOVE DATABASE IF EXISTS blog;

REMOVE USER IF EXISTS writer ON NAMESPACE;

REMOVE USER IF EXISTS writer ON DATABASE;

REMOVE ACCESS IF EXISTS token ON NAMESPACE;

REMOVE ACCESS IF EXISTS user ON DATABASE;

REMOVE BUCKET IF EXISTS my_bucket;

REMOVE EVENT IF EXISTS new_post ON TABLE article;

REMOVE FIELD IF EXISTS tags ON TABLE article;

REMOVE INDEX IF EXISTS authors ON TABLE article;

REMOVE ANALYZER IF EXISTS example_ascii;

REMOVE FUNCTION IF EXISTS fn::update_author;

REMOVE PARAM IF EXISTS $author;

REMOVE TABLE IF EXISTS article;

REMOVE TYPE IF EXISTS priority;
```

### Usage in table views

_(since v3.0.0)_

A table used as a source for a table view cannot be removed until the table view itself has been removed.

```surql
DEFINE TABLE pc;
DEFINE TABLE pc_agg AS SELECT count(), class FROM pc GROUP BY class;
CREATE |pc:3| SET class = "Wizard";
CREATE |pc:10| SET class = "Warrior";
SELECT * FROM pc_agg;
//- [{ class: 'Warrior', count: 10, id: pc_agg:['Warrior'] }, { class: 'Wizard', count: 3, id: pc_agg:['Wizard'] }]
REMOVE TABLE pc;
//- 'Invalid query: Cannot delete table `pc` on which a view is defined, table(s) `pc_agg` are defined as a view on this table.'
REMOVE TABLE pc_agg;
-- pc_agg is now gone, pc can be removed too
REMOVE TABLE pc;
```

The `SELECT * FROM pc_agg` query shows that the table view is pulling data from the `pc` table. As long as the `pc` table exists, `pc_agg` cannot be removed.

### Behaviour after removal

While all `REMOVE` statements remove the definition for a resource, some resources have additional actions when removed. They are:

* REMOVE DATABASE: This effectively deletes the database by removing the index stores, deleting all definitions, and clearing the cache. Since SurrealDB 3.2.0, and 2.7.0 on the 2.x line, this definition removes the database from the catalog immediately. This is followed by physical deletion of the underlying keys which is deferred to a background reaper (tune with [`SURREAL_RECLAIM_INTERVAL`](/docs/reference/cli/db/environment-variables.md) and, on 3.x, [`SURREAL_RECLAIM_GRACE`](/docs/reference/cli/db/environment-variables.md)), allowing `REMOVE DATABASE` to return quickly even for large tenants. Recreating the same database name yields a fresh, empty database. On 2.x, recreating it while more than 10,000 keys of the old database remain fails until the reaper catches up, as described in [Reusing a removed name](/docs/operate/upgrading/26-to-27.md#reusing-a-removed-name).
* REMOVE NAMESPACE: Same deferred reclaim as `REMOVE DATABASE` since SurrealDB 3.2.0 and 2.7.0, in addition to performing a remove on each database inside the namespace.
* REMOVE TABLE: Similar to the two previous statements but on a single table, and will fail if a table view depends on it. Removing a table will also send a [KILL](/docs/reference/query-language/statements/kill.md) notification for each live query defined on it.
* REMOVE INDEX: This statement also removes the index store cache and index data. Since 3.2.0, it removes the index definition immediately and thereafter reclaims index data in the background in the same way as namespace and database removal. If you are considering removing an index but want to test the behaviour out first, use an [ALTER INDEX PREPARE REMOVE](/docs/reference/query-language/statements/alter/indexes.md#prepare-remove-clause) statement. This will decommission the index, after which you can test out queries to see their behaviour as they would function after the index is removed. If acceptable then the index can then be removed, or the change can be reverted by [rebuilding the index](/docs/reference/query-language/statements/rebuild.md). Standard, unique, spatial, full-text and vector indexes share one store of document IDs for each table, and `COUNT` indexes do not use it. From SurrealDB 4.0, when the removed index was the last one on the table to use that store, a `DEFINE INDEX` or `REBUILD INDEX` of an index that uses it on the same table, while that background reclaim is still running, finishes the reclaim first and then succeeds. Inside `BEGIN ... COMMIT` or a transaction that a client holds open, the statement fails instead with a retryable transaction conflict, and a retry succeeds once the reclaim is complete.
* REMOVE TYPE: This statement fails while another definition names the type, and the error names that definition. A field names it in its type, or in a cast in its `DEFAULT`, `VALUE` or `ASSERT` clause, a function in its arguments or return type, and another type in its body, `ASSERT` or `DEFAULT`. An event, a view, a table or field permission, a parameter's permission, an API, an access method's `SIGNIN` or `AUTHENTICATE` clause, the `COUNT WHERE` condition of an index and a bucket's permission also name it when one of their expressions casts to it. Remove or change those definitions first.

On a [versioned SurrealKV datastore](/docs/reference/query-language/statements/select.md#the-version-clause), a `REMOVE TABLE` deletes only the current version of the table's data, so a `SELECT ... VERSION` at a time before the removal still reads the records. `REMOVE TABLE AND EXPUNGE` also deletes every earlier version of the table's records, its reference keys and the reference caches that point at it, so such a query no longer finds the table. `AND EXPUNGE` comes directly after the keyword, before `IF EXISTS` and the name, and `REMOVE NAMESPACE` and `REMOVE DATABASE` accept it as well.

```surql
-- Setup
CREATE article:1 SET title = 'Draft';

REMOVE TABLE AND EXPUNGE article;
```

Another `REMOVE` statement to note is `REMOVE FIELD`. It removes the definitions of the fields nested inside the field as well, at any depth, so `REMOVE FIELD address ON person` also removes the definition of `address.city`. This applies to every table and at every compatibility level. In SurrealDB 3.x, each nested definition stays until it is removed with its own `REMOVE FIELD`.

On a `SCHEMAFULL` table in a database at [compatibility level](/docs/reference/query-language/statements/define/database.md#compatibility-level) 4, the default for databases created from SurrealDB 4.0, it also removes the field's stored values:

> [!WARNING]
> At level 4, the values are gone and defining the field again does not restore them. In SurrealDB 3.x, and in a database at level 3, `REMOVE FIELD` leaves the stored values untouched, so a field that is removed and then defined again still holds them. A schema script that relies on that loses data when it runs against a database at level 4. Check the level with `(INFO FOR DB).compatibility` before running such a script.

```surql
-- In a database at compatibility level 4
DEFINE TABLE person SCHEMAFULL;
DEFINE FIELD name ON person TYPE string;
CREATE person:one SET name = "Billy";
REMOVE FIELD name ON person;

SELECT * FROM person;
```

```surql title="Output"
[{ id: person:one }]
```

In every other case it removes only the definition, and the stored values stay until each record is updated. That covers a `SCHEMALESS` table at either level, and any table in a database at level 3, which is how SurrealDB 3.x behaves. To remove the existing data, perform an `UPDATE` or `UPSERT` statement that uses `UNSET` on the field or sets the field's value to `NONE`.

```surql
DEFINE FIELD name ON person TYPE string;
CREATE person:one SET name = "Billy";
REMOVE FIELD name ON person;

-- 'name' data is still there
SELECT * FROM person;
-- Does nothing
UPDATE person;
-- Unsetting the field removes the 'name' data
UPDATE person UNSET name;
```

At level 3, a `SCHEMAFULL` table can still be read while its records hold a field that is no longer defined, but an update to such a record fails until the field is unset:

```surql
-- In a database at compatibility level 3
DEFINE TABLE person SCHEMAFULL;
DEFINE FIELD name ON person TYPE string;
CREATE person:one SET name = "Billy";
REMOVE FIELD name ON person;

UPDATE person;
```

```surql title="Error output"
"Found field 'name', but no such field exists for table 'person'"
```

---

Source: https://surrealdb.com/docs/reference/query-language/statements/return

# RETURN

The RETURN statement returns a value or the result of a query, and ends the statement, function, closure or per-record clause that it stands in.

The `RETURN` statement returns a value or the result of a query. It also ends the context it stands in, such as a function body, so the code after it there does not run. This page covers the syntax, which constructs a `RETURN` ends, and how a `RETURN` behaves in a `LET`, in a clause and in a transaction.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
RETURN @value
```

## Example usage
### Basic usage

`RETURN` is always followed by a value. As every data type in SurrealDB is a type of [value](/docs/reference/query-language/language-primitives/data-types/values.md), the `RETURN` statement can return anything from simple values to the result of queries.

```surql
-- Return a simple value
RETURN 123;
RETURN "I am a string!";
RETURN {
	prop: "value"
};

-- Return the result of a query
RETURN SELECT * FROM person;
RETURN (CREATE person).id;
```

Values on their own are treated as if they have an implicit `RETURN` in front. As such, the following queries return the same output as in the previous example.

```surql
123;
"I am a string!";
{
	prop: "value"
};
SELECT * FROM person;
(CREATE person).id;
```

## Ending a function or closure

A `RETURN` sets the value of a function or closure body and ends the body, so the statements after it do not run.

```surql title="Function return value"
DEFINE FUNCTION fn::person::create($firstname: string, $lastname: string) {
	LET $person = CREATE person CONTENT {
		firstname: $firstname,
		lastname: $lastname,
	};

	-- The RETURN statement will set the return value of the custom
	-- function, and further queries will not be executed.
	RETURN $person.id;

    -- This query will never be executed
    CREATE person SET firstname = "Stephen", lastname = "Strange";
};

fn::person::create("Thanos", "Johnson");
SELECT * FROM person;
```

```surql title="Functions"
DEFINE FUNCTION fn::round::up($num: number) -> number {
    IF $num % 2 == 0 {
        -- Ends the function
        RETURN $num;
    };

    -- Only runs when the RETURN inside the IF did not run
    RETURN $num + 1;
};
```

A block or an `IF` inside the body does not stop a `RETURN`. The `RETURN` in the inner block below ends the whole function, so the second `RETURN` never runs:

```surql
DEFINE FUNCTION fn::test() -> int {
    {
        RETURN 1;
    };
    RETURN 2;
};

RETURN fn::test();
```

```surql title="Output"
1
```

The same applies to a block that a `LET` binds inside a function. When `$x` is greater than `2`, the `RETURN` ends the function with `'big'`, and the `LET` binds nothing:

```surql
DEFINE FUNCTION fn::g($x: int) -> string {
    LET $y = {
        IF $x > 2 { RETURN 'big' };
        'small'
    };
    RETURN 'after ' + $y;
};

RETURN [fn::g(1), fn::g(3)];
```

```surql title="Output"
['after small', 'big']
```

A closure body works the same way:

```surql
[1, 2].map(|$x| {
    IF $x > 1 { RETURN 'big' };
    'small'
});
```

```surql title="Output"
['small', 'big']
```

## Which context a `RETURN` ends

A `RETURN` sets the value of the context it stands in and ends that context. The following constructs are contexts:

| Context | What the `RETURN` ends |
| --- | --- |
| A statement of a query or of a transaction | The statement, which gives the value as its result |
| A function or closure body | The call, which returns the value |
| A clause that a statement evaluates once for each record or value: `WHERE`, projections, `ORDER BY`, `GROUP BY` and `SPLIT` keys, `SET`, `CONTENT` and `MERGE` values, and the `RETURN` clause of a write, including the clauses of a table view | The evaluation for that one record or value |
| Stored code: a field's `VALUE`, `DEFAULT` and `ASSERT` clauses, a permission, and an event | The evaluation for that one record |

Every other construct passes a `RETURN` outwards to the nearest context around it. These include blocks, `IF` and `FOR`, parenthesised statements, operands, array and object elements, function arguments, the value of a `LET`, the `FROM` source, `LIMIT`, `START` and `TIMEOUT`, the target of a write, and the records that an `INSERT` writes.

At the top level of a query, the nearest context is the statement itself. A `RETURN` inside an operand or a block therefore gives the result of the whole statement, and the expression around it does not finish:

```surql
RETURN 1 + (RETURN 2);
//- 2

RETURN [1, (RETURN 2), 3];
//- 2

RETURN { IF true { RETURN 5 }; 6 } + 1;
//- 5
```

A `RETURN` only ends its own statement. The statements after it in the query still run, and their results are not changed.

## `RETURN` in the value of a `LET`

The value of a `LET` is not a context, so a `RETURN` inside it ends the `LET` statement. The statement gives the value of the `RETURN` as its result, and the `LET` binds nothing:

```surql
LET $x = { IF true { RETURN 1 }; 2 };
//- 1

RETURN $x;
//- NONE
```

When the `RETURN` does not run, the `LET` binds the last value of the block as usual:

```surql
LET $x = { IF false { RETURN 1 }; 2 };
//- NONE

RETURN $x;
//- 2
```

To choose the value that a `LET` binds, write an `IF` whose branches are values, with no `RETURN` in them:

```surql
LET $count = 150;
LET $size = IF $count > 100 { 'large' } ELSE { 'small' };
```

Before SurrealDB 4.0, a `LET` bound the value of a `RETURN` inside its value.

## `RETURN` in a clause

A clause that a statement evaluates once for each record is a context of its own. A `RETURN` there gives the value for that record only, and the statement continues with the next record. In a `WHERE` clause, the `RETURN` decides whether the record matches:

```surql
SELECT VALUE id FROM [
    { id: 1, a: 0 },
    { id: 2, a: 1 },
    { id: 3, a: 1.5 },
    { id: 4, a: 2 },
    { id: 5, a: 3 }
] WHERE {
    IF a > 2 { RETURN true };
    IF a < 1 { RETURN true };
    false
};
```

```surql title="Output"
[1, 5]
```

In a projection, the `RETURN` gives the value for the record:

```surql
SELECT VALUE {
    IF a > 2 { RETURN 'big' };
    'small'
} FROM [{ a: 0 }, { a: 3 }];
```

```surql title="Output"
['small', 'big']
```

In a `SET` clause, the `RETURN` gives the value of the field. The `+ 1` after it does not run, so `x` is `1`:

```surql
CREATE ts:1 SET x = (RETURN 1) + 1, y = 5;
```

```surql title="Output"
[{ id: ts:1, x: 1, y: 5 }]
```

A clause that a statement evaluates only once, such as `FROM`, `LIMIT` or `START`, is not a context, and neither is the target of a write. A `RETURN` there ends the whole statement before it reads or writes any record. The `DELETE` below gives `person:5` as its result and deletes nothing:

```surql
CREATE person:1, person:5 RETURN NONE;
//- []

DELETE (RETURN person:5);
//- person:5

SELECT VALUE id FROM person:5;
//- [person:5]

SELECT * FROM (RETURN 7);
//- 7
```

## `RETURN` inside a transaction

Each statement between `BEGIN` and `COMMIT` is a context of its own. A `RETURN` placed directly inside a transaction therefore ends only its own statement: its value is one of the results of the query, and the statements after it still run. This is the case from SurrealDB 4.0. Before 4.0, a `RETURN` ended the transaction early, and the statements after it did not run.

```surql title="Transaction return value"
BEGIN TRANSACTION;

-- We are executing quite a few queries here
LET $firstname = "John";
LET $lastname = "Doe";

LET $person = CREATE ONLY person CONTENT {
	firstname: $firstname,
	lastname: $lastname,
};

-- The person's ID is the result of this statement
RETURN $person.id;

-- One issue with this approach is that query errors are generic.
-- To get around that, use a block, which is executed as a transaction by itself.

COMMIT TRANSACTION;
```

Each of the statements below runs, and the two `RETURN` values are among the results:

```surql title="Transactions"
BEGIN;
-- Runs
RETURN 1;
-- Runs
CREATE a;
-- Runs
RETURN 2;
COMMIT;
```

A `RETURN` inside an `IF`, a block or the value of a `LET` that stands directly in the transaction also ends only that statement. To end part of a transaction early, put those statements in a block. The `RETURN` ends the block's statement, and the transaction carries on after it:

```surql title="Ending a block inside a transaction"
BEGIN;
CREATE c:1;
{
    CREATE c:2;
    RETURN "done";
    -- Does not run
    CREATE c:3;
};
-- Runs
CREATE c:4;
COMMIT;
```

To cancel the whole transaction instead, use [`THROW`](/docs/reference/query-language/statements/throw.md).

---

Source: https://surrealdb.com/docs/reference/query-language/statements/select

# SELECT

Select and query records, with FROM, WHERE, GROUP, ORDER and LIMIT.

The `SELECT` statement can be used for selecting and querying data in a database. Each SELECT statement supports selecting from multiple targets, which can include tables, records, edges, subqueries, parameters, arrays, objects, and other values.

The [Learn more](#learn-more) section has a video on selecting across document-style relationships.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
SELECT 
    VALUE @field | @fields [ AS @alias ] [ OMIT @fields ... ]
    FROM [ ONLY ] @targets
    [ WITH [ NOINDEX | INDEX @indexes ... ]]
    [ WHERE @conditions ]
    [ SPLIT [ ON ] @field, ... ]
    [ 
		GROUP [ ALL | [ BY ] @field, ... ] | 
		ORDER [ BY ] RAND() | @field [ COLLATE ] [ NUMERIC ] [ ASC | DESC ], ...
	]
    [ LIMIT [ BY ] @limit ]
    [ START [ AT ] @start 0 ]
    [ FETCH @fields ... ]
    [ TIMEOUT @duration ]
    [ FOR UPDATE ]
    [ TEMPFILES ]
    [ EXPLAIN [ FULL ] ]
;
```

## Example usage
### Basic usage

By default, SurrealDB returns an array of JSON-like objects called records instead of a tabular structure of rows and columns.

```surql
CREATE person:tobie SET
	name.first = "Tobie",
	address = "1 Bagshot Row",
	email = "tobie@surrealdb.com";

-- Select all fields from a table
SELECT * FROM person;

-- Select specific fields from a table
SELECT name, address, email FROM person;

-- Select all fields from a specific record
SELECT * FROM person:tobie;

-- Select specific fields from a specific record
SELECT name, address, email FROM person:tobie;

-- Select just a single record
-- Using the ONLY keyword, just an object
-- for the record in question will be returned.
-- This, instead of an array with a single object.
SELECT * FROM ONLY person:tobie;
```

An alias can be used to rename fields or change the structure of an object.

```surql
-- Setup from the example above
CREATE person:tobie SET
	name.first = "Tobie",
	address = "1 Bagshot Row",
	email = "tobie@surrealdb.com";

SELECT * FROM person;

-- Field `address` now shows up as "string::uppercase"
-- name.first structure now flattened into a simple field
SELECT
	name.first AS user_name,
	string::uppercase(address)
FROM person;

-- "Morgan Hitchcock" added to `name` field structure,
-- `angry_address` for field name instead of automatically
-- generated "string::uppercase(address) + '!!!'"
SELECT
	name.first,
	"Morgan Hitchcock" AS name.last,
	string::uppercase(address) + "!!!" AS angry_address
FROM person;
```

```surql title="Output"
-------- Query --------

[
	{
		address: '1 Bagshot Row',
		email: 'tobie@surrealdb.com',
		id: person:tobie,
		name: {
			first: 'Tobie'
		}
	}
]

-------- Query --------

[
	{
		"string::uppercase": '1 BAGSHOT ROW',
		user_name: 'Tobie'
	}
]

-------- Query --------

[
	{
		angry_address: '1 BAGSHOT ROW!!!',
		name: {
			first: 'Tobie',
			last: 'Morgan Hitchcock'
		}
	}
]
```

SurrealDB can also return specific fields as an array of values instead of the default array of objects. This only works if you select a single un-nested field from a table or a record.

```surql
-- Setup from the example above
CREATE person:tobie SET
	name.first = "Tobie",
	address = "1 Bagshot Row",
	email = "tobie@surrealdb.com";

-- Select the values of a single field from a table
SELECT VALUE name FROM person;

-- Select the values of a single field from a specific record
SELECT VALUE name FROM person:00e1nc508h9f7v63x72O;
```

### Advanced expressions

SELECT queries support advanced expressions in the field projections.

```surql
-- Setup
CREATE person:tobie SET address = [
	{ city: 'London', country: 'UK', coordinates: [51.51, -0.13], active: true },
	{ city: 'Paris', country: 'France', coordinates: [48.86, 2.35], active: false }
];
CREATE friend:jaime SET name = 'Jaime';
RELATE person:tobie->likes->friend:jaime;
CREATE post:hello SET title = 'Hello';
RELATE person:tobie->reacted_to->post:hello SET type = 'celebrate';
CREATE article:one SET tags = ['rust', 'database'];
CREATE article:two SET tags = ['database', 'graph'];
CREATE temperature:one SET celsius = 21.5;
CREATE review:one SET rating = 5;
CREATE user:jaime SET name = 'Jaime';
CREATE events:one SET type = 'activity';

-- Select nested objects/values
SELECT address.city FROM person;

-- Select all nested array values
-- note the .* syntax works to select everything from an array or object-like values
SELECT address.*.coordinates AS coordinates FROM person;
-- Equivalent to
SELECT address.coordinates AS coordinates FROM person;

-- Select one item from an array
SELECT address.coordinates[0] AS latitude FROM person;

-- Select unique values from an array
SELECT array::distinct(tags) FROM article;

-- Select unique values from a nested array across an entire table
SELECT array::group(tags) AS tags FROM article GROUP ALL;

-- Use mathematical calculations in a select expression
SELECT
	(( celsius * 1.8 ) + 32) AS fahrenheit
	FROM temperature;

-- Return boolean expressions with an alias
SELECT rating >= 4 as positive FROM review;

-- Select manually generated object structure
SELECT
	{ weekly: false, monthly: true } AS `marketing settings`
FROM user;

-- Select filtered nested array values
SELECT address[WHERE active = true] FROM person;

-- Select a person who has reacted to a post using a celebration
-- Path can be conceptualized as:
-- person->(reacted_to WHERE type='celebrate')->post
SELECT * FROM person WHERE ->(reacted_to WHERE type='celebrate')->post;

-- Select a remote field from connected out graph edges
SELECT ->likes->friend.name AS friends FROM person:tobie;

-- Use the result of a subquery as a returned field
SELECT *, (SELECT * FROM events
  WHERE type = 'activity' LIMIT 5) AS history FROM user;

-- Restructure objects in a select expression after `.` operator
SELECT address.{city, country} FROM person;
```

A subquery in parentheses resolves to a value, as any other parenthesised expression does, before the expression around it uses that value. The example below steps through a `SELECT` with one subquery in a field and another in its `WHERE` clause, for one of the records it reads:

<DemoEmbed title="How a SELECT with subqueries resolves" height={640} pages={[{ "label": "How a SELECT with subqueries resolves", "src": "/docs/parentheses/parentheses?example=select" }]} />

### Fields that share an output name

Each field in the projection is written to the output under its alias, or under its own path when it has no alias. When two fields write to the same name, the later one replaces the earlier one, so the order of the fields can change the result.

```surql
CREATE p:1 SET a = 1, b = 2;
SELECT a AS x, b AS x FROM p:1;
```

```surql title="Output"
[{ x: 2 }]
```

This also applies to graph paths. `<-write.*` and `<-write<-user.*` both write to `<-write`, so in the query below the second field overwrites the users that the first one nested there.

```surql
CREATE user:tobie SET name = 'tobie';
CREATE article:surreal SET title = 'good';
RELATE user:tobie->write->article:surreal;

-- The users from the first field are lost
SELECT *, <-write<-user.*, <-write.* FROM article:surreal;
```

Give each field its own alias to keep the values apart:

```surql
-- Setup from the example above
CREATE user:tobie SET name = 'tobie';
CREATE article:surreal SET title = 'good';
RELATE user:tobie->write->article:surreal;

SELECT *, <-write.* AS writes, <-write<-user.* AS authors FROM article:surreal;
```

```surql title="Output"
[
	{
		authors: [{ id: user:tobie, name: 'tobie' }],
		id: article:surreal,
		title: 'good',
		writes: [{ id: write:lpcwdmte8moxkgr1944t, in: user:tobie, out: article:surreal }]
	}
]
```

The same happens when a field path runs through a field that `*` has already written. Below, `*` writes the `places` array, and `places.city` then writes its whole result, an array of every city, into a `city` field on each element of that array:

```surql
CREATE place:west SET city = 'frankfurt';
CREATE place:wall SET city = 'berlin';
CREATE town:one SET places = [place:west, place:wall];

SELECT *, places.city FROM town:one;
```

```surql title="Output"
[
	{
		id: town:one,
		places: [
			{ city: ['frankfurt', 'berlin'] },
			{ city: ['frankfurt', 'berlin'] }
		]
	}
]
```

An alias puts the cities in a field of their own, and [destructuring](/docs/reference/query-language/language-primitives/idioms.md#destructuring) keeps each city with its own place:

```surql
-- Setup from the example above
CREATE place:west SET city = 'frankfurt';
CREATE place:wall SET city = 'berlin';
CREATE town:one SET places = [place:west, place:wall];

SELECT *, places.city AS cities FROM town:one;
//- [{ cities: ['frankfurt', 'berlin'], id: town:one, places: [place:west, place:wall] }]

SELECT id, places.{ id, city } AS places FROM town:one;
//- [{ id: town:one, places: [{ city: 'frankfurt', id: place:west }, { city: 'berlin', id: place:wall }] }]
```

## Filter queries using the `WHERE` clause

As with traditional SQL queries, a SurrealDB SELECT query supports conditional filtering using a `WHERE` clause. If the expression in the `WHERE` clause [is truthy](/docs/reference/query-language/language-primitives/data-types/values.md#values-and-truthiness) (is present and not an empty value), then the respective record will be returned.

```surql
-- Setup
CREATE article:one SET published = true;
CREATE article:two SET published = false;
CREATE profile:tobie;
CREATE organisation:one, organisation:two, organisation:three, organisation:four;
RELATE profile:tobie->experience->[organisation:one, organisation:two, organisation:three, organisation:four];
CREATE person:tobie SET name = 'Tobie', address = [
	{ city: 'London', active: true },
	{ city: 'Paris', active: false }
];
CREATE post:hello SET title = 'Hello';
RELATE person:tobie->reaction->post:hello SET type = 'celebrate';
CREATE user:tobie SET admin = true, active = true, owner = false;

-- Simple conditional filtering
SELECT * FROM article WHERE published = true;

-- Conditional filtering based on graph edges
SELECT * FROM profile WHERE count(->experience->organisation) > 3;

-- Conditional filtering based on graph edge properties
SELECT * FROM person WHERE ->(reaction WHERE type='celebrate')->post;

-- Conditional filtering with boolean logic
SELECT * FROM user WHERE (admin AND active) OR owner = true;

-- Select filtered nested array values
SELECT address[WHERE active = true] FROM person;

-- Select names for 'person' records as long as 'name' is present
-- and not an empty string ""
SELECT name FROM person WHERE name;
```

## Numeric ranges in a `WHERE` clause

A numeric range can replace a pair of comparisons in a `WHERE` clause. The two statements below return the same records, and the range form is shorter.

```surql
CREATE |person:20000| SET age = (rand::float() * 120).round() RETURN NONE;

-- Assign output to a parameter so the SELECT output is not displayed
LET $_ = SELECT * FROM person WHERE age > 18 AND age < 65;
LET $_ = SELECT * FROM person WHERE age in 18..=65;
```

The comparison form is faster. When the field has an index, the pair of comparisons is answered with an index scan, while `IN` with a range reads every record in the table. Without an index, both forms scan the table, but the comparisons can reject a record before it is decoded and the range cannot. Running `EXPLAIN` on each statement shows an `IndexScan` for the first and a `TableScan` for the second.

```surql
DEFINE INDEX person_age ON person FIELDS age;
EXPLAIN SELECT * FROM person WHERE age >= 18 AND age <= 65;
EXPLAIN SELECT * FROM person WHERE age IN 18..=65;
```

## Using parameters

Parameters can be used like variables to store a value which can then be used in a subsequent query.

More info on the `$parent` parameter in the second example can be seen on [the page for predefined variables](/docs/reference/query-language/language-primitives/parameters.md).

```surql
-- Setup
CREATE product:lamp SET name = 'Lamp', price = 40;
CREATE product:desk SET name = 'Desk', price = 200;
CREATE user:tobie SET name = 'Tobie';
CREATE events:launch SET host = user:tobie;

-- Store the subquery result in a variable and query that result.
LET $avg_price = (
	SELECT math::mean(price) AS avg_price FROM product GROUP ALL
).avg_price;

-- Find the name of the product where the price is higher than the avg price
SELECT name FROM product
WHERE [price] > $avg_price;

-- Use the parent instance's field in a subquery (predefined variable)
SELECT *, (SELECT * FROM events
  WHERE host == $parent.id) AS hosted_events FROM user;
```

## Skip certain fields using the `OMIT` clause

Sometimes, especially with tables containing numerous fields, it is desirable to select all fields except a few specific ones. The `OMIT` clause can be used in this case.

```surql
CREATE person:tobie SET
	name = 'Tobie',
	password = '123456',
	opts.security = 'secure',
	opts.enabled = true;
CREATE person:jaime SET
	name = 'Jaime',
	password = 'asdfgh',
	opts.security = 'secure',
	opts.enabled = false;

SELECT * FROM person;
-- Omit the password field and security field in the options object
SELECT * OMIT password, opts.security FROM person;

-- Using destructuring syntax
SELECT * OMIT password, opts.{ security, enabled } FROM person;
```

## Sort records using the `ORDER BY` clause

To sort records, SurrealDB allows ordering on multiple fields and nested fields. Use the `ORDER BY` clause to specify a comma-separated list of field names that should be used to order the resulting records. The `ASC` and `DESC` keywords can be used to specify whether results should be sorted in an ascending or descending manner. The `COLLATE` keyword can be used to use Unicode collation when ordering text in string values, ensuring that different cases, and different languages are sorted in a consistent manner. Finally, the `NUMERIC` can be used to correctly sort text which contains numeric values.

From SurrealDB 3.3, fields used only for sorting do not need to appear in the `SELECT` list. Sorting runs before projection, so the full record is available when the order keys are evaluated:

```surql
-- Setup
CREATE audit_log:1 SET event = 'login', subject = 'tobie', at = d'2026-01-01T09:00:00Z';
CREATE audit_log:2 SET event = 'logout', subject = 'tobie', at = d'2026-01-01T17:00:00Z';

-- Return only event and subject, ordered by a field that is not selected
SELECT event, subject FROM audit_log ORDER BY at DESC;
```

```surql
-- Setup
CREATE user:tobie, user:jaime;
CREATE song:1 SET artist = 'ABBA', rating = 4;
CREATE song:2 SET artist = 'ABBA', rating = 5;
CREATE song:3 SET artist = 'Queen', rating = 5;
CREATE article:1 SET title = 'Article 10';
CREATE article:2 SET title = 'Article 2';

-- Order records randomly
SELECT * FROM user ORDER BY rand();

-- Order records descending by a single field
SELECT * FROM song ORDER BY rating DESC;

-- Order records by multiple fields independently
SELECT * FROM song ORDER BY artist ASC, rating DESC;

-- Order text fields with Unicode collation
SELECT * FROM article ORDER BY title COLLATE ASC;

-- Order text fields with which include numeric values
SELECT * FROM article ORDER BY title NUMERIC ASC;
```

For more detail on collation, numeric ordering, and random order, see the [`ORDER` clause](/docs/reference/query-language/clauses/order.md).

### Ranking records

SurrealQL has no `RANK()` window function. To rank records, count the records that sort ahead of each one in a subquery, using `$parent` to refer to the outer record, and add one. Records with equal scores share a rank, and the rank after a tie is skipped, as in competition ranking (1, 1, 3, 4).

This works because a record's rank is defined by how many records beat it, not by its position in the output. For each record of the outer query, the subquery reads the whole `player` table again and keeps only the records whose score is strictly greater than `$parent.score`, the score of the record being ranked. If two records score higher, the record is third, so the rank is that count plus one. In the example below, Cai's score of 70 is beaten by Ana and Ben, so the subquery returns two records and Cai's rank is 3. Ana and Ben each find no higher score, so both get rank 1, and because the comparison is `>` rather than `>=`, neither counts the other. The `ORDER BY` clause only sorts the final output, so the ranks come out the same in any order.

The example under [Advanced expressions](#advanced-expressions) steps through a query of the same shape, with `$parent` inside a subquery, one value at a time.

```surql
CREATE player:1 SET name = 'Ana', score = 90;
CREATE player:2 SET name = 'Ben', score = 90;
CREATE player:3 SET name = 'Cai', score = 70;
CREATE player:4 SET name = 'Dee', score = 50;

SELECT name, score,
	(SELECT id FROM player WHERE score > $parent.score).len() + 1 AS rank
FROM player ORDER BY score DESC;
```

```surql title="Output"
[
	{ name: 'Ana', rank: 1, score: 90 },
	{ name: 'Ben', rank: 1, score: 90 },
	{ name: 'Cai', rank: 3, score: 70 },
	{ name: 'Dee', rank: 4, score: 50 }
]
```

For dense ranking, where the rank after a tie is the next number (1, 1, 2, 3), count the distinct higher scores instead:

```surql
-- Setup from the example above
CREATE player:1 SET name = 'Ana', score = 90;
CREATE player:2 SET name = 'Ben', score = 90;
CREATE player:3 SET name = 'Cai', score = 70;
CREATE player:4 SET name = 'Dee', score = 50;

SELECT name, score,
	(SELECT VALUE score FROM player WHERE score > $parent.score)
		.distinct().len() + 1 AS rank
FROM player ORDER BY score DESC;
```

```surql title="Output"
[
	{ name: 'Ana', rank: 1, score: 90 },
	{ name: 'Ben', rank: 1, score: 90 },
	{ name: 'Cai', rank: 2, score: 70 },
	{ name: 'Dee', rank: 3, score: 50 }
]
```

The subquery scans the table once for each record in the outer query, so this approach suits tables of modest size.

## The `LIMIT` clause

To limit the number of records returned, use the `LIMIT` clause.

```surql
-- Setup from the example above
CREATE person:tobie SET
	name.first = "Tobie",
	address = "1 Bagshot Row",
	email = "tobie@surrealdb.com";

-- Select only the top 50 records from the person table
SELECT * FROM person LIMIT 50;
```

When using the `LIMIT` clause, it is possible to paginate results by using the `START` clause to start from a specific record from the result set. The `START` count starts from 0.

```surql
-- Setup from the example above
CREATE user:tobie SET name = 'tobie';

-- Start at record 50 and select the following 50 records
SELECT * FROM user LIMIT 50 START 50;
```

The `LIMIT` clause followed by 1 is often used along with the `ONLY` clause to satisfy the requirement that only up to a single record can be returned.

```surql
-- Setup from the example above
CREATE person:jaime SET
	name = 'Jaime',
	password = 'asdfgh',
	opts.security = 'secure',
	opts.enabled = false;

-- Record IDs are unique so guaranteed to be no more than 1
SELECT * FROM ONLY person:jaime;

-- Returns an error when more than one record matches
SELECT * FROM ONLY person WHERE name = "Jaime";

-- Add `LIMIT 1` to ensure that only up to one record will be returned
SELECT * FROM ONLY person WHERE name = "Jaime" LIMIT 1;
```

```surql
-- Select the first 5 records from the array
SELECT * FROM [1,2,3,4,5,6,7,8,9,10] LIMIT 5 START 4; 
```

```surql title="Output"
[
	5,
	6,
	7,
	8,
	9
]
```

## The `ONLY` clause

If you are selecting just one single resource, it's possible to use the `ONLY` clause to filter that result from an array.

```surql
-- Setup
CREATE person:john SET name = 'John';

SELECT * FROM ONLY person:john;
```

If you are selecting from a resource where it is possible that multiple resources are returned, it is required to `LIMIT` the result to just one. This is needed because the query would otherwise not be deterministic.

```surql
-- Fails
SELECT * FROM ONLY table_name;
-- Succeeds
SELECT * FROM ONLY table_name LIMIT 1;
```

## More on using the `FROM` clause

The `FROM` clause can be used on targets beyond just a single table or record name.

```surql
-- Setup
CREATE user:tobie SET name = 'Tobie', admin = true, age = 36;
CREATE user:jaime SET name = 'Jaime', admin = false, age = 17;
CREATE user:admin SET name = 'Admin', admin = true, age = 40;
CREATE admin:root SET name = 'Root';
CREATE company:surrealdb SET name = 'SurrealDB';
CREATE person:lrym5gur8hzws72ux5fa SET name = 'Lena';

-- Selects all records from both 'user' and 'admin' tables.
SELECT * FROM user, admin;

-- Selects all records from the table named in the variable '$table',
-- but only if the 'admin' field of those records is true.
-- Equivalent to 'SELECT * FROM user WHERE admin = true'.
LET $table = "user";
SELECT * FROM type::table($table) WHERE admin = true;

-- Selects a single record from:
-- * the table named in the variable '$table',
-- * and the identifier named in the variable '$id'.
-- This query is equivalent to 'SELECT * FROM user:admin'.
LET $table = "user";
LET $id = "admin";
SELECT * FROM type::record($table, $id);

-- Selects all records for specific users 'tobie' and 'jaime',
-- as well as all records for the company 'surrealdb'.
SELECT * FROM user:tobie, user:jaime, company:surrealdb;

-- Selects from an array. The record ids are read as records,
-- and the number and the string are returned as they are.
SELECT * FROM [3648937, "test", person:lrym5gur8hzws72ux5fa, person:4luro9170uwcv1xrfvby];

-- Selects data from an object that includes a 'person' key,
-- which is associated with a specific person record, and an 'embedded' key set to true.
SELECT * FROM { person: person:lrym5gur8hzws72ux5fa, embedded: true };

-- This command first performs a subquery, which selects all 'user' records and adds a
-- computed 'adult' field that is true if the user's 'age' is 18 or older.
-- The main query then selects all records from this subquery where 'adult' is true.
SELECT * FROM (SELECT age >= 18 AS adult FROM user) WHERE adult = true;
```

A record id inside an array is read in the same way as a record id written directly in `FROM`, whether the array is written inline or held in a parameter, as in `SELECT * FROM $ids`. A record that exists comes back as an object, and a record that does not exist gives no result. Every other value in the array is returned as it is: a number, a string, an object, and also a string that looks like a record id. Before SurrealDB 3.1.0, the elements of an array held in a parameter were all returned as they were, and the records were not read.

```surql
CREATE item:1 SET name = 'lamp';
CREATE item:2 SET name = 'desk';

SELECT * FROM [item:1, item:404, 3, 'item:2', { a: 1 }];
```

```surql title="Output"
[
	{ id: item:1, name: 'lamp' },
	3,
	'item:2',
	{ a: 1 }
]
```

To keep every id in the array, including the ids of records that do not exist, use array methods instead of `SELECT`. To keep only the ids of records that exist, select the `id` of each one:

```surql
CREATE item:1 SET name = 'lamp';
LET $ids = [item:1, item:404];

$ids.map(|$id| { ref: $id });
//- [{ ref: item:1 }, { ref: item:404 }]

SELECT VALUE id FROM $ids;
//- [item:1]
```

> [!NOTE]
> A table name or a record range inside an array is returned as a value, and is not read. `SELECT VALUE $this FROM [item]` returns the table name itself as `[item]`, and `SELECT * FROM [item:1..4]` returns `[]`. Write a table or a range directly in `FROM`, as in `SELECT * FROM item:1..4`, to read its records.

SurrealQL has no `UNION` or `UNION ALL` keyword. Listing several tables in `FROM` returns the records of all of them and keeps duplicates, which is the result of `UNION ALL`. The results of two separate queries can be joined with [`array::concat()`](/docs/reference/query-language/functions/database-functions/array.md#arrayconcat) or the `+` operator. To remove duplicates, as `UNION` does, use [`array::union()`](/docs/reference/query-language/functions/database-functions/array.md#arrayunion):

```surql
CREATE user:tobie SET name = 'Tobie';
CREATE admin:jaime SET name = 'Jaime';
CREATE admin:tobie SET name = 'Tobie';

SELECT VALUE name FROM user, admin;
//- ['Tobie', 'Jaime', 'Tobie']

array::union((SELECT VALUE name FROM user), (SELECT VALUE name FROM admin));
//- ['Tobie', 'Jaime']
```

Every record belongs to a table, so a `SELECT` always names the tables that it reads from. To read the records of every table in the current database, take the table names from [`INFO FOR DB`](/docs/reference/query-language/statements/info.md) and select from each one. This reads every record in the database, so the time it takes grows with the size of the database.

```surql
CREATE person:aisha SET name = 'Aisha';
CREATE product:lamp SET price = 40;

(INFO FOR DB).tables.keys()
	.map(|$table| SELECT * FROM type::table($table))
	.flatten();
```

```surql title="Output"
[
	{ id: person:aisha, name: 'Aisha' },
	{ id: product:lamp, price: 40 }
]
```

## Record ranges

SurrealDB supports the ability to query a range of records, using the record ID. Record ID ranges retrieve records using the natural sorting order of the record IDs. These range queries can be used to query a range of records in a timeseries context. You can see more here about [array-based Record IDs](/docs/reference/query-language/language-primitives/data-types/record-ids.md#array-based-record-ids).

```surql
-- Setup
CREATE person:1, person:2;
CREATE temperature:['London', '2022-08-29T08:03:39'] SET celsius = 20;
CREATE temperature:['London', '2022-08-29T08:06:00'] SET celsius = 21;
CREATE temperature:['London', '2022-08-29T08:09:31'] SET celsius = 22;

-- Select all person records with IDs between the given range
SELECT * FROM person:1..1000;
-- Select all records for a particular location, inclusive
SELECT * FROM temperature:['London', NONE]..=['London', time::now()];
-- Select all temperature records with IDs less than a maximum value
SELECT * FROM temperature:..['London', '2022-08-29T08:09:31'];
-- Select all temperature records with IDs greater than a minimum value
SELECT * FROM temperature:['London', '2022-08-29T08:03:39']..;
-- Select all temperature records with IDs between the specified range
SELECT * FROM temperature:['London', '2022-08-29T08:03:39']..['London', '2022-08-29T08:09:31'];
```

Using a record range is more performant than the `WHERE` clause, as it does not require a table scan.

```surql
-- Create 5000 `person` records
CREATE |person:1..=5000| RETURN NONE;

-- Set the starting time
LET $now = time::now();
-- Put the output somewhere so it won't clutter the screen
LET $_ = SELECT * FROM person:1..=5000;
-- Get the elapsed time
LET $time1 = time::now() - $now;

LET $now = time::now();
LET $_ = SELECT * FROM person WHERE id >= person:1 AND id <= person:5000;
LET $time2 = time::now() - $now;
RETURN [$time1, $time2];
```

## The `GROUP BY` and `GROUP ALL` clause

SurrealDB supports data aggregation and grouping, with support for multiple fields, nested fields, and aggregate functions. In SurrealDB, every field which appears in the field projections of the select statement (and which is not an aggregate function), must also be present in the [`GROUP BY`](/docs/reference/query-language/clauses/group.md) clause.

```surql
-- Setup
CREATE user:1 SET country = 'UK';
CREATE user:2 SET country = 'UK';
CREATE user:3 SET country = 'France';
CREATE article:1 SET settings.published = true, tags = ['rust', 'database'];
CREATE article:2 SET settings.published = false, tags = ['database', 'graph'];
CREATE person:1 SET gender = 'F', country = 'UK', city = 'London';
CREATE person:2 SET gender = 'M', country = 'UK', city = 'London';

-- Group records by a single field
SELECT country FROM user GROUP BY country;

-- Group results by a nested field
SELECT settings.published FROM article GROUP BY settings.published;

-- Group results by multiple fields
SELECT gender, country, city FROM person GROUP BY gender, country, city;

-- Use an aggregate function to select unique values from a nested array across an entire table
SELECT array::group(tags) AS tags FROM article GROUP ALL;
```

A longer example of grouping using aggregate functions:

```surql
INSERT INTO person [
    { gender: "M", age: 20, country: "Japan" },
    { gender: "M", age: 25, country: "Japan" },
    { gender: "F", age: 23, country: "US" },
    { gender: "F", age: 30, country: "US" },
    { gender: "F", age: 25, country: "Korea" },
    { gender: "F", age: 45, country: "UK" },
];

SELECT
	count() AS total,
	math::mean(age) AS average_age,
	gender,
	country
FROM person
GROUP BY gender, country;

-- Get the total number of records in a table
SELECT count() AS number_of_records FROM person GROUP ALL;
```

```surql title="Output"
-------- Query --------

[
	{
		average_age: 25,
		country: 'Korea',
		gender: 'F',
		total: 1
	},
	{
		average_age: 45,
		country: 'UK',
		gender: 'F',
		total: 1
	},
	{
		average_age: 26,
		country: 'US',
		gender: 'F',
		total: 2
	},
	{
		average_age: 22,
		country: 'Japan',
		gender: 'M',
		total: 2
	}
]

-------- Query --------

[
	{
		number_of_records: 6
	}
]
```

To return the most recently modified record per group instead of aggregate totals, see [Latest record per group](/docs/learn/querying/concepts-and-guides/subqueries-and-advanced-patterns.md#latest-record-per-group).

To count the values of several fields across a set of search results at once, such as the brands and tags of matching products, see [Counts for search filters (facets)](/docs/learn/querying/concepts-and-guides/subqueries-and-advanced-patterns.md#counts-for-search-filters-facets).

### `GROUP` and `SPLIT` incompatibility

The `GROUP` and `SPLIT` clauses are incompatible with each other due to opposing behaviour: while `SPLIT` is a post-processing clause that multiplies the output of a query, `GROUP` works in the other way by collapsing the output.

Versions before 3.0.0 allowed these two clauses to be used together, after which attempting to do so results in a parsing error.

```surql notest
SELECT * FROM person SPLIT name GROUP BY name;
```

```surql title="Output"
'Parse error: SPLIT and GROUP are mutually exclusive
 --> [6:22]
  |
6 | SELECT * FROM person SPLIT name GROUP BY name;
  |                      ^^^^^^^^^^ SPLIT cannot be used with GROUP
 --> [6:33]
  |
6 | SELECT * FROM person SPLIT name GROUP BY name;
  |                                 ^^^^^^^^^^^^^ GROUP cannot be used with SPLIT
'
```

Disallowing the two clauses together forces a query that uses both to have one inside a subquery, which makes it clear which operation is to be performed first.

```surql
CREATE user SET
    name = "Jack",
    emails = ["my@firstemail.com", "another@builder.com"],
    age = 37;

CREATE user SET
    name = "Ellen",
    emails = ["ruler@forest.com", "wife@tom.com"],
    age = 50;

CREATE user SET
    name = "Phillip",
    emails = ["prior@kingsbridge.com", "boss@remigius.com"],
    age = 50;

SELECT age, emails FROM (SELECT * FROM user SPLIT emails) GROUP BY age;

SELECT age, emails
FROM (
  SELECT age, array::group(emails) AS emails
  FROM user
  GROUP BY age
)
SPLIT emails;
```

### Using a `COUNT` index to speed up `count()` in `GROUP ALL` queries

_(since v3.0.0)_

To speed up the `count()` function along with `GROUP ALL` to get the total number of records in a table, a `COUNT` index can be used. This keeps track of the total number of records as a single value as opposed to a dynamic iteration of the table to get the full count every time a query is run.

```surql
DEFINE INDEX person_count ON person COUNT;
SELECT count() AS number_of_records FROM person GROUP ALL;
```

### `math::stddev()` and `math::variance()` in table views

_(since v3.0.0)_

The `math::stddev()` and `math::variance()` functions can also be used in table views.

```surql
DEFINE TABLE person SCHEMALESS;
DEFINE TABLE person_stats AS
	SELECT
		count(),
		age,
		math::stddev(score) AS score_stddev,
		math::variance(score) AS score_variance
	FROM person
	GROUP BY age;

INSERT INTO person [
    { id: person:alice,          age: 25, score: 80 },
    { id: person:alices_rival,   age: 25, score: 88 },
    { id: person:bob,            age: 24, score: 90 },
    { id: person:bobs_rival,     age: 24, score: 99 },
    { id: person:charlie,        age: 23, score: 70 },
    { id: person:charlies_rival, age: 23, score: 77 }
];

SELECT * FROM person_stats WHERE age >= 24;
```

Output:

```surql
[
	{
		age: 24,
		count: 2,
		id: person_stats:[
			24
		],
		score_stddev: 6.363961030678927719607599259dec,
		score_variance: 40.50dec
	},
	{
		age: 25,
		count: 2,
		id: person_stats:[
			25
		],
		score_stddev: 5.656854249492380195206754897dec,
		score_variance: 32dec
	}
]
```

## The `SPLIT` clause

As SurrealDB supports arrays and nested fields within arrays, it is possible to use the [`SPLIT`](/docs/reference/query-language/clauses/split.md) clause to split the result on a specific field name, returning each value in an array as a separate value, along with the record content itself. This is useful in data analysis contexts.

```surql
CREATE user SET
    name = "Name",
    emails = ["me@me.com", "longer_email@other_service.com"];

-- Split the results by each value in an array
SELECT * FROM user SPLIT emails;
```

```surql title="Output"
[
	{
		emails: 'me@me.com',
		id: user:tr5sxe8iygdco05faoh0,
		name: 'Name'
	},
	{
		emails: 'longer_email@other_service.com',
		id: user:tr5sxe8iygdco05faoh0,
		name: 'Name'
	}
]
```

Other examples using the `SPLIT` clause:

```surql
-- Setup
CREATE country:uk SET locations.cities = ['London', 'Leeds', 'Edinburgh'];
CREATE person:tobie SET loggedin = ['2023-04-20', '2023-05-12'];

-- Split the results by each value in a nested array
SELECT * FROM country SPLIT locations.cities;

-- Filter the result of a subquery
SELECT * FROM (SELECT * FROM person SPLIT loggedin)
  WHERE loggedin > '2023-05-01';
```

## Connect targets using the FETCH clause

SurrealDB can connect records through [record links](/docs/reference/query-language/language-primitives/record-links.md) and [graph connections](/docs/reference/query-language/statements/relate.md).

Instead of pulling data from multiple tables and merging that data together, SurrealDB allows you to traverse related records efficiently without needing to use JOINs.

To fetch and replace records with the remote record data, use the [`FETCH`](/docs/reference/query-language/clauses/fetch.md) clause to specify the fields and nested fields which should be fetched in-place, and returned in the final statement response output.

```surql
-- Setup
CREATE artist:abba SET name = 'ABBA', email = 'abba@example.com';
CREATE review:one SET rating = 5, artist = artist:abba;
CREATE author:jane SET name = 'Jane', age = 28;
CREATE article:one SET title = 'Hello', author = author:jane;

-- Select all the review information
-- and the artist's email from the artist table
SELECT *, artist.email FROM review FETCH artist;

-- Select all the article information
-- only if the author's age (from the author table) is under 30.
SELECT * FROM article WHERE author.age < 30 FETCH author;
```

## Selecting inside graph queries

A `SELECT` statement and/or its clauses can be used inside graph queries as well at the graph edge portion of the query.

```surql
-- Note: 1..4 used to be inclusive until SurrealDB 3.0.0
-- Now creates 1 up to but not including 4
CREATE |person:1..4|;

RELATE person:1->likes->person:2 SET like_strength = 20, know_in_person = true;
RELATE person:1->likes->person:3 SET like_strength = 5,  know_in_person = false;
RELATE person:2->likes->person:1 SET like_strength = 10, know_in_person = true;
RELATE person:2->likes->person:3 SET like_strength = 12, know_in_person = false;
RELATE person:3->likes->person:1 SET like_strength = 2,  know_in_person = false;
RELATE person:3->likes->person:2 SET like_strength = 9,  know_in_person = false;

SELECT ->likes AS likes FROM person;
SELECT ->(SELECT like_strength FROM likes) AS likes FROM person;
SELECT ->(SELECT like_strength FROM likes
  WHERE like_strength > 10) AS likes FROM person;
SELECT ->(likes WHERE like_strength > 10) AS likes FROM person;
SELECT ->(SELECT like_strength, know_in_person
  FROM likes ORDER BY like_strength DESC) AS likes
  FROM person;
SELECT ->(SELECT count() as count, know_in_person
  FROM likes GROUP BY know_in_person) AS likes
  FROM person;
SELECT ->(likes LIMIT 1) AS likes FROM person;
SELECT ->(likes START 1) AS likes FROM person;
```

For more examples, see the [graph clauses](/docs/reference/query-language/statements/relate.md#graph-clauses) section of the page on the `RELATE` statement.

## The `WITH` clause

The query planner can replace the standard table iterator with one or several index iterators based on the structure and requirements of the query. However, there may be situations where manual control over these potential optimizations is desired or required.

For instance, the cardinality of an index can be high, potentially even equal to the number of records in the table. The sum of the records iterated by several indexes may end up being larger than the number of records obtained by iterating over the table. In such cases, if there are different index possibilities, the most probable optimal choice would be to use the index known with the lowest cardinality.

- `WITH INDEX @indexes ...` restricts the query planner to using only the specified index(es)
- `WITH NOINDEX` forces the query planner to use the table iterator.

```surql
-- Setup
DEFINE INDEX ft_email ON person FIELDS email;
CREATE person:tobie SET name = 'Tobie', email = 'tobie@surrealdb.com', company = 'SurrealDB', job = 'engineer', gender = 'm';
CREATE person:jaime SET name = 'Jaime', email = 'jaime@surrealdb.com', company = 'SurrealDB', job = 'founder', gender = 'm';

-- forces the query planner to use the specified index(es):
SELECT * FROM person
WITH INDEX ft_email
WHERE
	email = 'tobie@surrealdb.com' AND
	company = 'SurrealDB';

-- forces the usage of the table iterator
SELECT name FROM person WITH NOINDEX WHERE job = 'engineer'
  AND gender = 'm';
```

## The `EXPLAIN` clause

When `EXPLAIN` is added, the `SELECT` statement returns its execution plan instead of its result. The plan is a tree of operators: an `IndexScan` reads the records through an index, and a `TableScan` reads every record in the table. `EXPLAIN FULL` also runs the query and adds `metrics` to each operator, such as the number of rows it produced.

```surql
DEFINE INDEX fast_email ON TABLE person FIELDS email;
CREATE person:tobie SET email = "tobie@surrealdb.com";

SELECT * FROM person WHERE email = 'tobie@surrealdb.com' EXPLAIN;
```

```surql title="Output"
{
	attributes: {
		projections: '*'
	},
	children: [
		{
			attributes: {
				access: "= 'tobie@surrealdb.com'",
				direction: 'Forward',
				index: 'fast_email',
				table: 'person'
			},
			context: 'Db',
			operator: 'IndexScan'
		}
	],
	context: 'Db',
	operator: 'SelectProject'
}
```

The [`EXPLAIN` clause](/docs/reference/query-language/clauses/explain.md) page shows the plan with and without an index, and the output of `EXPLAIN FULL`.

## The `TIMEOUT` clause

When processing a large result set with many interconnected records, it is possible to use the `TIMEOUT` keyword to specify a timeout duration for the statement. If the statement continues beyond this duration, then the transaction will fail, and the statement will return an error.

```surql
-- Setup from the example above
CREATE person:tobie SET
	name.first = "Tobie",
	address = "1 Bagshot Row",
	email = "tobie@surrealdb.com";

-- Cancel this conditional filtering based on graph edge properties
-- if it's not finished within 5 seconds
SELECT * FROM person
  WHERE ->knows->person->(knows
  WHERE influencer = true) TIMEOUT 5s;
```

## The `TEMPFILES` clause

When processing a large result set with many records, it is possible to use the `TEMPFILES` clause to specify that the statement should be processed in temporary files rather than memory.

This significantly reduces memory usage in exchange for slower performance.

```surql
-- Setup from the example above
CREATE person:tobie SET
	name.first = "Tobie",
	address = "1 Bagshot Row",
	email = "tobie@surrealdb.com";

-- Select every person and order them by name using temporary files rather than memory.
SELECT * FROM person ORDER BY name TEMPFILES;
```

This requires the temporary directory to be set in the server configuration or when using the [`surreal db start`](/docs/reference/cli/db/commands/start.md) command.

From SurrealDB 4.0, sorts, grouped aggregates, `DISTINCT` and join builds spill to temporary files by memory budget without `TEMPFILES`, and the temporary directory defaults to a `surrealdb` folder in the system temporary directory. See [Memory limits and spilling to disk](/docs/reference/cli/db/environment-variables.md#memory-limits-and-spilling-to-disk) for the limits that control this.

## The `VERSION` clause

If you are using a storage engine that supports versioning (SurrealKV) with versioning enabled, write operations on a table will track the state of each record at the time at which the operation was performed.

You can then perform time-travel queries that query the state of a table at a specific point in time by using the `VERSION` clause in a `SELECT` query.

This clause can be used on startup by adding `versioned=true` to the [datastore configuration parameters](/docs/reference/cli/db/commands/start.md#datastore-configuration) when executing the `surreal db start` command.

```bash title="Examples of surreal db start with versioning enabled"
# Start with a versioned SurrealKV datastore with a root user
surreal db start --user root --pass secret "surrealkv://my_kv_db?versioned=true"

# Or disable authentication for quick anonymous access
surreal db start --unauthenticated "surrealkv://my_kv_db?versioned=true"
```

The in-memory SurrealMX backend does not support versioned queries. From 3.3.0 it refuses `versioned=true` and a non-zero `retention` at startup, and a `VERSION` clause sent to it returns an error saying that the underlying datastore does not support versioned queries.

The `VERSION` clause is always followed by a [datetime](/docs/reference/query-language/language-primitives/data-types/datetimes.md). When the specified timestamp does not exist, an empty array is returned.

```surql
CREATE user:john SET name = 'John';

-- user:john did not exist two days ago, returns empty array
SELECT * FROM user:john VERSION time::now() - 2d;

-- Slee for five seconds
SLEEP 5s;

-- Returns user:john as the record existed three seconds ago
SELECT * FROM user:john VERSION time::now() - 3s;
```

The `VERSION` clause can be used via other dynamic expressions such as functions as long as they resolve to a datetime.

```surql
DEFINE FUNCTION fn::yesterday() -> datetime { time::now() - 1d };

CREATE user:john SET name = 'John';

SELECT * FROM user VERSION fn::yesterday();
```

## The `FOR UPDATE` clause

_(since v3.3.0)_

Inside a transaction, a plain `SELECT` reads a consistent [snapshot](/docs/learn/querying/concepts-and-guides/transactions.md#snapshot-isolation), but the transaction can still commit successfully even if the records it read were modified by another transaction in the meantime. When later writes depend on a value that was only read, this allows the transaction to commit decisions based on stale data.

The `FOR UPDATE` clause registers each selected record for commit-time conflict detection: the enclosing transaction will only commit if none of those records were modified by another transaction after the snapshot was taken. If a concurrent modification is detected, `COMMIT` fails with a transaction conflict error, and the transaction can be retried.

```surql
-- Setup
CREATE account:one SET status = "active";

BEGIN;

-- Read the account purely as a decision input; it is not written below
LET $account = SELECT * FROM ONLY account:one FOR UPDATE;

IF $account.status = "active" {
    CREATE order SET account = account:one, item = "widget";
};

-- Fails with a retryable conflict error if another transaction
-- modified account:one after this transaction's snapshot
COMMIT;
```

The clause takes no lock, and no transaction waits on another. A concurrent transaction can write a registered record and commit normally; the conflict surfaces on the transaction that read the record, whose `COMMIT` then fails. Where `SELECT ... FOR UPDATE` holds a row lock in other databases, here it adds a check, so plan for retries rather than for waiting.

`FOR UPDATE` is only needed for records that are read as decision inputs but never written within the transaction. A record that the transaction also writes is already protected, because the write itself is checked for conflicts at commit time.

The `FOR UPDATE` clause requires record ids as targets, and each selected record is protected individually. It does not lock tables, ranges, or query predicates, so it does not prevent new matching records from being created by concurrent transactions.

A target can be named literally or passed through a parameter, so `SELECT * FROM $record FOR UPDATE` behaves the same as naming the record id inline, as long as the parameter holds a record id rather than a table.

Reading a record id that does not exist registers that id too, so a concurrent transaction that creates it also causes this transaction's commit to fail. This is what makes the clause suitable for guarding a get-or-create path, where the decision rests on a record being absent.

The clause cannot be combined with the `VERSION`, `GROUP`, or `SPLIT` clauses, nor with `LIMIT` across multiple targets, and it cannot be used with targets other than record ids.

Because the conflict registration is only validated at commit time, `FOR UPDATE` needs a transaction that commits. A read nested inside an expression is accommodated by promoting the enclosing statement to a write, so the registration still reaches a committing transaction. A read-only transaction has no commit to validate against, and rejects the clause.

## Learn more

This explainer video covers selecting across document-style relationships, including record links and nested data:

[Watch on YouTube](https://www.youtube.com/watch?v=TyX45cyZ-W0)

---

Source: https://surrealdb.com/docs/reference/query-language/statements/show

# SHOW

The SHOW statement can be used to replay changes made to a table.

Changefeeds allow you to retrieve and sync changes from SurrealDB to external systems and platforms using the `SHOW` statement.

For updates to existing records, the shape of each mutation depends on how the changefeed was defined on the table. When you use [`INCLUDE ORIGINAL`](/docs/reference/query-language/statements/define/table.md#example-usage) with `CHANGEFEED`, stored differences are **reverse diffs**: they describe the changes required to go from the record’s state after the write **back** to the state immediately before it. See the [`DEFINE TABLE`](/docs/reference/query-language/statements/define/table.md#example-usage) examples for sample responses with and without `INCLUDE ORIGINAL`.

## Requirements

* You must first [`DEFINE`](/docs/reference/query-language/statements/define/table.md#example-usage) a changefeed on either a table or a database.
* You must be signed in as a system user with the `VIEWER` role or higher, at the database level or above. A record user who runs `SHOW CHANGES` gets the error `IAM error: Not enough permissions to perform this action`.

### Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
SHOW CHANGES FOR TABLE @tablename
	SINCE @timestamp | @versionstamp
	[ LIMIT @number ]
```

## Example usage

### Basic usage

The following expression shows usage of the SHOW statement.

```surql
-- Define the changefeed and its duration
DEFINE TABLE reading CHANGEFEED 3d;

-- Create some records in the reading table
CREATE reading SET story += ["Once upon a time"];
UPDATE reading SET story += ["there was a database"];

-- Replay changes to the reading table since a date
SHOW CHANGES FOR TABLE reading SINCE d"2023-09-07T01:23:52Z" LIMIT 10;
-- Replay changes to the reading table since a versionstamp
SHOW CHANGES FOR TABLE reading SINCE 1 LIMIT 10;
```

Assuming the datetime above matches with the one when the changefeed was established, the response for both queries will be as follows.

```surql title="Output"
[
	{
		changes: [
			{
				define_table: {
					changefeed: {
						expiry: 3d,
						original: false
					},
					drop: false,
					id: 0,
					kind: {
						kind: 'ANY'
					},
					name: 'reading',
					permissions: {
						create: false,
						delete: false,
						select: false,
						update: false
					},
					schemafull: false
				}
			}
		],
		versionstamp: 116395873313095680
	},
	{
		changes: [
			{
				update: {
					id: reading:kpqxnt8h4me84zed9fgf,
					story: [
						'Once upon a time'
					]
				}
			}
		],
		versionstamp: 116395873313161216
	},
	{
		changes: [
			{
				update: {
					id: reading:kpqxnt8h4me84zed9fgf,
					story: [
						'Once upon a time',
						'there was a database'
					]
				}
			}
		],
		versionstamp: 116395873313161217
	}
]
```

```surql title="Output if INCLUDE ORIGINAL set on changefeed"
[
	{
		changes: [
			{
				define_table: {
					changefeed: {
						expiry: 3d,
						original: true
					},
					drop: false,
					id: 0,
					kind: {
						kind: 'ANY'
					},
					name: 'reading',
					permissions: {
						create: false,
						delete: false,
						select: false,
						update: false
					},
					schemafull: false
				}
			}
		],
		versionstamp: 116395871166398464
	},
	{
		changes: [
			{
				update: {
					id: reading:q0lovlass9zgq19l1kfb,
					story: [
						'Once upon a time, '
					]
				}
			}
		],
		versionstamp: 116395871166464000
	},
	{
		changes: [
			{
				current: {
					id: reading:q0lovlass9zgq19l1kfb,
					story: [
						'Once upon a time, ',
						'there was a database'
					]
				},
				update: [
					{
						op: 'remove',
						path: '/story/1'
					}
				]
			}
		],
		versionstamp: 116395871166529536
	}
]
```

The changefeed is a log of the table's changes in versionstamp order. It keeps recording for as long as the table defines it, and each change is kept for the duration that `CHANGEFEED` sets, counted from when the change was written. A background clean-up deletes older changes, so a change can stay readable for a short time past that duration. Where a database and its tables set different durations, the longest one applies to every changefeed in the database. `SHOW CHANGES` reads the log from the point that `SINCE` names:

<img src="~/assets/img/diagrams/light/changefeed-log-light.webp" darkSrc="~/assets/img/diagrams/changefeed-log.webp" alt="The changefeed of the reading table, kept for 3 days. Entries older than 3 days are deleted by a periodic clean-up. Three entries remain in versionstamp order: define_table, then an update setting story to ['Once upon a time'], then an update adding 'there was a database'. SHOW CHANGES FOR TABLE reading SINCE 1 LIMIT 10 reads them from the oldest onwards." />

### Deletes with `INCLUDE ORIGINAL`

_(since v3.2.0)_

When a table changefeed is defined with `INCLUDE ORIGINAL`, delete events surface the record's pre-image under `delete.original`. Plain changefeeds (without `INCLUDE ORIGINAL`) still emit `{ delete: { id } }` only.

```surql
DEFINE TABLE original_tb CHANGEFEED 1h INCLUDE ORIGINAL;
CREATE original_tb:1 SET name = 'Tobie';
DELETE original_tb:1;
SHOW CHANGES FOR TABLE original_tb SINCE 0;
```

```surql title="Output"
[
	{
		changes: [
			{
				delete: {
					id: original_tb:1,
					original: {
						id: original_tb:1,
						name: 'Tobie'
					}
				}
			}
		],
		versionstamp: /* … */
	}
]
```

Note the following when working with the versionstamps of a changefeed:

* Changefeeds defined on tables are implemented via a single `CHANGEFEED` on the database level. As such, `SHOW CHANGES FOR TABLE sometable` will only show versionstamps in sequential order if `sometable` is the database's only table.
* The `versionstamp` output above is due to an extra two bytes needed for more detailed ordering in the FoundationDB distributed [SurrealDB backend](/docs/learn/data-models/architecture.md). To turn these versionstamps into a normal sequence of numbers, a right shift of sixteen bits (`>> 16`) can be used.
* A `SINCE <number` greater than the current sequential number will return an empty array.
* `SINCE <time>` needs to be a datetime after which the `CHANGEFEED` was defined.

Versionstamps carry the following two guarantees:

* Versionstamps monotonically increase.
* Versionstamp format is universal across various backends.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/sleep

# SLEEP

The SLEEP statement is used to introduce a delay or pause in the execution of a query or a batch of queries for a specific amount of time.

The `SLEEP` statement is used to introduce a delay or pause in the execution of a query or a batch of queries for a specific amount of time.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
SLEEP @duration;
```

## Example usage

The following query shows example usage of this statement.

```surql
-- Sleep one second
SLEEP 1s;
-- Sleep 100 milliseconds
SLEEP 100ms;
```

For more dynamic usage of sleep, see SurrealDB's [sleep](/docs/reference/query-language/functions/database-functions/sleep.md) function.

## SLEEP during parallel operations

A `SLEEP` statement does not interfere with operations that are underway in the background, such as a [`DEFINE INDEX`](/docs/reference/query-language/statements/define/indexes.md) statement using the `CONCURRENTLY` clause.

```surql
CREATE |user:1..=50000| RETURN NONE;
UPDATE user SET name = id.id() RETURN NONE;
DEFINE INDEX unique_name ON TABLE user FIELDS name UNIQUE CONCURRENTLY;
INFO FOR INDEX unique_name ON TABLE user;
SLEEP 50ms;
INFO FOR INDEX unique_name ON TABLE user;
SLEEP 50ms;
INFO FOR INDEX unique_name ON TABLE user;
SLEEP 50ms;
INFO FOR INDEX unique_name ON TABLE user;
```

```surql title="Possible output"
-------- Query 1 --------
{
	building: {
		active: false,
		armed_shards: 0,
		compacting: false,
		queued: false,
		status: 'started'
	}
}

-------- Query 2 --------
{
	building: {
		active: false,
		armed_shards: 0,
		compacting: false,
		initial: 9016,
		pending: 0,
		queued: false,
		status: 'indexing'
	}
}

-------- Query 3 --------
{
	building: {
		active: false,
		armed_shards: 0,
		compacting: false,
		initial: 17266,
		pending: 0,
		queued: false,
		status: 'indexing'
	}
}

-------- Query 4 --------
{
	building: {
		active: false,
		armed_shards: 0,
		compacting: false,
		initial: 25766,
		pending: 0,
		queued: false,
		status: 'indexing'
	}
}
```

## Use cases

`SLEEP` can be useful in a small number of situations, such as:

* Testing and debugging: can be used to understand how concurrent transactions interact, test how systems handle timeouts and delays, simulate behaviour in more distant regions with longer latency
* Throttling: can be used to throttle the execution of operations to prevent the database from being overwhelmed by too many requests at once
* Security measures: can be used to slow down the response rate of login attempts to mitigate the risk of brute force attacks

---

Source: https://surrealdb.com/docs/reference/query-language/statements/throw

# THROW

The THROW statement can be used to stop execution of a query and return information on the underlying problem

The `THROW` statement can be used to throw an error in a place where something unexpected is happening. Execution of the query will be aborted and the error will be returned to the client. While a string is most commonly seen after a `THROW` statement, any [value](/docs/reference/query-language/language-primitives/data-types/values.md) at all can be used as error output.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
THROW @error
```

## Example usage

The following query shows example usage of this statement.

```surql
-- Throw an error
THROW "some error message";
```
The following query shows the `THROW` statement being used to send back a custom error to the client.

```surql
-- In this example, we throw a custom error when a user provides invalid signin details
DEFINE ACCESS user ON DATABASE TYPE RECORD
	SIGNIN {
		LET $user = (SELECT * FROM user WHERE username = $username
		  AND crypto::argon2::compare(password, $password));
		IF !$user {
			THROW "You either provided invalid credentials, or a user with the username " + <string> $username + " might not exist.";
		};

		RETURN $user;
	}
	DURATION FOR SESSION 1w
;
```

`THROW` can contain any value: arrays, objects, and so on. It can even take the value of a separate `SELECT` statement:

```surql
CREATE event:one SET time = d'2025-10-08T07:15:04.994633Z';
CREATE event:two SET time = d'2025-10-08T07:15:04.996995Z';
THROW SELECT * FROM event;
```

```surql title="Output"
"An error occurred: [{ id: event:one, time: d'2025-10-08T07:15:04.994633Z' }, { id: event:two, time: d'2025-10-08T07:15:04.996995Z' }]"
```

`THROW` can also be used to cancel a transaction, usually inside an `IF` statement checking a condition.

```surql
BEGIN TRANSACTION;
LET $transfer_amount = 150;
CREATE account:one SET dollars =  100;
CREATE account:two SET dollars =  100;
UPDATE account:one SET dollars -= $transfer_amount;
UPDATE account:two SET dollars += $transfer_amount;
IF account:one.dollars < 0 {
    THROW "Insufficient funds, would have $" + <string>account:one.dollars + " after transfer"
};
COMMIT TRANSACTION;
SELECT * FROM account;
```

```surql title="Output when $transfer_amount set to 150"
'An error occurred: Insufficient funds, would have $-50 after transfer'
```

```surql title="Output when $transfer_amount set to 50"
[
	{
		dollars: 50,
		id: account:one
	},
	{
		dollars: 150,
		id: account:two
	}
]
```

A `THROW` placed inside an expression also shows whether that expression is evaluated at all, such as a computed field or a branch of a function. See [Checking whether an expression runs](/docs/learn/querying/concepts-and-guides/error-handling.md#checking-whether-an-expression-runs).

---

Source: https://surrealdb.com/docs/reference/query-language/statements/update

# UPDATE

The UPDATE statement can be used to update records in the database. If they already exist, they will be updated. If they do not exist, no records will be updated.

The `UPDATE` statement can be used to update existing records in the database. If the record does not exist, the statement will succeed but no records will be updated. To compare it with the other statements that write records, see [Writing records that may already exist](/docs/reference/query-language/statements/overview.md#writing-records-that-may-already-exist).

> [!NOTE]
> This statement can not be used to create graph relationships. For that, use the [`RELATE`](/docs/reference/query-language/statements/relate.md) or [`INSERT`](/docs/reference/query-language/statements/insert.md) statement.

> [!NOTE]
> `UPDATE` does not create records that do not exist. To update a record and create it if it does not exist, use the [`UPSERT`](/docs/reference/query-language/statements/upsert.md) statement.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
UPDATE [ ONLY ] @targets
	[ CONTENT @value
	  | MERGE @value
	  | PATCH @value
	  | REPLACE @value
	  | [ SET @field = @value, ... | UNSET @field, ... ]
	]
	[ WHERE @condition ]
	[ RETURN NONE | RETURN BEFORE | RETURN AFTER | RETURN DIFF
	  | RETURN @statement_param, ... | RETURN VALUE @statement_param ]
	[ TIMEOUT @duration ]
	[ EXPLAIN [ FULL ]]
;
```

> [!NOTE]
> `@target` refers to either record output including an `id` field, or a [record ID](/docs/reference/query-language/language-primitives/data-types/record-ids.md) on its own.

## Example usage

The examples below show how to use the `UPDATE` statement. They start by creating two `person` records with the [`CREATE`](/docs/reference/query-language/statements/create.md) statement so that the examples produce meaningful output.

```surql
-- Create a Schemaless person table with a random id
CREATE person CONTENT {
    name: 'John',
    company: 'SurrealDB Studio',
    skills: ['JavaScript', 'Go' , 'SurrealQL']
};

-- Create another person with a specific id
CREATE person:tobie CONTENT {
    name: 'Tobie',
    company: 'SurrealDB',
    skills: ['JavaScript', 'Go' , 'SurrealQL']
};
```

Suppose we want to update the `person` table with a new field `enjoys` (an array), a new skill `breathing` to the existing `skills` field (another array), add a new numeric field called `dollars`, and a `last_name` field that relies on the existing `name` field to set its value.

To do this we would use the following query.

```surql
-- Setup from the example above
CREATE person CONTENT {
    name: 'John',
    company: 'SurrealDB Studio',
    skills: ['JavaScript', 'Go' , 'SurrealQL']
};
CREATE person:tobie CONTENT {
    name: 'Tobie',
    company: 'SurrealDB',
    skills: ['JavaScript', 'Go' , 'SurrealQL']
};

-- Update all records in a table
-- The `enjoys` field will also be an array.
-- The += operator alone is enough to infer the type
UPDATE person SET 
	dollars = 50,
	skills += 'breathing',
	enjoys += 'reading',
	full_name = name + ' Mc' + name + 'erson';
```

```surql title="Output"
[
	{
		company: 'SurrealDB Studio',
		dollars: 50,
		enjoys: [
			'reading'
		],
		full_name: 'John McJohnerson',
		id: person:j1qov2pxey3p8s6hqlev,
		name: 'John',
		skills: [
			'JavaScript',
			'Go',
			'SurrealQL',
			'breathing'
		]
	},
	{
		company: 'SurrealDB',
		dollars: 50,
		enjoys: [
			'reading'
		],
		full_name: 'Tobie McTobieerson',
		id: person:tobie,
		name: 'Tobie',
		skills: [
			'JavaScript',
			'Go',
			'SurrealQL',
			'breathing'
		]
	}
]
```

For more specific updates, you can specify a record ID to update a single record. The following query will update the record with the ID `person:tobie` to add "Rust" as a skill.

```surql
-- Setup from the examples above
CREATE person:tobie CONTENT {
    name: 'Tobie',
    company: 'SurrealDB',
    skills: ['JavaScript', 'Go' , 'SurrealQL']
};
UPDATE person SET 
	dollars = 50,
	skills += 'breathing',
	enjoys += 'reading',
	full_name = name + ' Mc' + name + 'erson';

-- Update a record with a specific string id to add a new skill: 'Rust'
UPDATE person:tobie SET skills += 'Rust';
```

```surql title="Output"
[
	{
		company: 'SurrealDB',
		dollars: 50,
		enjoys: [
			'reading'
		],
		full_name: 'Tobie McTobieerson',
		id: person:tobie,
		name: 'Tobie',
		skills: [
			'JavaScript',
			'Go',
			'SurrealQL',
			'breathing',
			'Rust'
		]
	}
]
```

The `-=` operator can be used to remove an item from an array or reduce a numeric value by a certain value.

```surql
-- Setup from the examples above
CREATE person:tobie CONTENT {
    name: 'Tobie',
    company: 'SurrealDB',
    skills: ['JavaScript', 'Go' , 'SurrealQL']
};
UPDATE person SET 
	dollars = 50,
	skills += 'breathing',
	enjoys += 'reading',
	full_name = name + ' Mc' + name + 'erson';
UPDATE person:tobie SET skills += 'Rust';

UPDATE person:tobie SET 
	skills -= 'Go', 
	dollars -= 1;
```

```surql title="Output"
[
	{
		company: 'SurrealDB',
		dollars: 49,
		enjoys: [
			'reading'
		],
		full_name: 'Tobie McTobieerson',
		id: person:tobie,
		name: 'Tobie',
		skills: [
			'JavaScript',
			'SurrealQL',
			'breathing',
			'Rust'
		]
	}
]
```

You can also remove a field from a record using the `UNSET` keyword or by setting the field to `NONE`.

```surql
-- Setup from the examples above
CREATE person:tobie CONTENT {
    name: 'Tobie',
    company: 'SurrealDB',
    skills: ['JavaScript', 'Go' , 'SurrealQL']
};
UPDATE person SET 
	dollars = 50,
	skills += 'breathing',
	enjoys += 'reading',
	full_name = name + ' Mc' + name + 'erson';
UPDATE person:tobie SET skills += 'Rust';
UPDATE person:tobie SET 
	skills -= 'Go', 
	dollars -= 1;

-- Remove the company field by setting it to NONE or using the UNSET keyword
UPDATE person:tobie SET company = NONE;

UPDATE person:tobie UNSET company;
```

```surql title="Output"
[
	{
		dollars: 49,
		enjoys: [
			'reading'
		],
		full_name: 'Tobie McTobieerson',
		id: person:tobie,
		name: 'Tobie',
		skills: [
			'JavaScript',
			'SurrealQL',
			'breathing',
			'Rust'
		]
	}
]
```

To rename a field on every record of a table, copy it to the new name and set the old name to `NONE` in the same statement. Every expression in `SET` reads the record as it was before the statement, so `username = name` still reads the old value even though `name` is removed in the same statement:

```surql
CREATE user:1 SET name = 'Ann';
CREATE user:2 SET name = 'Bob';

UPDATE user SET username = name, name = NONE;
```

```surql title="Output"
[
	{ id: user:1, username: 'Ann' },
	{ id: user:2, username: 'Bob' }
]
```

On a schemafull table, define the new field and [remove](/docs/reference/query-language/statements/remove.md) the definition of the old one before the `UPDATE`. While the old field is still defined with a type such as `string`, setting it to `NONE` fails. The stored values stay readable after the definition is removed, so the `UPDATE` can still copy them.

### Updating objects inside an array

Setting a field through an array path, such as `partnerships.pl`, sets the same value on every object in the array. The value is calculated once for the whole record, so a path that reads the array in the value gives an array, not the value of the current element:

```surql
CREATE deal:one SET amount = 400, partnerships = [
	{ share: 0.5, pl: 0 },
	{ share: 0.25, pl: 0 }
];

UPDATE deal:one SET partnerships.pl = amount * partnerships.share;
//- "Cannot perform multiplication with 'int' and 'array'"
```

To calculate a value for each element, replace the array with a [`.map()`](/docs/reference/query-language/functions/database-functions/array.md#arraymap) over it. The closure can read the other fields of the record, such as `amount`, and `+` on two objects keeps the fields of the first and adds or replaces the fields of the second:

```surql
-- Setup from the example above
CREATE deal:one SET amount = 400, partnerships = [
	{ share: 0.5, pl: 0 },
	{ share: 0.25, pl: 0 }
];

UPDATE deal:one SET partnerships = partnerships.map(|$p|
	$p + { pl: amount * $p.share }
);
```

```surql title="Output"
[
	{
		amount: 400,
		id: deal:one,
		partnerships: [
			{ pl: 200f, share: 0.5f },
			{ pl: 100f, share: 0.25f }
		]
	}
]
```

To change only some elements, filter the path with `[WHERE]` or pick one by its index:

```surql
-- Setup from the example above
CREATE deal:one SET amount = 400, partnerships = [
	{ share: 0.5, pl: 0 },
	{ share: 0.25, pl: 0 }
];

UPDATE deal:one SET partnerships[WHERE share > 0.3].pl = 0;
UPDATE deal:one SET partnerships[1].pl = 0;
```

## Conditional update with `WHERE` clause

The `UPDATE` statement supports conditional matching of records using a `WHERE` clause. If the expression in the `WHERE` clause evaluates to `true`, then the respective record will be updated.

```surql
-- Setup from the examples above
CREATE person CONTENT {
    name: 'John',
    company: 'SurrealDB Studio',
    skills: ['JavaScript', 'Go' , 'SurrealQL']
};
CREATE person:tobie CONTENT {
    name: 'Tobie',
    company: 'SurrealDB',
    skills: ['JavaScript', 'Go' , 'SurrealQL']
};
UPDATE person SET 
	dollars = 50,
	skills += 'breathing',
	enjoys += 'reading',
	full_name = name + ' Mc' + name + 'erson';
UPDATE person:tobie SET skills += 'Rust';
UPDATE person:tobie SET 
	skills -= 'Go', 
	dollars -= 1;
UPDATE person:tobie UNSET company;

-- Update all records which match the condition that `company` is not equal to "SurrealDB"
UPDATE person SET skills += "System design"
  WHERE company != "SurrealDB";
```

```surql title="Output"
[
	{
		company: 'SurrealDB Studio',
		dollars: 50,
		enjoys: [
			'reading'
		],
		full_name: 'John McJohnerson',
		id: person:i5z3i64cpqpo8jtr6jww,
		name: 'John',
		skills: [
			'JavaScript',
			'Go',
			'SurrealQL',
			'breathing',
			'System design'
		]
	},
	{
		dollars: 49,
		enjoys: [
			'reading'
		],
		full_name: 'Tobie McTobieerson',
		id: person:tobie,
		name: 'Tobie',
		skills: [
			'JavaScript',
			'SurrealQL',
			'breathing',
			'Rust',
			'System design'
		]
	}
]
```

### Evaluation order

_(since v3.3.0)_

The `WHERE` condition is checked before the data clause is evaluated, so a data clause with side effects only runs for the records the condition matches. The same applies to [`UPSERT`](/docs/reference/query-language/statements/upsert.md#evaluation-order) when it updates an existing record.

```surql
-- Setup from the example above
CREATE person:tobie CONTENT {
    name: 'Tobie',
    company: 'SurrealDB',
    skills: ['JavaScript', 'Go' , 'SurrealQL']
};

-- Updates no records, and creates no `audit` records
UPDATE person
	SET last_audit = (CREATE ONLY audit SET at = time::now()).id
	WHERE false;

-- No record matches, so the query effectively becomes this:
UPDATE person
	/* SET last_audit = (CREATE ONLY audit SET at = time::now()).id */
	WHERE false;
```

Validation of the data clause is deferred in the same way, so a data clause that would be rejected for a record no longer raises an error when the condition excludes that record.

> [!NOTE]
> Before SurrealDB 3.3.0, the data clause was evaluated for every scanned record on a full table scan, so its side effects fired for records the condition rejected. On an index-backed plan they did not, which meant that adding an index changed how many times the side effects ran.

### One image of the record

_(since v3.3.0)_

The `WHERE` condition and the data clause read the same image of the record, taken before the statement changes anything. Reads therefore never observe the statement's own writes, and both clauses agree on what the record contains.

This has held for ordinary fields since 3.0.0, so `SET a = a + 1, b = a + 1` assigns `b` from the old `a`. Before 3.0.0 the assignments ran in the order they were written, and `b` read the new `a` (see [the 2.x to 3.x upgrade notes](/docs/operate/upgrading/2x-to-3x.md#21-set-expressions-read-the-record-from-before-the-statement)). [Computed fields](/docs/reference/query-language/statements/define/field.md#restrictions-on-computed-fields) are now part of that image too, so a data clause and a condition both see their pre-mutation values.

```surql
DEFINE FIELD can_drive ON person COMPUTED age >= 18;
CREATE person:1 SET age = 17;

-- `can_drive` is false in all three: it reflects age 17, not the new age of 18
UPDATE person:1 SET age = 18, my_field = can_drive;
UPDATE person:1 SET my_field = can_drive, age = 18;
UPDATE person:1 SET my_field = can_drive, age = 18
	WHERE can_drive = false;
```

A statement that creates a record has no earlier image, so a computed field reads `NONE` there - whether the record ID was named, generated, or reached through [`UPSERT`](/docs/reference/query-language/statements/upsert.md).

> [!NOTE]
> Before 3.3.0, a computed field read `NONE` in the data clause but held its value in the `WHERE` condition, so whichever clause ran first decided what the other saw. The first two statements above returned `NONE` and the third returned `false`.

### KNN operators in the `WHERE` clause

_(since v4.0.0)_

A KNN operator such as `<|2,COSINE|>` in the `WHERE` clause of an `UPDATE` needs a [vector index](/docs/learn/data-models/vector-search/vector-indexes.md) on the field. Without one, the statement fails:

```surql
INSERT INTO article [
	{ id: article:1, embedding: [1.0, 0.0, 0.0] },
	{ id: article:2, embedding: [0.0, 1.0, 0.0] },
	{ id: article:3, embedding: [0.9, 0.1, 0.0] }
] RETURN NONE;
LET $q = [1.0, 0.0, 0.0];
UPDATE article SET seen = true WHERE embedding <|2,COSINE|> $q;
```

```text title="Error output"
Invalid query: A KNN operator in the WHERE of an UPDATE or DELETE needs a vector index on the field; define one, or write `UPDATE (SELECT id FROM ... WHERE ...)`.
```

To update the nearest records without a vector index, select them in a subquery and update the result. With the records and `$q` above:

```surql
UPDATE (SELECT id FROM article WHERE embedding <|2,COSINE|> $q)
	SET seen = true
	RETURN VALUE id;
```

```surql title="Output"
[article:1, article:3]
```

With a vector index, the `RETURN` clause can read the KNN operator and [`vector::distance::knn()`](/docs/reference/query-language/functions/database-functions/vector.md#vectordistanceknn). Both report the search as it found each record before the write, so a record that the statement moves away from the query vector, or that a `DELETE` removes, still counts as a neighbour at the distance the search computed. With the records above and a vector index on `embedding`:

```surql
DEFINE INDEX article_embedding ON article FIELDS embedding HNSW DIMENSION 3 DIST COSINE;
UPDATE article SET embedding = [0.0, 0.0, 1.0]
	WHERE embedding <|1,40|> [1.0, 0.0, 0.0]
	RETURN id, embedding, vector::distance::knn() AS distance;
```

```surql title="Output"
[
	{
		distance: 0f,
		embedding: [0f, 0f, 1f],
		id: article:1
	}
]
```

## CONTENT clause

Instead of specifying record data using the `SET` clause, it is also possible to use the `CONTENT` keyword to specify the record data using a SurrealQL object.

```surql
-- Setup from the example above
CREATE person CONTENT {
    name: 'John',
    company: 'SurrealDB Studio',
    skills: ['JavaScript', 'Go' , 'SurrealQL']
};
CREATE person:tobie CONTENT {
    name: 'Tobie',
    company: 'SurrealDB',
    skills: ['JavaScript', 'Go' , 'SurrealQL']
};

-- Update all records with the same content
UPDATE person CONTENT {
	name: 'John',
	company: 'SurrealDB',
	skills: ['Rust', 'Go', 'JavaScript'],
};

-- Oops, now they are both named John.
-- Update a specific record with some content
UPDATE person:tobie CONTENT {
	name: 'Tobie',
	company: 'SurrealDB',
	skills: ['Rust', 'Go', 'JavaScript'],
};
```

A statement with a `CONTENT` clause bypasses `READONLY` fields instead of generating an error.

```surql
DEFINE FIELD created
  ON person TYPE datetime DEFAULT d'2024-01-01T00:00:00Z' READONLY;
CREATE person:gladys SET age = 90;
-- Does not try to modify `created` field, no error
UPDATE person:gladys CONTENT { age: 70 };
```

```surql title="Output"
-------- Query --------
[
	{
		age: 90,
		created: d'2024-01-01T00:00:00Z',
		id: person:gladys
	}
]

-------- Query --------
[
	{
		age: 70,
		created: d'2024-01-01T00:00:00Z',
		id: person:gladys
	}
]
```

## MERGE clause

Instead of specifying the full record data using `CONTENT` or one field at a time using `SET`, it is also possible to merge-update only specific fields by using the `MERGE` keyword followed by an object containing the fields which are to be upserted.

```surql
-- Setup from the examples above
CREATE person CONTENT {
    name: 'John',
    company: 'SurrealDB Studio',
    skills: ['JavaScript', 'Go' , 'SurrealQL']
};
CREATE person:tobie CONTENT {
    name: 'Tobie',
    company: 'SurrealDB',
    skills: ['JavaScript', 'Go' , 'SurrealQL']
};
UPDATE person CONTENT {
	name: 'John',
	company: 'SurrealDB',
	skills: ['Rust', 'Go', 'JavaScript'],
};
UPDATE person:tobie CONTENT {
	name: 'Tobie',
	company: 'SurrealDB',
	skills: ['Rust', 'Go', 'JavaScript'],
};

-- Update certain fields on all records
UPDATE person MERGE {
	settings: {
		marketing: true,
	},
};

-- Update certain fields on a specific record
UPDATE person:tobie MERGE {
	settings: {
		marketing: true,
	},
};
```

```surql title="Output"
[
	{
		company: 'SurrealDB',
		id: person:i5z3i64cpqpo8jtr6jww,
		name: 'John',
		settings: {
			marketing: true
		},
		skills: [
			'Rust',
			'Go',
			'JavaScript'
		]
	},
	{
		company: 'SurrealDB',
		id: person:tobie,
		name: 'Tobie',
		settings: {
			marketing: true
		},
		skills: [
			'Rust',
			'Go',
			'JavaScript'
		]
	}
]
```

`MERGE` combines objects at every level, so a nested object in the merge keeps the fields it does not mention. An array is a single value rather than a set of fields, so an array in the merge replaces the stored array whole, including an array of objects:

```surql
CREATE doc:1 SET tags = ['a', 'b'], meta = { x: 1, y: 2 };

UPDATE doc:1 MERGE { meta: { y: 3 }, tags: ['c'] };
```

```surql title="Output"
[
	{
		id: doc:1,
		meta: { x: 1, y: 3 },
		tags: ['c']
	}
]
```

To add to an array or remove from it instead of replacing it, use `SET tags += 'd'` or `SET tags -= 'a'`.

## REPLACE clause

Originally an alias for `CONTENT`, the `REPLACE` clause maintains the previous behaviour regarding `READONLY` fields. If the content following `REPLACE` does not match a record's `READONLY` fields, an error will be generated.

```surql
DEFINE FIELD created
  ON person TYPE datetime DEFAULT d'2024-01-01T00:00:00Z' READONLY;
CREATE person:gladys SET age = 90;
-- Attempts to change `created` field, error
UPDATE person:gladys REPLACE { age: 70 };
-- `created` equals current value, query works
UPDATE person:gladys REPLACE { age: 70,
  created: d'2024-01-01T00:00:00Z' };
```

```surql title="Output"
-------- Query --------
[
	{
		age: 90,
		created: d'2024-01-01T00:00:00Z',
		id: person:gladys
	}
]

-------- Query --------
'Found changed value for field `created`,
  with record `person:gladys`,
  but field is readonly'

-------- Query --------
[
	{
		age: 70,
		created: d'2024-01-01T00:00:00Z',
		id: person:gladys
	}
]
```

## Alter the `RETURN` value

By default, the update statement returns the record value once the changes have been made. To change the return value of each record, use the `RETURN` clause, specifying `NONE`, `BEFORE`, `AFTER`, `DIFF`, a comma-separated list of specific fields or ad-hoc fields, or `VALUE` for a single field without its key name.

```surql
-- Setup from the example above
CREATE person CONTENT {
    name: 'John',
    company: 'SurrealDB Studio',
    skills: ['JavaScript', 'Go' , 'SurrealQL']
};
CREATE person:tobie CONTENT {
    name: 'Tobie',
    company: 'SurrealDB',
    skills: ['JavaScript', 'Go' , 'SurrealQL']
};

-- Don't return any result
UPDATE person SET skills += 'reading' RETURN NONE;

-- Return the changeset diff
UPDATE person SET skills += 'reading' RETURN DIFF;

-- Return the record before changes were applied
UPDATE person SET skills += 'reading' RETURN BEFORE;

-- Return the record after changes were applied (the default)
UPDATE person SET skills += 'reading' RETURN AFTER;

-- Return the value of the 'skills' field without the field name
UPDATE person SET skills += 'reading' RETURN VALUE skills;

-- Return a specific field only from the updated records
UPDATE person:tobie SET skills = ['skiing',
  'music'] RETURN name,
  interests;
```

## Counting the records a statement changed

`UPDATE` returns one entry for each record it changed, so the length of its output is the number of records changed. The same works for [`DELETE`](/docs/reference/query-language/statements/delete.md) with `RETURN BEFORE`, since a `DELETE` returns nothing by default:

```surql
CREATE |item:1..=5| SET old = true;

(UPDATE item SET checked = true WHERE old).len();
//- 5

(DELETE item WHERE old RETURN BEFORE).len();
//- 5

(DELETE item WHERE old RETURN BEFORE).len();
//- 0
```

For an `UPDATE`, add `RETURN VALUE id` to keep the output small when only the count is needed. For a `DELETE`, keep `RETURN BEFORE`: the deleted records no longer have an `id`, so `RETURN VALUE id` returns `NONE` for each of them.

## PATCH clause

You can also specify changes to be applied to your query response, using the PATCH command, which works similarly to the [JSON Patch specification](https://jsonpatch.com/).

```surql
-- Setup from the examples above
CREATE person:tobie CONTENT {
    name: 'Tobie',
    company: 'SurrealDB',
    skills: ['JavaScript', 'Go' , 'SurrealQL']
};
UPDATE person:tobie CONTENT {
	name: 'Tobie',
	company: 'SurrealDB',
	skills: ['Rust', 'Go', 'JavaScript'],
};
UPDATE person:tobie MERGE {
	settings: {
		marketing: true,
	},
};

-- Patch the JSON response
UPDATE person:tobie PATCH [
	{
		"op": "add",
		"path": "Engineering",
		"value": "true"
	}
]
```

```surql title="Output"
[
	{
		Engineering: 'true',
		company: 'SurrealDB',
		id: person:tobie,
		name: 'Tobie',
		settings: {
			marketing: true
		},
		skills: [
			'Rust',
			'Go',
			'JavaScript'
		]
	}
]
```

### Operations

A patch is an array of operations, each naming its target with a [JSON Pointer](https://datatracker.ietf.org/doc/html/rfc6901) - a `/`-separated path into the record, so `/settings/marketing` reaches the `marketing` field inside `settings`. SurrealDB accepts the six operations of the JSON Patch specification plus `change`:

| Operation | Takes | Does |
| --- | --- | --- |
| `add` | `path`, `value` | Sets the member at `path` on an object, or inserts at that position in an array |
| `remove` | `path` | Deletes the field at `path` |
| `replace` | `path`, `value` | Overwrites the field at `path` |
| `copy` | `from`, `path` | Reads the value at `from` and writes it to `path` |
| `move` | `from`, `path` | Reads the value at `from`, writes it to `path`, and deletes `from` |
| `test` | `path`, `value` | Fails the whole patch unless the field at `path` already equals `value` |
| `change` | `path`, `value` | Applies a text diff to the string at `path` |

An unknown operation fails the statement with `The JSON Patch contains invalid operations`, and so does a `test` whose value does not match, which is what makes `test` useful as a guard in front of the operations that follow it.

```surql
CREATE person:tobie SET name = 'Tobie', company = 'SurrealDB', nickname = 'Tobie';

UPDATE person:tobie PATCH [
	{ "op": "replace", "path": "/company", "value": "SurrealDB Ltd" },
	{ "op": "copy", "from": "/name", "path": "/display_name" },
	{ "op": "remove", "path": "/nickname" }
];
```

```surql title="Output"
[
	{
		company: 'SurrealDB Ltd',
		display_name: 'Tobie',
		id: person:tobie,
		name: 'Tobie'
	}
]
```

The value of a `change` operation is a text patch in the format of the [diff-match-patch](https://github.com/google/diff-match-patch) library. Each hunk starts with an `@@` header giving character positions, followed by lines that start with a space for unchanged text, `-` for removed text and `+` for added text.

```surql
CREATE person:tobie SET company = "SurrealDB";

UPDATE person:tobie PATCH [
	{
		"op": "change",
		"path": "/company",
		"value": "@@ -2,8 +2,12 @@\n urrealDB\n+ Ltd\n"
	}
];
```

```surql title="Output"
[
	{
		company: 'SurrealDB Ltd',
		id: person:tobie
	}
]
```

[`value::diff()`](/docs/reference/query-language/functions/database-functions/value.md#valuediff) produces this format, so `UPDATE person:tobie PATCH value::diff({ company: 'SurrealDB' }, { company: 'SurrealDB Ltd' })` applies the same change. A diff whose context does not match the current string leaves the field unchanged, and the statement does not report an error.

The start and length numbers in the `@@` header are a hint, not a requirement. SurrealDB finds where to apply each hunk by its unchanged and removed text, so the change above applies with any numbers in its header. When the text a hunk changes appears more than once in the string, the header does not choose between them, so include enough unchanged text around the change for the hunk to match in one place only.

#### Pointers into arrays

_(since v3.3.0)_

A segment addresses a position in an array only in the canonical spelling RFC 6901 gives it, so a member named `007`, `+3` or `-1` stays addressable as a member rather than being read as an index. The segment `-` addresses the position after the last element.

`add`, and the destination of `copy` and `move`, **insert** at the position and shift the elements after it, rather than overwriting the element already there. `move` removes its source before writing its destination, so a destination in the same array counts against the array that removal left behind.

`replace` needs an element to exist at the position it names and fails otherwise, matching the bounds `add` already enforced. On an object it still creates a missing member.

Two pointers are refused rather than guessed at: one whose prefix reaches every element of a sequence, since it names no single position, and a destination inside its own source, which would otherwise nest a copy of the source inside itself each time it ran.

Writing to a [set](/docs/reference/query-language/language-primitives/data-types/sets.md) by position reaches whichever element sorts into that place, so a set is rebuilt once the patch has been applied.

> [!WARNING]
> Before 3.3.0 a pointer through an array index did not apply at all, and `replace` corrupted the record on top of that, giving every element of the array a member named after the index segment. Replacing the whole array was the only reliable way to change one property of one element.

### Read pointers and field permissions

Three `PATCH` operations read from a pointer as well as writing: `copy` and `move` read the path in their `from`, and `test` reads its `path`. Each of those reads resolves against the caller's permitted view of the record, and the statement fails with a not-allowed error where the pointer reaches a field the caller cannot `select`.

This holds for a pointer at the restricted field itself, at an ancestor object that holds it, and at a nested leaf beneath it.

The check walks the operations in order against a copy of the record, judging each pointer as the record stands when that operation runs. A patch is a sequence, so an earlier insertion or removal shifts every later element by one, and a pointer that reached nothing when the patch arrived can come to reach a restricted field by the time its own operation runs.

`add` and `change` also read a pointer, but each writes its result back to the path it read, so neither moves a value out of the field it came from and neither is gated.

The other data clauses reduce rather than refuse: a `SET`, `CONTENT`, `MERGE` or `REPLACE` right-hand side sees `NONE` where a field is restricted. `PATCH` fails the statement instead, because substituting `NONE` would store a value the caller never asked for, and for `move` would delete the source field as well. The failure reveals that a field is restricted, which a plain `SELECT` already shows by omitting it, rather than the value.

Every statement that takes a `PATCH` clause behaves this way, so the same applies to [`CREATE`](/docs/reference/query-language/statements/create.md), [`UPSERT`](/docs/reference/query-language/statements/upsert.md), [`RELATE`](/docs/reference/query-language/statements/relate.md) and [`INSERT`](/docs/reference/query-language/statements/insert.md).

## Using a timeout

When processing a large result set with many interconnected records, it is possible to use the `TIMEOUT` keyword to specify a timeout duration for the statement. If the statement continues beyond this duration, then the transaction will fail, no records will be updated in the database, and the statement will return an error.

```surql
-- Setup
CREATE person:tobie, person:jaime, person:ann;
RELATE person:tobie->knows->person:jaime;
RELATE person:jaime->knows->person:ann SET influencer = true;

UPDATE person 
	SET important = true 
	WHERE ->knows->person->(knows WHERE influencer = true) 
	TIMEOUT 5s;
```

## The `EXPLAIN` clause

When `EXPLAIN` is used:

1. The `UPDATE` statement returns an explanation of its execution plan, which shows how the query will be performed.
2. The records are not updated.

`EXPLAIN` can be followed by `FULL` to see the number of executed rows.

## UPDATE inside database exports

As `UPDATE` before version 2.0.0 used to create a specified record ID if it did not exist, it was used in the `.surql` files generated by the [`surreal db export`](/docs/reference/cli/db/commands/export.md) command to export existing records in a database. As of version 2.0.0, the [`INSERT`](/docs/reference/query-language/statements/insert.md) statement is used instead.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/upsert

# UPSERT

The UPSERT statement can be used to insert records or modify records that already exist.

The `UPSERT` statement can be used to insert records into the database, or to update them if they exist. To compare it with the other statements that write records, see [Writing records that may already exist](/docs/reference/query-language/statements/overview.md#writing-records-that-may-already-exist).

> [!NOTE]
> In versions of SurrealDB between 2.0.0 and 2.0.4, an UPSERT statement was treated as an "UPDATE, otherwise INSERT" statement. It has since been changed to a statement which defaults to insertion, and updates otherwise. Please see the examples below for details.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
UPSERT [ ONLY ] @targets
    [ CONTENT @value
      | MERGE @value
      | PATCH @value
	  | REPLACE @value
      | [ SET @field = @value, ... | UNSET @field, ... ]
    ]
    [ WHERE @condition ]
    [ RETURN NONE | RETURN BEFORE | RETURN AFTER | RETURN DIFF
      | RETURN @statement_param, ... | RETURN VALUE @statement_param ]
    [ TIMEOUT @duration ]
	[ EXPLAIN [ FULL ]]
;
```

## Example usage

Conceptually, an `UPSERT` statement can be thought of as an "`INSERT`, otherwise `UPDATE`" statement.

### `UPSERT` without a `WHERE` clause

As an `UPSERT` statement is primarily an `INSERT` statement, one without a `WHERE` clause will not perform an update.

```surql
UPSERT person SET name = 'Billy';
UPSERT person SET name = 'Bobby';
SELECT * FROM person;
```

As the output shows, the second `UPSERT` simply inserted another `person` record with the name "Bobby", rather than updating the existing record.

```surql title="Output"
-------- Query --------
[
	{
		id: person:c2bl54ahi551fcx9dqri,
		name: 'Billy'
	}
]

-------- Query --------
[
	{
		id: person:886dcoe1ayul217nl2fu,
		name: 'Bobby'
	}
]

-------- Query --------
[
	{
		id: person:886dcoe1ayul217nl2fu,
		name: 'Bobby'
	},
	{
		id: person:c2bl54ahi551fcx9dqri,
		name: 'Billy'
	}
]
```

### Using the `WHERE` clause

#### Without a specified ID

When using the `WHERE` clause and no specified ID, SurrealDB will check to see if any records match the clause. If nothing matches, a new record will be created. Exactly one record is created for the whole statement, and none when any record matches, whatever the `RETURN` clause.

> [!NOTE]
> Before SurrealDB 4.0, `UPSERT` decided whether to create a record from what the statement returned rather than from what it matched. A matching `UPSERT ... WHERE` with `RETURN NONE` therefore also created a new record.

As such, the following `UPSERT` statement will return a new record:

```surql
UPSERT person SET name = 'Jaime' WHERE name = 'Jaime';
```

```surql title="Output"
[
	{
		id: person:7ilunylkcjgbg9gf0tqn,
		name: 'Jaime'
	}
]
```

Since a record with the name 'Jaime' exists, an `UPSERT` followed by `WHERE name = 'Jaime'` will update the existing record instead of creating a new one.

```surql
UPSERT person SET name = 'Tobie' WHERE name = 'Jaime';
```

```surql title="Output"
[
	{
		id: person:7ilunylkcjgbg9gf0tqn,
		name: 'Tobie'
	}
]
```

Now that no records have the name `'Jaime'`, the same query as above will now create a new record because no records match the `WHERE` clause. The database will now have two `person` records.

```surql
UPSERT person SET name = 'Tobie' WHERE name = 'Jaime';
SELECT * FROM person;
```

```surql title="Output"
-- Query
[
	{
		id: person:0n0ddlkmhe6mdb6ikkui,
		name: 'Tobie'
	}
]

-- Query
[
	{
		id: person:0n0ddlkmhe6mdb6ikkui,
		name: 'Tobie'
	},
	{
		id: person:7ilunylkcjgbg9gf0tqn,
		name: 'Tobie'
	}
]
```

#### With a specified ID

`UPSERT` behaviour with a specific ID and a `WHERE` clause differs slightly from the examples above. In this case, there is the possibility that a record ID already exists but the `WHERE` clause does not match. As such, there is no way to create a new record as the statement only pertains to an ID for an already existing record.

The following query will return a record, because the `person:test` record does not yet exist. The `WHERE` clause makes no difference as there is no record to apply it to.

```surql
UPSERT person:test SET name = 'Jaime' WHERE name = 'Jaime';
```

```surql title="Output"
[
	{
		id: person:test,
		name: 'Jaime'
	}
]
```

The following query will update the `person:test` record, because the record exists and the `WHERE` clause matches. The `person:test` record will now have the name `'Tobie'`.

```surql
UPSERT person:test SET name = 'Tobie' WHERE name = 'Jaime';
```

```surql title="Output"
[
	{
		id: person:test,
		name: 'Tobie'
	}
]
```

However, this third query will return nothing. The `WHERE` clause does not match and thus `person:test` cannot be updated, and the statement itself only pertains to the `person:test` record, so a new record using a random ID will not be returned.

```surql
UPSERT person:test SET name = 'Billy' WHERE name = 'Jaime';
```

```surql title="Output"
[]
```

#### KNN operators in the `WHERE` clause

_(since v4.0.0)_

An `UPSERT` does not accept a KNN operator such as `<|1,COSINE|>` in its `WHERE` clause, with or without a [vector index](/docs/learn/data-models/vector-search/vector-indexes.md) on the field:

```surql
INSERT INTO article [
	{ id: article:1, embedding: [1.0, 0.0, 0.0] },
	{ id: article:2, embedding: [0.0, 1.0, 0.0] },
	{ id: article:3, embedding: [0.9, 0.1, 0.0] }
] RETURN NONE;
LET $q = [1.0, 0.0, 0.0];
UPSERT article SET seen = true WHERE embedding <|1,COSINE|> $q;
```

```text title="Error output"
Invalid query: A KNN operator is not supported in the WHERE of an UPSERT; use UPDATE, or UPSERT the ids a SELECT returns.
```

To change the nearest records, select them in a subquery and [`UPDATE`](/docs/reference/query-language/statements/update.md#knn-operators-in-the-where-clause) the result:

```surql
UPDATE (SELECT id FROM article WHERE embedding <|1,COSINE|> $q)
	SET seen = true
	RETURN VALUE id;
```

```surql title="Output"
[article:1]
```

### Evaluation order

_(since v3.3.0)_

When an `UPSERT` updates an existing record, the `WHERE` condition is checked before the data clause is evaluated. A data clause with side effects therefore only runs for the records the condition matches, matching [`UPDATE`](/docs/reference/query-language/statements/update.md#evaluation-order).

```surql
CREATE person:jaime SET name = 'Jaime';

-- Updates nothing, and creates no `audit` record
UPSERT person:jaime
	SET last_audit = (CREATE ONLY audit SET at = time::now()).id
	WHERE false;

-- `person:jaime` does not match, so the query effectively becomes this:
UPSERT person:jaime
	/* SET last_audit = (CREATE ONLY audit SET at = time::now()).id */
	WHERE false;
```

Validation of the data clause is deferred in the same way, so a data clause that would be rejected for a record no longer raises an error when the condition excludes that record.

The condition only gates the update path. When an `UPSERT` creates a record instead, the `WHERE` clause is not evaluated at all - as described in [With a specified ID](#with-a-specified-id) above - and the data clause runs.

```surql
-- `person:billy` does not exist, so it is created and an `audit` record is written
UPSERT person:billy
	SET last_audit = (CREATE ONLY audit SET at = time::now()).id
	WHERE false;
```

> [!NOTE]
> Before SurrealDB 3.3.0, the data clause was evaluated for every scanned record on a full table scan, so its side effects fired for records the condition rejected. On an index-backed plan they did not, which meant that adding an index changed how many times the side effects ran.

### Improved performance via UPSERT and a unique index

[Unique indexes](/docs/reference/query-language/statements/define/indexes.md#unique-index) can be used to ensure that no field or combination of fields is ever present more than once. For example, a game might have a rule that duplicate names can exist, but not within the same class.

```surql
DEFINE INDEX unique_key ON TABLE user FIELDS name, class UNIQUE;
DEFINE FIELD official_name ON TABLE user VALUE name + " the " + class;
CREATE user:billy SET name = "Billy",
  class = "wizard",
  metadata = { likes: ["strawberries"] };
CREATE user:billy_der_zweite SET name = "Billy",
  class = "wizard",
  metadata = { likes: ["strawberries",
  "fields"] };
```

As the output shows, the unique index prevents the creation of a second user with the name and class as the first.

```surql title="Output"
-------- Query --------
[
	{
		id: user:billy,
		metadata: {
			likes: [
				'strawberries'
			]
		},
		name: 'Billy',
		official_name: 'Billy the wizard',
		class: 'wizard'
	}
]

-------- Query --------
"Database index `unique_key` already contains ['Billy',
  'wizard'],
  with record `user:billy`"
```

To change an existing record's `metadata` field to the value `{ likes: ["strawberries", "fields"] }`, an `UPDATE` with a `WHERE` can be used. As `name` and `class` are the fields of the `unique_key` index, the `UPDATE` finds the record through the index rather than by scanning the `user` table.

```surql
-- Setup from the example above
DEFINE INDEX unique_key ON TABLE user FIELDS name, class UNIQUE;
DEFINE FIELD official_name ON TABLE user VALUE name + " the " + class;
CREATE user:billy SET name = "Billy",
  class = "wizard",
  metadata = { likes: ["strawberries"] };

UPDATE user SET
	metadata = { likes: ["strawberries", "fields"] }
WHERE
	name = "Billy" AND
	class = "wizard";
```

If you only need to update one record and have a unique index that covers it, `UPSERT` can do the same work without a `WHERE` clause. The statement always checks the unique index first to see if the record is a duplicate, and so reaches the existing record directly.

```surql
-- Checks the index for ["Mandy", "wizard"], no existing
-- record found so no problem
UPSERT user SET name = "Mandy", class = "wizard";

-- Fails because statement tries to upsert a new user:mandy
-- on top of the previous randomly generated one
UPSERT user:mandy SET 
	name = "Mandy",
	class = "wizard",
	metadata = { likes: ["strawberries" ]};
```

```surql title="Output"
-------- Query --------

[
	{
		class: 'wizard',
		id: user:kdvh401gofckvvy6nbiw,
		name: 'Mandy',
		official_name: 'Mandy the wizard'
	}
]

-------- Query --------

"Database index `unique_key` already contains ['Mandy',
  'wizard'],
  with record `user:kdvh401gofckvvy6nbiw`"
```

Since an `UPSERT` statement already checks unique indexes by default, it uses this to recognize that the user with `name = "Billy"` and `the = "Wizard"` corresponds to the record `user:j2ecdb2tf4ou29mr0yp5` and update it without needing to scan the entire `user` table.

```surql
UPSERT user SET
	name = "Billy",
	class = "wizard",
	metadata = { likes: ["strawberries", "fields"] };
```

```surql title="Output"
-------- Query --------
[
	{
		id: user:j2ecdb2tf4ou29mr0yp5,
		metadata: {
			likes: [
				'strawberries'
			]
		},
		name: 'Billy',
		official_name: 'Billy the wizard',
		class: 'wizard'
	}
]
```

The following example creates a crowded field of 50000 `user` records, followed by one more `user` named "Billy". Both the `UPDATE` using `WHERE name = "Billy" AND class = "wizard"` and the `UPSERT` using the two fields of the index find Billy through the index, so neither scans the 50,001 records.

```surql
DEFINE INDEX unique_key ON TABLE user FIELDS name, class UNIQUE;
DEFINE FIELD official_name ON TABLE user VALUE name + " the " + class;

-- Add 50000 users to fill up the database
FOR $i IN <array>0..50000 { CREATE user SET name = <string>$i,
  class = <string>$i;
};

-- Create Billy, one of 50,001 records
CREATE user SET name = "Billy", class = "wizard";

-- UPDATE finds Billy through the unique index
UPDATE user SET
	interests += "music"
WHERE
	name = "Billy" AND
	class = "wizard";

-- But UPSERT uses 'name' and 'class' to check the index anyway,
-- and thus can use it to access the record without a scan
UPSERT user SET
	name = "Billy",
	class = "wizard",
	interests += "travel";
```

> [!NOTE]
> Before SurrealDB 2.3.0, `UPDATE ... WHERE` did not use indexes and scanned the whole table, so on those versions `UPSERT` with a unique index was the faster way to modify a single record identified by its unique fields.

## Using the ONLY clause

The `ONLY` clause can be used to return a single record instead of an array of records.

```surql
-- UPSERT just a single record
-- Using the ONLY keyword, just an object for the record in question will be returned.
-- This, instead of an array with a single object.
UPSERT ONLY person:tobie SET 
	name = 'Tobie', 
	company = 'SurrealDB', 
	skills = ['Rust', 'Go', 'JavaScript'];
```

## Type inference when using UPSERT

The `+=` operator in the following query is enough for SurrealDB to infer that the `interests` field must be an `array<string>`.

```surql
-- UPSERT a document and remove a tag from an array
UPSERT person:tobie SET interests += 'Java';
```

Type inference will also work with a numeric value such as the `click_count` field below, in which case it will infer the field to be of type `int` with a default value of 0.

```surql
-- UPSERT a document and increment a numeric value
UPSERT webpage:home SET click_count += 1;
```

Creating a record by default makes the `UPSERT` statement an ideal way to manage an incrementing field.

```surql
UPSERT event_for:[time::now().format("%Y-%m-%d")] SET
    number += 1;
```

```surql title="Possible output"
[
	{
		id: event_for:[
			'2024-09-18'
		],
		number: 1
	}
]
```

Doing the same with an `UPDATE` statement would require much more manual work.

```surql
-- Setup from the example above
UPSERT event_for:[time::now().format("%Y-%m-%d")] SET
    number += 1;

IF (SELECT *
  FROM event_for:[time::now().format("%Y-%m-%d")]).is_empty() {
    CREATE event_for:[time::now().format("%Y-%m-%d")] SET number = 1;
} ELSE {
    UPDATE event_for:[time::now().format("%Y-%m-%d")] SET number += 1;
};
```

## CONTENT clause

Instead of specifying record data using the `SET` clause, it is also possible to use the `CONTENT` keyword to specify the record data using a SurrealQL object.

```surql
-- UPSERT all records with the same content
UPSERT person CONTENT {
	name: 'Tobie',
	company: 'SurrealDB',
	skills: ['Rust', 'Go', 'JavaScript'],
};

-- UPSERT a specific record with some content
UPSERT person:tobie CONTENT {
	name: 'Tobie',
	company: 'SurrealDB',
	skills: ['Rust', 'Go', 'JavaScript'],
};
```

A statement with a `CONTENT` clause bypasses `READONLY` fields instead of generating an error.

```surql
DEFINE FIELD created
  ON person TYPE datetime DEFAULT d'2024-01-01T00:00:00Z' READONLY;
UPSERT person:gladys SET age = 90;
-- Does not try to modify `created` field, no error
UPSERT person:gladys CONTENT { age: 70 };
```

```surql title="Output"
-------- Query --------
[
	{
		age: 90,
		created: d'2024-01-01T00:00:00Z',
		id: person:gladys
	}
]

-------- Query --------
[
	{
		age: 70,
		created: d'2024-01-01T00:00:00Z',
		id: person:gladys
	}
]
```

## REPLACE clause

Originally an alias for `CONTENT`, the `REPLACE` clause maintains the previous behaviour regarding `READONLY` fields. If the content following `REPLACE` does not match a record's `READONLY` fields, an error will be generated.

```surql
DEFINE FIELD created
  ON person TYPE datetime DEFAULT d'2024-01-01T00:00:00Z' READONLY;
UPSERT person:gladys SET age = 90;
-- Attempts to change `created` field, error
UPSERT person:gladys REPLACE { age: 70 };
-- `created` equals current value, query works
UPSERT person:gladys REPLACE { age: 70,
  created: d'2024-01-01T00:00:00Z' };
```

```surql title="Output"
-------- Query --------
[
	{
		age: 90,
		created: d'2024-01-01T00:00:00Z',
		id: person:gladys
	}
]

-------- Query --------
'Found changed value for field `created`,
  with record `person:gladys`,
  but field is readonly'

-------- Query --------
[
	{
		age: 70,
		created: d'2024-01-01T00:00:00Z',
		id: person:gladys
	}
]
```

## MERGE clause

Instead of specifying the full record data using the `SET` clause or the `CONTENT` keyword, it is also possible to merge-UPSERT only specific fields by using the `MERGE` keyword and specifying only the fields which are to be upserted.

```surql
-- Inserts a new record with a single field and random ID
UPSERT person MERGE {
	settings: {
		marketing: true,
	},
};

-- Updates certain fields on a specific record
UPSERT person:tobie MERGE {
	settings: {
		marketing: true,
	},
};
```

## PATCH clause

You can also specify changes to be applied to your query response, using the `PATCH` clause, which works similarly to the [JSON Patch specification](https://jsonpatch.com/).

The `copy`, `move` and `test` operations read from a pointer, and a pointer into a field the caller cannot `select` fails the statement. See [read pointers and field permissions](/docs/reference/query-language/statements/update.md#read-pointers-and-field-permissions).

```surql
-- Patch the JSON response
UPSERT person:tobie PATCH [
	{
		"op": "add",
		"path": "Engineering",
		"value": "true"
	}
];
```

## Alter the `RETURN` value

By default, the UPSERT statement returns the record value once the changes have been made. To change the return value of each record, specify a `RETURN` clause, specifying either `NONE`, `BEFORE`, `AFTER`, `DIFF`, or a comma-separated list of specific fields to return.

```surql
-- Don't return any result
UPSERT person:tobie SET interests += 'reading' RETURN NONE;

-- Return the changeset diff
UPSERT person:tobie SET interests += 'reading' RETURN DIFF;

-- Return the record before changes were applied
UPSERT person:tobie SET interests += 'reading' RETURN BEFORE;

-- Return the record after changes were applied (the default)
UPSERT person:tobie SET interests += 'reading' RETURN AFTER;

-- Return a specific field only from the upserted records
UPSERT person:tobie SET interests = ['skiing',
  'music'] RETURN name,
  interests;
```

When processing a large result set with many interconnected records, it is possible to use the `TIMEOUT` keywords to specify a timeout duration for the statement. If the statement continues beyond this duration, then the transaction will fail, no records will be upserted in the database, and the statement will return an error.

```surql
UPSERT person:3 SET important = true
  WHERE ->knows->person->(knows
  WHERE influencer = true) TIMEOUT 5s;
```

## The `EXPLAIN` clause

When `EXPLAIN` is used:

1. The `UPSERT` statement returns an explanation of its execution plan, which shows how the query will be performed.
2. The records are not updated.

`EXPLAIN` can be followed by `FULL` to see the number of executed rows.

---

Source: https://surrealdb.com/docs/reference/query-language/statements/use

# USE

The USE statement specifies a namespace and / or a database to use for the subsequent SurrealQL statements when switching between namespaces and databases.

The `USE` statement specifies a namespace and / or a database to use for the subsequent SurrealQL statements when switching between namespaces and databases. If you have a single namespace and database, you can define them in the [sql command](/docs/reference/cli/db/commands/sql.md#example-usage).

Ensure that your database and namespace exist and you have [started your database](/docs/reference/cli/db/commands/start.md) before using the Sql command option.

## Statement syntax

**SurrealQL Syntax**

```syntax title="SurrealQL Syntax"
USE [ NS @ns ] [ DB @db ];
```

## Example usage

The following query shows example usage of this statement if you have multiple namespaces and databases.

```surql
USE NS test; -- Switch to the 'main' Namespace
```

```surql
USE DB test; -- Switch to the 'main' Database
```

```surql
USE NS test DB test; -- Switch to the 'test' namespace and the 'test' database
```

You can also use the [INFO Statement](/docs/reference/query-language/statements/info.md) to check the current namespace and database.

```surql
INFO FOR NS; -- Check the current Namespace
```

```surql
INFO FOR DB; -- Check the current Database
```

## `USE` statement behaviour when resource does not exist

_(since v3.0.0)_

A `USE` statement creates the namespace or database that it names if it does not exist yet, as long as the user has permission to define it. A misspelled name therefore creates a new, empty namespace or database, and the statement succeeds.

```surql
USE NS typo DB typo;
//- { database: 'typo', namespace: 'typo' }

(INFO FOR ROOT).namespaces.typo;
//- 'DEFINE NAMESPACE typo'
```

A user who cannot define the namespace or database, such as a user with the `VIEWER` role, also gets a successful result from `USE`, but nothing is created. The [`STRICT`](/docs/reference/query-language/statements/define/database.md#defining-a-strict-database) clause of `DEFINE DATABASE` applies to the tables inside a database, and does not change what `USE` does.

The namespace and database named in the `surreal-ns` and `surreal-db` headers of an [HTTP request](/docs/reference/protocols/http-protocol.md) are not created in this way. A query that uses a namespace or database that does not exist fails with an error such as `The namespace 'mian' does not exist`.

A `DEFINE` statement, such as `DEFINE TABLE` or `DEFINE FUNCTION`, also creates a namespace or database that does not exist, including one named in the HTTP headers, and the same rule applies: it does so only when the user has permission to define it. A namespace user with the `VIEWER` role who runs `DEFINE FUNCTION` in a database that does not exist gets the error `IAM error: Not enough permissions to perform this action`, and no database is created. A namespace user with the `EDITOR` role creates the database and the function.

## Value returned by `USE` statement

_(since v3.0.0)_

Before SurrealDB 3.0.0, the output of a `USE` statement was `NONE`. Since then, each `USE` statement returns an object containing the current namespace and database.

```surql
USE NS main;
```

```surql title="Output"
{ database: 'main', namespace: 'main' }
```
