DROP vs TRUNCATE TABLE ποΈΒΆ
Prerequisites: CREATE TABLE
Mentor's Note: This is a classic interview topic. "How do I empty a table?" The answer depends on whether you want to keep the table structure or destroy it entirely. π‘
π The Scenario: The Office Cleanup π’ΒΆ
- DELETE: Taking files out of the cabinet one by one. (Slow, Detailed).
- TRUNCATE: Dumping the entire cabinet contents into the bin instantly. (Fast, keeps the cabinet).
- DROP: Throwing the cabinet itself into the crusher. (Destroys everything).
π» 1. DROP TABLE (Destruction) π£ΒΆ
Removes the table definition AND all data.
- Result: The table no longer exists.
- Rollback?: No (Usually).
π» 2. TRUNCATE TABLE (Reset) β‘ΒΆ
Removes all data but keeps the table structure.
- Result: Table is empty (0 rows), but columns remain.
- Performance: Much faster than DELETE because it doesn't log individual row removals.
- Identity/Auto-Increment: Resets to 1.
π Comparison: DELETE vs TRUNCATE vs DROPΒΆ
| Feature | DELETE | TRUNCATE | DROP |
|---|---|---|---|
| Type | DML (Data) | DDL (Definition) | DDL (Definition) |
| Speed | Slow (Row-by-row) | Fast (Page deallocation) | Instant |
| Structure | Kept | Kept | Removed |
| Where Clause | Yes (Can filter) | No (All or nothing) | No |
| Rollback | Yes | No (In most DBs) | No |
π‘ Pro TipΒΆ
"Use
TRUNCATEwhen you need to refresh a staging table or clear test data. UseDELETEwhen you need to remove specific users. UseDROPonly when the feature is deprecated."