Skip to content

GORM Raw SQL: Scan Not Populating

DodaTech Updated 2026-06-24 1 min read

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
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

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. 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

**Difference between Scan and Find?**

Scan works with raw queries. Find works with GORM query builder.

Can I use named parameters?

Yes. Use sql.Named("name", value).

Does GORM prepare raw SQL?

No. Raw SQL is sent directly. Use parameterized values.


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