GORM Raw SQL: Scan Not Populating
In this tutorial, you'll learn about GORM Raw SQL: Scan Not Populating. We cover key concepts, practical examples, and best practices.
Raw SQL queries in GORM -- Execute raw SQL with db.Raw().Scan() and map results to structs correctly.
The Problem
db.Raw() executes raw SQL but Scan requires column names matching struct fields (or tags). Mismatched names cause silent zero-value fields.
Wrong
var stats []map[string]interface{}
db.Raw("SELECT count(*) as cnt, status FROM orders GROUP BY status").Scan(&stats)
Output:
// Works but no type safety
Right
type OrderStat struct {
Count int `gorm:"column:cnt"`
Status string `gorm:"column:status"`
}
var stats []OrderStat
db.Raw("SELECT count(*) as cnt, status FROM orders GROUP BY status").Scan(&stats)
Output:
// Properly typed and populated
Prevention
- Use Scan for multiple rows from Raw
- Use Row for single row: db.Raw(...).Row().Scan(&field)
- Use Exec for INSERT/UPDATE
- Map columns with gorm:"column:col_name"
- Use db.Rows() for raw row iteration
Common Mistakes with gorm raw sql
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro