Skip to content

Concepts

Executing queries

The Java SDK provides methods for executing raw SurrealQL queries against SurrealDB. You can run single or multi-statement queries, bind parameters for safe variable injection, and call server-side functions.

Method

Description

db.query(sql)

Executes a SurrealQL query

db.queryBind(sql, params)

Executes a parameterised query

db.run(name, args)

Runs a SurrealDB function

The .query() method executes one or more SurrealQL statements and returns a Response. Use .take(int) to extract the result of a specific statement by its zero-based index, or .take(Class, int) to deserialise the result into a typed Java object.

Response response = db.query("SELECT * FROM users; SELECT * FROM posts;");

Value users = response.take(0);
List<Post> posts = response.take(Post.class, 1);

The .queryBind() method accepts a Map<String, ?> of parameters that are safely injected into the query. Parameterised queries prevent SurrealQL injection and ensure values are properly escaped.

Map<String, Object> params = Map.of("min_age", 18);

Response response = db.queryBind(
    "SELECT * FROM users WHERE age > $min_age",
    params
);

List<User> users = response.take(User.class, 0);

Always prefer .queryBind() over string concatenation when incorporating user-provided values into queries.

The Response object contains the results of all statements in the query. Use .take(int) to get a raw Value, or .take(Class, int) to deserialise into a POJO. The .size() method returns the number of statement results.

Response response = db.query(
    "CREATE users SET name = 'Alice'; SELECT * FROM users;"
);

int statementCount = response.size();

Value created = response.take(0);
List<User> users = response.take(User.class, 1);

See Value types for details on working with the Value class and type conversions.

The .run() method calls a server-side function defined with DEFINE FUNCTION. Pass the function name and any arguments.

Value result = db.run("fn::calculate_total", 100, 0.2);

Was this page helpful?