Skip to content

GORM Composite Primary Key — Complete Guide

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about GORM Composite Primary Key. We cover key concepts, practical examples, and best practices.

Composite keys in GORM -- Configure composite primary keys by adding gorm:'primaryKey' tags to multiple fields.

The Problem

GORM uses a single ID field as primary key by default. For composite keys, tag multiple fields with gorm:'primaryKey'.

Wrong

type UserRole struct {
    UserID uint
    RoleID uint
}
db.AutoMigrate(&UserRole{})

Output:

// GORM adds ID column automatically! Not intended.
type UserRole struct {
    UserID    uint `gorm:'primaryKey'`
    RoleID    uint `gorm:'primaryKey'`
    CreatedAt time.Time
}
db.Where(&UserRole{UserID: 1, RoleID: 2}).First(&ur)

Output:

// Proper composite primary key, no auto-ID

Prevention

  • Tag multiple fields with gorm:'primaryKey' for composite keys
  • Composite keys ordered by struct field order
  • Use gorm:"primaryKey;autoIncrement:false"
  • GORM uses all PK fields in WHERE
  • Works with associations

Common Mistakes with gorm composite key

  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

**Can I have auto-increment with composite key?**

One field can auto-increment, but unusual.

How to delete by composite key?

db.Where(&UserRole{UserID: 1, RoleID: 2}).Delete(&UserRole{}).

Do composite keys work with all databases?

Yes. All support composite primary keys.


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