Soft delete lets you “delete” records by setting a timestamp rather than removing the row. Soft-deleted records are excluded from normal queries and can be recovered or permanently removed later.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/go-gorm/gorm/llms.txt
Use this file to discover all available pages before exploring further.
How soft delete works
When your model embedsgorm.Model or includes a gorm.DeletedAt field, GORM automatically enables soft delete for that model.
gorm.DeletedAt type implements QueryClauses, UpdateClauses, and DeleteClauses interfaces. GORM uses these to intercept operations automatically:
- Delete — sets
deleted_atto the current time instead of issuingDELETE. - Find / First / Last — adds
WHERE deleted_at IS NULLautomatically. - Update — also adds
WHERE deleted_at IS NULLto avoid updating soft-deleted rows.
Soft deleting a record
Querying soft-deleted records
Normal queries exclude soft-deleted records:db.Unscoped() to include soft-deleted records:
Permanently deleting a record
ChainUnscoped() before Delete to issue a real DELETE statement:
Restoring a soft-deleted record
Setdeleted_at back to NULL using an update:
Custom DeletedAt field name
GORM identifies the soft-delete field by its type (gorm.DeletedAt). You can rename the column using a struct tag:
Soft delete with a zero-value timestamp
Some databases have trouble indexingNULL efficiently. You can configure GORM to use a zero time value instead of NULL via the softDeleteZeroValueUnixSecond tag. For flag-based soft delete, implement the SoftDeleteDeleteClause interface on a custom type.
The
gorm.io/plugin/soft_delete package provides additional soft-delete strategies including Unix-second timestamps and boolean flags.Indexes on DeletedAt
Add an index ondeleted_at to keep queries fast on large tables. gorm.Model already includes gorm:"index" on DeletedAt.
deleted_at alongside frequently filtered columns: