Skip to content

Concepts

Query builder

Warning

The contrib/surrealql package that provides this feature is outside the backward compatibility guarantee of the SDK. Its API can change in a minor release.

The surrealql package builds SurrealQL statements with Go method calls. It binds each value as a parameter, and does not write the value into the text of the query. It returns the SurrealQL and a map of variables, which you pass to surrealdb.Query. This page covers each kind of statement that the package builds. The comment below each example shows the SurrealQL that the example builds.

The query builder is part of the SDK module, so it needs no other go get:

import "github.com/surrealdb/surrealdb.go/v2/contrib/surrealql"

Every builder has a .Build() method that returns the SurrealQL and a map[string]any of variables. Pass both to surrealdb.Query:

q := surrealql.Select("user").Where("age > ?", 18).OrderBy("name").Limit(10)
sql, vars := q.Build()
// SELECT * FROM user WHERE (age > $param_1) ORDER BY name LIMIT 10

results, err := surrealdb.Query[[]User](ctx, db, sql, vars)

The builder writes a table name that you give as a string into the SurrealQL as it is. Only pass names that your own code chooses. To bind the target as a parameter too, pass a models.RecordID or a models.Table.

Select starts a SELECT statement. Chain .Fields(), .Field(), .Where(), .GroupBy(), .OrderBy(), .Limit() and the other methods to refine it:

surrealql.Select("user")
// SELECT * FROM user

surrealql.Select("user").Fields("name", "email").Where("active = ?", true)
// SELECT name, email FROM user WHERE (active = $param_1)

surrealql.Select("user").
	Field(surrealql.Expr("count()").As("total")).
	GroupBy("department")
// SELECT count() AS total FROM user GROUP BY department

SelectOnly builds SELECT ... FROM ONLY, which returns one record instead of an array:

surrealql.SelectOnly(models.NewRecordID("user", "tobie")).Fields("name")
// SELECT name FROM ONLY $from_id_1

.Where() takes a condition with ? placeholders, and binds each value as a parameter. Each further call to .Where() adds another condition with AND:

surrealql.Select("product").
	Where("price < ?", 100).
	Where("category = ?", "electronics")
// SELECT * FROM product WHERE (price < $param_1) AND (category = $param_2)

The builder puts each condition in brackets, so an OR inside one condition stays within that condition.

surrealql.Select("user").
	OrderByDesc("created_at").
	Limit(20).
	Start(40)
// SELECT * FROM user ORDER BY created_at DESC LIMIT 20 START 40

The package has helpers that build a models.Range, such as RangeBeginInclusiveEndExclusive and RangeOpen. To select a range of records, use a range as the ID of a models.RecordID:

surrealql.Select(models.RecordID{
	Table: "reading",
	ID:    surrealql.RangeBeginInclusiveEndExclusive(2, 4),
})
// SELECT * FROM $from_id_1, where $from_id_1 is reading:2..4

The same value works as the target of surrealdb.Select.

Create builds a CREATE statement. Set fields with .Set(), or give the whole content with .Content():

surrealql.Create("user").
	Set("name", "Alice").
	Set("age", 30)
// CREATE user SET name = $param_1, age = $param_2

surrealql.Create("user").Content(map[string]any{
	"name": "Alice",
	"age":  30,
})
// CREATE user CONTENT $content_1

CreateOnly builds CREATE ONLY, which returns one record:

surrealql.CreateOnly("user").Set("name", "Alice").ReturnNone()
// CREATE ONLY user SET name = $param_1 RETURN NONE

Update builds an UPDATE statement, with .Set() and .Where():

surrealql.Update("user").
	Set("active", false).
	Where("last_login < ?", "2025-01-01")
// UPDATE user SET active = $param_1 WHERE (last_login < $param_2)

.Set() also takes a compound operation, such as -= or +=, with a placeholder:

surrealql.Update(models.NewRecordID("product", "apple")).Set("stock -= ?", 1)
// UPDATE $id_1 SET stock -= $param_1

Upsert builds an UPSERT statement, which creates a record when it does not exist and updates it when it does. Choose how to give the data with .Set(), .Content(), .Merge(), .Patch() or .Replace():

surrealql.Upsert(models.NewRecordID("user", "tobie")).
	Set("name", "Tobie").
	Set("active", true)
// UPSERT $id_1 SET name = $param_1, active = $param_2

surrealql.Upsert("user:tobie").Content(map[string]any{
	"name":   "Tobie",
	"active": true,
})
// UPSERT user:tobie CONTENT $upsert_content_1

surrealql.Upsert("user:tobie").Merge(map[string]any{"active": false})
// UPSERT user:tobie MERGE $upsert_merge_1

The Upsert builder also has .Where(), .Timeout(), .Parallel() and .Explain().

Delete builds a DELETE statement:

surrealql.Delete("session").Where("expired_at < ?", "2025-01-01")
// DELETE session WHERE (expired_at < $param_1)

Insert builds an INSERT statement, for one record, several records, or lists of values:

surrealql.Insert("user").Value(map[string]any{
	"name": "Alice",
	"age":  30,
})
// INSERT INTO user $insert_data_1

surrealql.Insert("user").
	Fields("name", "age").
	Values("Alice", 30).
	Values("Bob", 25)
// INSERT INTO user (name, age) VALUES ($insert_0_0_1, $insert_0_1_1), ($insert_1_0_1, $insert_1_1_1)

.Relation() builds INSERT RELATION, for edges between records:

surrealql.Insert("knows").Relation().Value(map[string]any{
	"in":  models.NewRecordID("user", "tobie"),
	"out": models.NewRecordID("user", "jaime"),
})
// INSERT RELATION INTO knows $insert_data_1

To update a record that already exists, add ON DUPLICATE KEY UPDATE:

surrealql.Insert("product").
	Fields("id", "stock").
	Values(models.NewRecordID("product", "apple"), 10).
	OnDuplicateKeyUpdateRaw("stock += $input.stock")
// INSERT INTO product (id, stock) VALUES ($insert_0_0_1, $insert_0_1_1) ON DUPLICATE KEY UPDATE stock += $input.stock

Relate builds a RELATE statement between two records:

surrealql.Relate(
	models.NewRecordID("user", "tobie"),
	"wrote",
	models.NewRecordID("post", "first"),
).Set("created_at", "2026-01-01")
// RELATE $id_1->wrote->$id_2 SET created_at = $param_1

Expr builds an expression with ? placeholders, for a function call, a graph traversal, or any expression that needs bound values:

surrealql.Select("user").
	Field(surrealql.Expr("math::mean([?, ?, ?])", 1, 2, 3).As("avg"))
// SELECT math::mean([$param_1, $param_2, $param_3]) AS avg FROM user

surrealql.Select(surrealql.Expr("?->knows->user", models.NewRecordID("user", "tobie")))
// SELECT * FROM $from_param_1->knows->user

The statements that change records take a return clause:

surrealql.Create("user").Set("name", "Alice").ReturnNone()
// CREATE user SET name = $param_1 RETURN NONE

surrealql.Update("user").Set("active", true).Return("AFTER")
// UPDATE user SET active = $param_1 RETURN AFTER

surrealql.Delete("session").ReturnBefore()
// DELETE session RETURN BEFORE

ShowChangesForTable builds a SHOW CHANGES statement, for a table defined with a change feed. .SinceVersionstamp() starts from a versionstamp, and .Limit() sets the maximum number of changes:

surrealql.ShowChangesForTable("reading").SinceVersionstamp(versionstamp).Limit(10)
// SHOW CHANGES FOR TABLE reading SINCE 65536 LIMIT 10, for a versionstamp of 65536

Pass a versionstamp exactly as SHOW CHANGES returned it. SINCE is inclusive. When you continue from the last change that you received, the server returns that change again. Version 1 of the SDK shifted the versionstamp right by 16 bits, as the migration guide describes.

Begin builds a text transaction, which runs its statements in one request and commits them together. Add statements with .Do(), variables with .Let(), and raw SurrealQL with .Raw():

q := surrealql.Begin().
	Let("amount", 100).
	Do(surrealql.Update(models.NewRecordID("account", "one")).Set("balance -= $amount")).
	Do(surrealql.Update(models.NewRecordID("account", "two")).Set("balance += $amount"))

sql, vars := q.Build()
Output
BEGIN TRANSACTION;
LET $amount = 100;
UPDATE $id_1 SET balance -= $amount;
UPDATE $id_2 SET balance += $amount;
COMMIT TRANSACTION;
Note

A text transaction is not an interactive transaction. A text transaction runs every statement in a single request, so your code cannot read a result before the next statement runs. An interactive transaction runs one statement at a time.

Was this page helpful?

Last updated