Querying records
Find, First, Take, Last, inline conditions, FindInBatches, and FirstOrInit/FirstOrCreate.
The query family shares one callback chain — build, hooks, execute, scan — and differs only in the clauses they add before executing.
Find — a miss is not an error
Find scans every matching row into dest. When nothing matches, dest
is left as an empty slice and Error stays nil:
func (db *DB) Find(dest any, conds ...any) *DBvar empty []crudUser
if err := db.Find(&empty, "name = ?", "nobody").Error; err != nil || len(empty) != 0 {
// never reached: a miss is an empty slice, not an error
}dest is normally a pointer to a slice of structs; a pointer to a map also
works for two-column key → value scans (see
Count, Pluck & Scan). When Model is unset, the
model is inferred from dest.
First, Take, Last
All three limit the result to one row and return
fusion.ErrRecordNotFound when nothing matches:
First— orders by the primary key ascending, thenLIMIT 1.Last— orders by the primary key descending, thenLIMIT 1.Take— addsLIMIT 1with no implicit ordering.
// First scans the first row ordered by primary key; a miss returns
// ErrRecordNotFound.On models with a composite primary key, First/Last order by the full
key tuple — ORDER BY id ASC LIMIT 1 for a single key, ORDER BY a ASC, b ASC LIMIT 1 for two — so results stay deterministic when the first key
column ties (see
composite primary keys).
var first, last crudUser
_ = db.First(&first) // ORDER BY id ASC LIMIT 1
_ = db.Last(&last) // ORDER BY id DESC LIMIT 1
var one crudUser
db.Take(&one, map[string]any{"name": "bob"}) // no ORDER BYFind vs First
First, Take, and Last return ErrRecordNotFound when nothing
matches. Find returns an empty slice and a nil error instead.
Inline conditions
Every query finisher takes trailing conditions. They are applied to the chain before the query builds:
// applyConds appends finisher conditions to the instance in place — the
// finisher already materialized its own copy, so Where's clone would be
// pure churn.| Form | Meaning |
|---|---|
db.Find(&users, 42) | primary key equals 42 |
db.Find(&users, "name = ?", "ada") | SQL with placeholders |
db.Find(&users, "age > 18") | raw SQL fragment |
db.Find(&users, map[string]any{"name": "ada"}) | equality on each key |
db.Find(&users, &User{Name: "ada"}) | equality on each non-zero field |
A scalar condition binds the model's single primary key. On a composite
key model it is rejected with ErrInvalidValue rather than silently
matching every row that shares the first key column.
FindInBatches — keyset pagination
FindInBatches pages through a table in primary-key order, calling fc
once per batch with a session whose statement is bound to the fresh batch.
Rows are never skipped or repeated: each page resumes with
WHERE id > <last id> instead of a growing offset.
func (db *DB) FindInBatches(dest any, batchSize int, fc func(tx *DB, batch int) error) *DBvar seen []string
result := db.FindInBatches(&[]crudUser{}, 2, func(tx *DB, batch int) error {
var rows []crudUser
if err := tx.Find(&rows).Error; err != nil {
return err
}
for _, row := range rows {
seen = append(seen, row.Name)
}
return nil
})
// seen == [alice bob carol]; result.RowsAffected == number of batchesRules the finisher enforces:
batchSizemust be positive, or the chain carriesErrInvalidValue.- The model must have a primary key — pagination walks it.
- Composite keys paginate by row-value comparison,
("a", "b") > (?, ?), gated on the dialect'sfeature.RowValuesflag (declared by both built-in dialects). A dialect without the flag fails with an unsupported-feature error instead of paginating wrongly.
An error returned from fc stops the pagination and lands on the result's
Error.
FirstOrInit / FirstOrCreate
FirstOrInit finds the first matching row or initializes dest from
the conditions — it never writes to the database:
// FirstOrInit finds the first matching row or initializes dest from the
// conditions and Attrs/Assign values without writing to the database.FirstOrCreate builds on it: after initialization, if dest's primary key
is still zero, the struct is inserted.
var init crudUser
res := db.FirstOrInit(&init, map[string]any{"name": "eve"}, map[string]any{"age": 29})
// init.Name == "eve", init.Age == 29; the table is untouched
var created crudUser
res = db.FirstOrCreate(&created, map[string]any{"name": "frank"})
// created.ID != 0; one row now existsAttrs and Assign
The chainables Attrs and Assign feed the not-found branch:
Attrs— defaults for fields that the conditions did not set; used only when no row is found.Assign— values applied byFirstOrInit/FirstOrCreate— again only when no row is found in this implementation.
// Attrs supplies defaults used by FirstOrInit when no row is found.
// Assign supplies values applied by FirstOrInit and FirstOrCreate.Application order on a miss is Attrs, then Assign, then the map-shaped
conditions themselves — which is why the test above sees both "name" and
"age" on the struct.
Assign does not update a found row
Unlike GORM, Assign here is not applied when a row is found:
FirstOrInit returns the scanned row untouched, and FirstOrCreate
returns it without issuing an UPDATE. Treat Assign as "fill the struct
when we are about to insert", not "upsert".