Skip to content

Statements

USE

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.

Ensure that your database and namespace exist and you have started your database before using the Sql command option.

SurrealQL Syntax
USE [ NS @ns ] [ DB @db ];

The following query shows example usage of this statement if you have multiple namespaces and databases.

USE NS test; -- Switch to the 'main' Namespace
USE DB test; -- Switch to the 'main' Database
USE NS test DB test; -- Switch to the 'test' namespace and the 'test' database

You can also use the INFO Statement to check the current namespace and database.

INFO FOR NS; -- Check the current Namespace
INFO FOR DB; -- Check the current Database

Available 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.

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 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 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.

Available 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.

USE NS main;
Output
{ database: 'main', namespace: 'main' }

Was this page helpful?