Soft delete vs hard delete: which should you use?
Soft delete vs hard delete: which should you use?
A hard delete removes the row with DELETE. A soft delete keeps the row and marks it as deleted, usually with a deleted_at timestamp or an is_deleted flag.
-- soft delete
ALTER TABLE users ADD COLUMN deleted_at TIMESTAMP NULL;
UPDATE users SET deleted_at = CURRENT_TIMESTAMP WHERE id = 42;
-- every read must exclude deleted rows
SELECT * FROM users WHERE deleted_at IS NULL;
| Pros | Cons |
|---|---|
| Easy undo and audit trail | Every query must remember the filter (bugs leak deleted data) |
| Foreign keys stay valid; history is kept | UNIQUE constraints break: a deleted bob@x.com blocks a new signup |
| Simple for "trash" features | Tables and indexes grow; scans touch dead rows |
| Conflicts with privacy rules that demand real erasure |
-- hide deleted rows behind a view or an ORM default scope
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.