Count, Pluck & Scan
Aggregates, column extraction, and scanning into scalars, maps, and raw rows.
The aggregation family runs ordinary queries whose destinations are not
model slices: a counter, a column, a scalar, a map, or a raw
*sql.Rows.
Count
// Count stores the number of matching rows in count.
// countColumns is shared by every Count call: Select.Build only reads it,
// and Statement/clone never append into Columns.Count(count *int64) replaces the select list with COUNT(*):
var count int64
if err := db.Model(&crudUser{}).Count(&count).Error; err != nil || count != 3 {
panic(err)
}SELECT COUNT(*) FROM "crud_users"ORDER BY is stripped before execution — PostgreSQL rejects an ORDER BY
column that is not in the aggregate's GROUP BY. Whatever the caller or a
scope added is removed; GROUP BY and HAVING you attached through
Clauses() are left intact (GORM #7516).
// TestAuditCountStripsOrderBy: ORDER BY must not survive into COUNT(*) —
// PostgreSQL rejects it (column must appear in GROUP BY). GORM #7516 class.Pluck
Pluck(column, dest) selects one column. The destination may be a slice
(the usual case) or a scalar (a single value):
var names []string
if err := db.Model(&crudUser{}).Order("id").Pluck("name", &names).Error; err != nil {
panic(err)
}
// names == [alice bob carol]var name string
if err := db.Model(&auditSaveUser{}).Where("id = ?", 1).
Pluck("name", &name).Error; err != nil {
panic(err)
}// Pluck scans one column into dest (a slice or scalar).Scan — into anything
Scan(dest) runs the accumulated chain and scans into dest without
model-slice assumptions:
A scalar — the aggregate pattern:
var total int64
if err := db.Model(&crudUser{}).Select(`COUNT(*) AS total`).Scan(&total).Error; err != nil || total != 3 {
panic(err)
}A struct slice — same as Find into a slice:
var scanned []crudUser
if err := db.Model(&crudUser{}).Scan(&scanned).Error; err != nil {
panic(err)
}A map — a two-column result scans as key → value pairs: the first selected column becomes the key, the second the value; later rows overwrite earlier ones:
var mapped map[string]any
if err := db.Model(&crudUser{}).Select("name, age").Find(&mapped).Error; err != nil {
panic(err)
}
// mapped == {"name": <age of the last row>}Alias scanning
Column aliases ending in __field can populate nested relations during a
Scan — profile__bio fills Profile.Bio on a has-one. See
scan_test.go:24
for the shape.
Row and Rows — manual scanning
When you want database/sql primitives, Row() returns the first row and
Rows() the result set; you close it:
row := db.Model(&crudUser{}).Where("name = ?", "alice").Select("age").Row()
var age int
if err := row.Scan(&age); err != nil {
panic(err)
}rows, err := db.Model(&crudUser{}).Order("id").Rows()
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
// scan each row yourself
}Two details worth knowing:
Row()never returns nil — a build error yields a sentinel row whoseScanfails, and the build error surfaces on the chain node (m.Error, GORM #7575).Rows()skips the scan callback entirely and hands you the driver rows.
Both build through the row callback chain; for fully hand-written SQL use
Exec and the raw-SQL surface — see
raw SQL.