Skip to content

GORM Joins: Filtering on Associated Tables

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about GORM Joins: Filtering on Associated Tables. We cover key concepts, practical examples, and best practices.

GORM Joins for filtering -- Use GORM's Joins method to filter parent records based on conditions in child tables.

The Problem

Preload loads associated data but cannot filter the parent query. To find users with orders over $100, use JOIN with WHERE clause.

Wrong

var users []User
db.Where("orders.amount > ?", 100).Find(&users)

Output:

// ERROR: column "orders" does not exist
var users []User
db.Joins("JOIN orders ON orders.user_id = users.id").
   Where("orders.amount > ?", 100).
   Distinct().Find(&users)

Output:

// Returns only users with orders over $100

Prevention

  • Use Joins("JOIN ...") for raw SQL JOINs
  • Use Joins("AssociationName") for association-based JOINs
  • Always use Distinct() after JOINs
  • Use JoinsPreload for JOIN filtering + association loading
  • Joins supports LEFT JOIN

Common Mistakes with gorm joins

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks

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

**Can I use Joins with Preload together?**

Yes. Joins filters parent, Preload loads associated data.

Does GORM support raw SQL JOINs?

Yes. db.Raw("SELECT * FROM users JOIN orders ON ...").Scan(&result).

How do I avoid duplicate rows?

Use .Distinct() or .Group("users.id").


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