What is the difference between DELETE and TRUNCATE?
In SQL, both the DELETE and TRUNCATE commands are used to remove data from tables. However, they operate very differently in terms of how they remove data, their performance, logging, and transactional behavior.
Overview
DELETE is a DML (Data Manipulation Language) command that removes rows one by one, allowing for conditional deletion and transaction logging. TRUNCATE is a DDL (Data Definition Language) command that deallocates data pages, making it faster for removing all rows from a table.
DELETE Statement
The DELETE statement is used to remove one or more rows from a table. It can include a WHERE clause to specify which rows to delete. If no WHERE clause is provided, all rows are deleted. DELETE operations are logged, allowing them to be rolled back and triggering ON DELETE triggers.
DELETE FROM Employees WHERE DepartmentID = 10;
DELETE FROM Products;
- DML (Data Manipulation Language) command.
- Removes rows one by one.
- Allows
WHEREclause for conditional deletion. - Generates rollback segments (can be rolled back).
- Fires
ON DELETEtriggers. - Resets
AUTO_INCREMENTorIDENTITYcolumns only if all rows are deleted and the table is empty. - Slower for large tables compared to TRUNCATE.
- Requires
DELETEprivilege.
TRUNCATE Statement
The TRUNCATE statement is used to remove all rows from a table quickly and efficiently. It works by deallocating the data pages used by the table and logging only the deallocation of pages, rather than individual row deletions. This makes it much faster than DELETE for large tables, but it cannot be rolled back and does not fire triggers.
TRUNCATE TABLE Employees;
- DDL (Data Definition Language) command.
- Removes all rows by deallocating data pages.
- Does not allow
WHEREclause. - Cannot be rolled back (implicit COMMIT).
- Does not fire
ON DELETEtriggers. - Always resets
AUTO_INCREMENTorIDENTITYcolumns. - Faster for large tables.
- Requires
DROPprivilege on the table.
Key Differences
| Feature | DELETE | TRUNCATE |
|---|---|---|
| Command Type | DML | DDL |
| Row-by-row deletion | Yes | No (deallocates pages) |
| `WHERE` clause | Yes | No |
| Rollback | Yes | No (implicit COMMIT) |
| Triggers | Fires `ON DELETE` triggers | Does not fire triggers |
| Auto-Increment Reset | Only if all rows deleted and table empty | Always resets |
| Performance | Slower for large tables | Faster for large tables |
| Logging | Logs each row deletion | Logs page deallocation |
| Privilege | `DELETE` privilege | `DROP` privilege on table |