The .query() family runs raw SurrealQL and is the foundation of the SDK — the CRUD builders compile to SurrealQL and dispatch through it. Queries can be supplied as a string with a JsonObject of bound parameters, or built with the surql DSL.
API references
Method | Description |
|---|---|
client.query(sql, vars) | Runs SurrealQL and returns the raw result |
client.queryAs<T>(sql, vars) | Runs SurrealQL and decodes the result to T |
client.queryResult(sql, vars) | Runs SurrealQL and returns a Result |
client.let(key, value) | Defines a session parameter |
client.unset(key) | Removes a session parameter |
Running a query
Pass SurrealQL and, optionally, a JsonObject of bound parameters. The result is returned as a JsonElement.
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
val result = client.query(
"SELECT * FROM person WHERE age > \$min_age",
buildJsonObject { put("min_age", 25) },
) Always bind variables with the vars argument rather than interpolating values into the query string. This avoids SurrealQL injection and lets the server cache query plans.
Decoding results
To decode a query result straight into your own types, use the inline [`.queryAs()`](/docs/reference/kotlin/api/core/surreal-client#query-as) helper with a [`@Serializable`](/docs/reference/kotlin/concepts/serialization) type.
import kotlinx.serialization.Serializable
@Serializable
data class Person(val name: String, val age: Int)
val people: List<Person> = client.queryAs(
"SELECT * FROM person WHERE age > \$min_age",
buildJsonObject { put("min_age", 25) },
)You can also decode an arbitrary [`JsonElement`](/docs/reference/kotlin/concepts/value-types) yourself with [`.decode()`](/docs/reference/kotlin/api/core/surreal-client#decode).
Result variants
Every networked call has a ...Result companion that returns a Result instead of throwing, which is useful when you prefer to handle failures functionally.
val outcome = client.queryResult("SELECT * FROM person")
outcome
.onSuccess { println("got $it") }
.onFailure { println("query failed: ${it.message}") }See Error handling for the exception hierarchy thrown by the non-Result variants.
Session parameters
Define parameters that persist for the session with .let(), and remove them with .unset(). These are referenced as $name in subsequent queries.
import kotlinx.serialization.json.JsonPrimitive
client.let("min_age", JsonPrimitive(18))
client.query("SELECT * FROM person WHERE age > \$min_age")
client.unset("min_age")Building queries
The surql DSL builds a parameterised BoundQuery with automatic binding of values and record identifiers.
import com.surrealdb.kotlin.query.surql
val bound = surql("SELECT * FROM person WHERE age > \$min", "min" to 25)
val result = client.query(bound)Learn more
SurrealClient API reference for complete method signatures
Query builder reference for the fluent builders and
surqlDSLData manipulation for CRUD with the builders
Serialization for working with
@Serializabletypes