GORM Soft Delete: Records Still Appear
In this tutorial, you'll learn about GORM Soft Delete: Records Still Appear. We cover key concepts, practical examples, and best practices.
Soft delete in GORM -- Use GORM's built-in soft delete by embedding gorm.DeletedAt to automatically filter deleted records.
The Problem
GORM adds WHERE deleted_at IS NULL for models with gorm.DeletedAt. If deleted records appear, the model may be missing the DeletedAt field.
Wrong
type User struct { ID uint; Name string }
db.Delete(&user) // Hard delete!
Output:
// Record permanently deleted
Right
type User struct {
ID uint
Name string
DeletedAt gorm.DeletedAt `gorm:"index"`
}
db.Delete(&user) // Soft delete
db.Find(&users) // WHERE deleted_at IS NULL
db.Unscoped().Find(&users) // All records
Output:
// deleted_at timestamp set, record not removed
Prevention
- Embed gorm.DeletedAt for soft delete
- Normal queries auto-filter deleted
- Use Unscoped() to include or permanently delete
- Add index on deleted_at
- Soft delete does not cascade
Common Mistakes with gorm soft delete
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty 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