Conditions
Where and Or with string, map, and struct conditions — precedence, soft delete, and error paths.
The two chainables
Where AND-joins a condition; Or OR-joins one. Both accept a string with
? placeholders, a map[string]any, or a struct.
// Where adds an AND-joined condition. Struct and map values build equality
// expressions from their non-zero fields.
func (db *DB) Where(query any, args ...any) *DB {
return db.addCondition(query, args, false)
}// Or adds an OR-joined condition.
func (db *DB) Or(query any, args ...any) *DB {
return db.addCondition(query, args, true)
}Each call appends a condition to the statement's where clause; the clause
is rendered in registration order, left to right.
String conditions
A string is used verbatim, with each ? consuming the next argument.
sql := db.ToSQL(func(tx *fusion.DB) *fusion.DB {
return tx.Model(&User{}).Where("name = ?", "Ada").Find(&[]User{})
})SELECT * FROM "users" WHERE name = 'Ada'Map conditions — stable SQL
A map[string]any becomes one "key" = ? equality per entry. Map
iteration order is random in Go, so keys are sorted before rendering:
case map[string]any:
// Sorted keys keep the SQL text stable across calls so prepared-stmt
// caches and ToSQL reproducibility are not defeated by map order.
keys := make([]string, 0, len(v))
for key := range v {
keys = append(keys, key)
}
sort.Strings(keys)This matters twice over: the prepared-statement cache keys on SQL text, and
ToSQL is documented as reproducible. A regression test renders the same
map condition thirty times and demands byte-identical SQL
(GORM #5846 class):
cond := map[string]any{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
first := db.ToSQL(func(tx *DB) *DB {
return tx.Table("audit_plain_users").Where(cond).Find(&[]auditPlainUser{})
})
for i := 0; i < 30; i++ {
got := db.ToSQL(func(tx *DB) *DB {
return tx.Table("audit_plain_users").Where(cond).Find(&[]auditPlainUser{})
})
if got != first {
t.Fatalf("unstable SQL for identical map condition (GORM #5846)")
}
}Because keys sort, a two-key map renders in alphabetical order:
WHERE "age" = 30 AND "name" = 'ada'Struct conditions
A struct (or pointer to one) becomes one "column" = ? per non-zero
field, matched against the parsed schema:
var exprs []clause.Expression
for _, field := range table.Fields {
value := fieldAt(rv, field.Index)
if !value.IsValid() || field.IsZero(value) {
continue
}
exprs = append(exprs, clause.Expr(quoteIdentifier(db, field.DBName)+" = ?", value.Interface()))
}This is what makes delete-by-value work — only Name is non-zero, so only
it becomes a condition:
del := db.Delete(&crudUser{Name: "carol"})DELETE FROM "crud_users" WHERE "name" = 'carol'Zero fields are skipped
A zero field cannot be expressed with a struct condition — Age: 0 is
indistinguishable from an unset field. Pass a map or a string condition
when you need to match a zero value.
Or joins, precedence holds
Or appends an OR-joined condition to the list. Chained calls read
left to right:
db.Model(&crudUser{}).Where("age > ?", 18).Or("name = ?", "bob").Find(&users)WHERE age > 18 OR name = 'bob'The precedence contract lives in the clause builder itself:
// buildConditions renders conds, prefixing each with its join. A condition
// holding multiple expressions is parenthesized unless it is the only one,
// so a list reads left-to-right: appending a predicate to `a OR b` yields
// `(a OR b) AND x`, never `a OR b AND x`.In practice: a condition built from clause.Or(expr1, expr2) — one
condition holding two expressions — is parenthesized the moment it sits in
a list with anything else, so the group's meaning survives later appends.
The raw-clause form of this is shown in
Raw clauses.
Soft delete never leaks through Or
The live-row filter (deleted_at IS NULL) is injected as one more AND-ed
predicate. A top-level OR in the caller's conditions would otherwise bind
tighter than that AND — "a OR b AND deleted_at IS NULL" — so the builder
regroups the caller's conditions into one parenthesized group first:
// A top-level OR in the caller's conditions would bind tighter than the
// appended AND ("a OR b AND deleted_at IS NULL"), letting deleted rows
// back in — regroup everything so it renders "(a OR b) AND deleted...".The regression test soft-deletes row "a", then queries name = 'a' OR name = 'b':
var got []softUser
if err := db.Model(&softUser{}).
Where("name = ?", "a").
Or("name = ?", "b").
Find(&got).Error; err != nil {
t.Fatal(err)
}WHERE (name = 'a' OR name = 'b') AND "deleted_at" IS NULLThe deleted row can never reappear through an Or branch
(GORM #6998/#5652 class). See Soft delete for
the full behavior.
Invalid condition types error
Anything that is not a string, map, or struct records
ErrInvalidValue on the chain — no panic, the finisher reports it:
{
name: "invalid where value",
want: ErrInvalidValue,
run: func() error { return db.Where(42).Find(&[]errPathUser{}).Error },
},res := db.Model(&User{}).Where(42).Find(&users)
if errors.Is(res.Error, fusion.ErrInvalidValue) {
// not a string, map, or struct
}Inline conditions on finishers
First, Take, Last, Find, and Delete accept inline conditions and
apply them exactly like Where before executing:
var missing crudUser
if err := db.First(&missing, "name = ?", "nobody").Error; !errors.Is(err, ErrRecordNotFound) {
t.Errorf("First miss = %v", err)
}A bare int/int64 inline condition matches the primary key:
db.First(&got, user.ID). Multiple inline conditions AND together.