Skip to content

GORM Preload: N+1 Query Problem

DodaTech Updated 2026-06-24 1 min read

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

  1. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  2. Misunderstanding that String is [Char] with poor performance for large text operations
  3. Using foldl instead of foldl' 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

**Difference between Preload and JoinsPreload?**

Preload makes separate queries. JoinsPreload uses SQL JOINs.

How do I preload all associations?

Use db.Preload(clause.Associations).

Does Preload work with pagination?

Yes. Preload runs after the main query.


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