CASCADE quy định "khi xóa/sửa dòng cha thì làm gì với dòng con". Các lựa chọn ON DELETE:
- CASCADE: xóa cha → tự xóa luôn con (xóa user → mất hết order, comment, session). Tiện nhưng nguy hiểm nếu đặt nhầm.
- SET NULL: xóa cha → đặt FK con về NULL, con vẫn còn (xóa category →
products.category_id = NULL). Dùng khi con tồn tại độc lập được. - RESTRICT (mặc định): chặn xóa cha nếu còn con — an toàn nhất, app phải tự xử lý.
- SET DEFAULT: đặt FK về giá trị mặc định.
Lưu ý chuỗi lan: A → B → C cùng CASCADE thì xóa A kéo theo B rồi C — dễ không lường hết.
Khi nào dùng CASCADE: quan hệ "sở hữu" rõ ràng, con vô nghĩa nếu thiếu cha (order → order_items, user → sessions). Khi không nên: tài nguyên dùng chung (xóa tác giả không nên xóa sách nếu sách còn giá trị riêng). Lưu ý: nếu dùng soft delete thì CASCADE không kích hoạt — phải tự code logic xóa lan ở tầng app.
CASCADE defines "what happens to child rows when the parent is deleted/updated". The ON DELETE options:
- CASCADE: deleting the parent → auto-deletes children too (delete a user → lose all orders, comments, sessions). Convenient but dangerous if set by mistake.
- SET NULL: deleting the parent → sets the child FK to NULL, the child survives (delete a category →
products.category_id = NULL). Use when children can exist independently. - RESTRICT (default): blocks deleting the parent while children exist — safest; the app must handle it.
- SET DEFAULT: sets the FK to its default value.
Watch out for cascade chains: A → B → C all with CASCADE means deleting A pulls down B then C — easy to underestimate.
When to use CASCADE: clear "ownership" where children are meaningless without the parent (order → order_items, user → sessions). When not to: shared resources (deleting an author shouldn't delete books if they have standalone value). Note: with soft delete, CASCADE does not fire — you must code the cascade logic in the app layer.