GORM Preload: N+1 Query Problem
In this tutorial, you'll learn about GORM Preload: N+1 Query Problem. We cover key concepts, practical examples, and best practices.
GORM Preload vs Joins -- Use GORM's Preload to eagerly load associations and avoid the N+1 query problem.
The Problem
Accessing associated collections without Preload triggers a separate query for each parent -- the N+1 problem. Preload loads all in 1-3 queries.
Wrong
var users []User
db.Find(&users)
for _, u := range users {
db.Model(&u).Association("Orders").Find(&u.Orders)
}
Output:
// 1 + N queries. 100 users = 101 queries!
Right
var users []User
db.Preload("Orders").Find(&users)
db.Preload("Orders.Items").Preload("Profile").Find(&users)
Output:
// 1 + 1 queries. 100 users = 2 queries!
Prevention
- Use Preload for most association loading
- Preload supports nested: "Orders.Items.Product"
- Use JoinsPreload for inner JOIN style
- Use Preload with conditions: Preload("Orders", "amount > ?", 100)
- Limit association query with Preload("Orders", func(db *gorm.DB) *gorm.DB { return db.Limit(10) })
Common Mistakes with gorm preload
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
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