Skip to Content
fusion-orm
Querying

Advanced query

Subqueries, CTEs, grouped conditions, IN lists, DTO projection, row locking, iteration, and the honest boundary of the chain.

This page is the fusion-orm counterpart to GORM's "Advanced Query": the techniques you reach for once Where/Order/Limit are not enough. Every snippet below is rendered by the same builder the executor uses, so the SQL shown is the SQL that runs (modulo placeholder display — see Raw SQL & DryRun).

Where a GORM idiom has no fusion-orm equivalent, this page says so and points at the closest supported shape instead of pretending the API exists. The builder is deliberately small: a handful of chainables plus the raw clause catalog. Most "advanced" SQL is raw fragments carried through Where or Clauses.

Subqueries

There is no subquery-builder object. A subquery is a raw SQL fragment with ? placeholders, handed to Where; the fragment renders verbatim and its arguments bind exactly like a top-level predicate:

db.Model(&User{}).
	Where("id IN (SELECT user_id FROM posts WHERE title LIKE ?)", "%go%").
	Find(&users)
SELECT * FROM "users" WHERE id IN (SELECT user_id FROM posts WHERE title LIKE '%go%')

Arguments are bound, not interpolated: on PostgreSQL the ? becomes $1 on the wire. Nesting a *DB as the argument — GORM's Where("amount > (?)", db.Table(...)) — is not supported; the argument would be bound as a value, not rendered as SQL. Keep subqueries as strings.

Common table expressions

CTEs are clause.With, registered through Clauses. The CTE body is a raw string; the name is identifier-quoted by the dialect and the clause builds first, before select:

chain · Godb.Model(&User{})
db.Clauses(clause.With{
  CTEName:  "adults",
  Subquery: "SELECT id FROM users WHERE age >= 18",
}).
  Model(&User{}).
  Where("id IN (SELECT id FROM adults)").
  Find(&users)
SQL · compiled
WITH "adults" AS (SELECT id FROM users WHERE age >= 18)
SELECT * FROM "users"
WHERE id IN (SELECT id FROM adults)
both dialectswith builds first (slot 1 of 16)src: clause/query.go:169, statement.go:74

Because the body is a string, it cannot carry bound variables. Inline constants you control, or move the parameters into the outer query. See Complex queries for the full treatment.

Grouped conditions

Where/Or already parenthesise OR groups so appending another predicate cannot change their meaning. For explicit grouping, register a clause.Where whose Conds nest: a Condition with Conds renders as a parenthesised group, and Condition.Join picks the separator (AND by default, OR when set):

chain · Godb.Model(&User{})
db.Clauses(clause.Where{Conds: []clause.Condition{{
  Join: "OR",
  Conds: []clause.Condition{{
    Join:  "AND",
    Exprs: []clause.Expression{
      clause.Expr("age > ?", 18),
      clause.Expr("name = ?", "ada"),
    },
  }},
}}}).
  Model(&User{}).
  Find(&users)
SQL · compiled
SELECT * FROM "users" WHERE (age > 18 AND name = 'ada')
both dialectsnested Conds → parenthesessrc: clause/clause.go:61-79

Append a further predicate and the group stays intact:

SELECT * FROM "users" WHERE (age > 18 AND name = 'ada') AND active = TRUE

There is no chainable Group or Having — see GROUP BY & HAVING for the raw-SQL path.

IN lists — what works

These shapes render correctly:

// Placeholder per element.
db.Model(&User{}).Where("id IN (?, ?, ?)", 1, 2, 3).Find(&users)

// A raw row-value tuple list.
db.Model(&User{}).
	Where("(name, age) IN ((?, ?), (?, ?))", "a", 1, "b", 2).
	Find(&users)
SELECT * FROM "users" WHERE id IN (1, 2, 3)
SELECT * FROM "users" WHERE (name, age) IN (('a', 1), ('b', 2))

These GORM shapes do not work here, because each ? consumes exactly one argument and slice arguments are never expanded:

AttemptResult
Where("id IN ?", []int64{1, 2, 3})binds the slice as one value → IN '[1 2 3]'
Where("id IN (?)", []int64{1, 2, 3})same, wrapped: IN ('[1 2 3]')
Where([]int64{1, 2, 3})rejected with ErrInvalidValue (not a struct)

Write one ? per element, or build the fragment yourself. Relation preloads and composite-key keyset pagination generate their own IN lists internally; you do not spell them by hand.

Projecting into a DTO

Select with a destination struct that carries only the columns you want is the supported replacement for GORM's "smart select". The projection is explicit — you name the columns:

type APIUser struct {
	Name string
	Age  int
}

var apiUsers []APIUser
db.Model(&User{}).Select("name", "age").Find(&apiUsers)
SELECT "name", "age" FROM "users"

Project explicitly

Unlike GORM, the destination type does not drive the SELECT list. The scanner plans against the model schema, and a destination that does not line up with the selected columns is not validated — it can fail or panic at scan time. Always list the columns your DTO reads, and keep the field order and types aligned with them.

Aggregates, scalars, and maps

Aggregate calls survive in Select as raw fragments; scan the one-row result into a scalar:

var total int64
db.Model(&User{}).Select("COUNT(*) AS total").Scan(&total)

var avg float64
db.Model(&User{}).Select("AVG(age)").Scan(&avg)

Count, Pluck, and Distinct cover the common cases:

var n int64
db.Model(&User{}).Where("age > ?", 18).Count(&n) // ORDER BY is stripped

var names []string
db.Model(&User{}).Order("id").Pluck("name", &names)

db.Model(&User{}).Select("name").Distinct().Find(&users)
SELECT COUNT(*) FROM "users" WHERE age > 18
SELECT "name" FROM "users" ORDER BY id
SELECT DISTINCT "name" FROM "users"

Pluck rebuilds the SELECT

Pluck replaces the select clause with its single column, so Distinct does not survive across it. If you need SELECT DISTINCT col, pair Select(col) with Distinct() and use Find, as above.

Map destinations are not GORM's "row as map". A map is a two-column name→value scan (columns[0] becomes the key, columns[1] the value), and it needs a Model so the table is known — Table(...) alone cannot infer one for a map destination:

var byName map[string]any
db.Model(&User{}).Select("name, age").Order("id").Find(&byName)
// byName == {"name": <last age>} — the first column is the key

For row-shaped results, use a struct DTO. Reach for the pool (db.DB()) when you truly need dynamic columns.

Window functions and computed columns

Any Select entry containing a space or parenthesis passes through verbatim, so window functions render without a builder:

db.Model(&User{}).
	Select("id", "name", "ROW_NUMBER() OVER (ORDER BY id) AS rn").
	Where("age > ?", 18).
	Find(&users)
SELECT "id", "name", ROW_NUMBER() OVER (ORDER BY id) AS rn FROM "users" WHERE age > 18

Two rules: Select splits on commas (keep a window frame with a comma in its own argument), and the struct scanner skips columns the model does not map — rn will not land on User. Consume computed columns with a report DTO (Select + struct dest) or Row/Rows for a manual scan.

Iterating rows

Row and Rows hand you database/sql objects for streaming and manual scanning:

rows, err := db.Model(&User{}).Select("id", "name").Order("id").Rows()
if err != nil {
	return err
}
defer rows.Close()

for rows.Next() {
	var id int64
	var name string
	if err := rows.Scan(&id, &name); err != nil {
		return err
	}
	// ...
}
return rows.Err()

There is no exported ScanRows equivalent — rows.Scan is the API. For bulk work in batches, prefer FindInBatches, which pages by primary key without re-reading the table (see Querying records).

Row locking

Locking(true) registers clause.Locking, which renders FOR UPDATE:

tx := db.Model(&User{}).Where("id = ?", 1).Locking(true).Find(&user)
SELECT * FROM "users" WHERE id = 1 FOR UPDATE

FOR UPDATE only

clause.Locking carries a single Enabled flag — there is no Strength, Options, or Table, so FOR SHARE, NOWAIT, and SKIP LOCKED are not available. It also has no dialect feature gate: it renders verbatim, so only lock on databases that support row-level locking, and pair it with Transaction/Begin so the lock is released.

First or init, first or create

FirstOrInit finds a row or fills the destination without writing; FirstOrCreate inserts when the primary key is still zero. Attrs supplies defaults for the not-found branch:

var user User
db.Where(User{Name: "ada"}).Attrs(User{Age: 36}).FirstOrInit(&user)

var created User
db.Where(User{Name: "grace"}).FirstOrCreate(&created)

Assign differs from GORM

Assign applies only on the not-found path here: unlike GORM, it does not update a row that is found. Treat it as "fill values before insert", not "upsert". See Querying records.

Returning modified rows

clause.Returning adds RETURNING to an UPDATE or DELETE, gated on the dialect's Returning feature flag:

db.Model(&User{}).
	Clauses(clause.Returning{Columns: []string{"id"}}).
	Where("id = ?", 1).
	Update("name", "ada")

db.Model(&User{}).
	Clauses(clause.Returning{Columns: []string{"id"}}).
	Where("id = ?", 1).
	Delete(nil)
UPDATE "users" SET "name" = 'ada' WHERE id = 1 RETURNING "id"
DELETE FROM "users" WHERE id = 1 RETURNING "id"

On a dialect without the flag the clause is a no-op — the statement still executes, just without returned rows. (The update above is on a model with no UpdatedAt; with one, the timestamp surfaces in SET and can be returned too.)

Not expressible through the chain

These GORM features have no fusion-orm chainable today. The table gives the closest supported shape; the method names are deliberately written without call syntax because they do not exist on *DB.

GORM idiomfusion-ormWhere to go
Omit / per-field allow-listSelect plus tag permissions ->, <-, -Tag reference
Notwrite the negated predicate: Where("status <> ?", s)Conditions
Raw(...) then scanExec for writes; Row/Rows or the db.DB() pool for readsRaw SQL
SQL-expression update values (gorm.Expr / clause.Expr as a value)not supported — the value binds as a literal; use Exec for SQL arithmeticRaw SQL
Group / Havingno chainables and no clause slotGROUP BY & HAVING
Subquery object, FROM subquery, table aliasraw SQL through the poolComplex queries
Named arguments (sql.Named)positional ? placeholders onlyConditions
Optimizer / index hintsraw SQL through the poolRaw SQL
Find into a row mapstruct DTO, or the two-column map shape aboveAggregation
ScanRowsRows then rows.ScanRaw SQL
Locking strengths (FOR SHARE, NOWAIT)FOR UPDATE onlyTransactions

Inspect before you run

Every example here can be captured without executing it. ToSQL returns the rendered string; DryRun leaves SQL and Vars on the statement so you can assert on them:

sql := db.ToSQL(func(tx *fusion.DB) *fusion.DB {
	return tx.Model(&User{}).Where("id IN (?, ?, ?)", 1, 2, 3).Find(&[]User{})
})

See Raw SQL & DryRun for the capture forms and their caveats.

Next

On this page