diff --git a/models/repo/topic.go b/models/repo/topic.go
index ca533fc1e..b71f43bc8 100644
--- a/models/repo/topic.go
+++ b/models/repo/topic.go
@@ -377,3 +377,13 @@ func syncTopicsInRepository(sess db.Engine, repoID int64) error {
 	}
 	return nil
 }
+
+// CountOrphanedAttachments returns the number of topics that don't belong to any repository.
+func CountOrphanedTopics(ctx context.Context) (int64, error) {
+	return db.GetEngine(ctx).Where("repo_count = 0").Count(new(Topic))
+}
+
+// DeleteOrphanedAttachments delete all topics that don't belong to any repository.
+func DeleteOrphanedTopics(ctx context.Context) (int64, error) {
+	return db.GetEngine(ctx).Where("repo_count = 0").Delete(new(Topic))
+}
diff --git a/modules/doctor/dbconsistency.go b/modules/doctor/dbconsistency.go
index ac983f916..e2dcb63f3 100644
--- a/modules/doctor/dbconsistency.go
+++ b/modules/doctor/dbconsistency.go
@@ -158,6 +158,12 @@ func checkDBConsistency(ctx context.Context, logger log.Logger, autofix bool) er
 			Fixer:        actions_model.FixRunnersWithoutBelongingOwner,
 			FixedMessage: "Removed",
 		},
+		{
+			Name:         "Topics with empty repository count",
+			Counter:      repo_model.CountOrphanedTopics,
+			Fixer:        repo_model.DeleteOrphanedTopics,
+			FixedMessage: "Removed",
+		},
 	}
 
 	// TODO: function to recalc all counters