Executing queries
The Go SDK provides two ways to execute SurrealQL queries: Query for typed, parameterized queries and QueryRaw for composing multiple statements with per-statement results. Both are generic functions that work with *DB, *Session, and *Transaction.
This page covers running queries, parameterizing them, handling multi-statement results, and managing connection-scoped variables.
API References
| Function | Description |
|---|---|
surrealdb.Query[T](ctx, s, sql, vars) | Executes a SurrealQL query with typed results |
surrealdb.QueryRaw(ctx, s, queries) | Executes a batch of query statements with per-statement results |
db.Let(ctx, key, val) | Defines a variable on the connection for use in queries |
db.Unset(ctx, key) | Removes a previously defined connection variable |
Running a query
The Query function executes a SurrealQL string and returns typed results. The first type parameter specifies the expected result type. The second parameter s can be a *DB, *Session, or *Transaction.
The function returns *[]QueryResult[T], where each QueryResult contains the Status, execution Time, Result, and an optional Error for that statement.
Parameterizing queries
Always use parameters ($name) instead of string interpolation to prevent injection attacks and ensure correct CBOR encoding of value types.
Pass nil for the variables map when no parameters are needed:
Handling multi-statement queries
When a query string contains multiple statements, Query returns a QueryResult for each statement. Check the Error field on each result to detect per-statement failures.
Note
Composing queries with QueryRaw
QueryRaw lets you compose a batch of QueryStmt objects, each with its own SQL and variables. After execution, each statement's result is available via .GetResult().
Defining connection variables
Use .Let() to define a variable that persists on the connection and is available in all subsequent queries. Use .Unset() to remove it.
Connection variables are scoped to the connection (or session if using sessions). They do not affect other connections. You can also build queries programmatically using the query builder.
Learn more
DB API reference for complete method signatures and parameters
Data manipulation for typed CRUD operations
Error handling for distinguishing between query errors and transport errors
Types reference for
QueryResultandQueryStmtdefinitionsSurrealQL statements for the query language syntax