Select & Distinct
Column projection, aggregate scalars, map scanning, and DISTINCT.
Select
// Select restricts the selected columns. A single comma-separated string is
// split into columns.
func (db *DB) Select(columns ...string) *DBTwo call shapes do the same thing — arguments, or one comma-separated string:
db.Model(&crudUser{}).Select("name", "age")
db.Model(&crudUser{}).Select("name, age")Both render the same projection. The rule for how each entry is rendered
lives in the Select clause builder:
for i, col := range s.Columns {
if i > 0 {
b.WriteString(", ")
}
if strings.ContainsAny(col, "( )") {
b.WriteString(col)
} else {
b.WriteQuoted(col)
}
}Plain column names are identifier-quoted; anything containing a space or
parenthesis — aggregates, expressions, aliases — is written verbatim.
Dotted names quote each segment ("users"."name"), which is how joined
relations select their columns.
{
"select", Select{Columns: []string{"id", "users.name"}},
`SELECT "id", "users"."name"`, `SELECT "id", "users"."name"`, nil,
},SELECT "id", "users"."name"Quoting is trust boundary
Because an entry with spaces bypasses quoting, never interpolate user input
into a Select string — project columns from a fixed set.
Aggregates into a scalar
The verbatim rule is what lets Select carry an aggregate expression. Scan
it into a scalar:
var total int64
if err := db.Model(&crudUser{}).Select(`COUNT(*) AS total`).Scan(&total).Error; err != nil || total != 3 {
t.Errorf("scalar Scan = %d, %v", total, err)
}SELECT COUNT(*) AS total FROM "crud_users"The same shape works for SUM(...), MIN(...), MAX(...), and AVG(...)
— any single-value aggregate. This is also the building block for grouped
aggregates today; see GROUP BY & HAVING.
Scanning into a map
With a reduced projection, scan the row into a map[string]any instead of
a struct:
var mapped map[string]any
if err := db.Model(&crudUser{}).Select("name, age").Find(&mapped).Error; err != nil {
t.Fatalf("map Find: %v", err)
}
if mapped["name"] == nil {
t.Errorf("map = %v", mapped)
}Scan accepts a pointer to a struct, a slice of structs, a map, or a bare
scalar — the destination decides the scanning strategy.
Distinct
// Distinct adds DISTINCT to the SELECT clause.
func (db *DB) Distinct() *DBDistinct preserves any columns already selected on the chain and flips
the flag on the select clause:
{
"select distinct", Select{Columns: []string{"id"}, Distinct: true},
`SELECT DISTINCT "id"`, `SELECT DISTINCT "id"`, nil,
},SELECT DISTINCT "id"Order of calls does not matter: Select("id").Distinct() and
Distinct().Select("id") both keep the columns and set the flag, because
each call re-reads the previous select clause before overwriting it.