TRUNCATE vs DELETE vs DROP in SQL
1. TRUNCATE
The TRUNCATE
SQL command removes all rows from a table without logging individual row deletions. It is faster than DELETE and is classified as a DDL (Data Definition Language) command.
Key Characteristics of TRUNCATE:
-
Removes all rows from a table.
-
Faster than DELETE due to minimal logging in the transaction log.
-
Uses a table lock, meaning the entire table is locked while the operation is performed.
-
Cannot use the WHERE clause (it removes all rows at once).
-
Resets identity columns (if any) to their seed values.
-
Requires ALTER permission on the table.
-
Consumes less transaction log space than DELETE.
-
It cannot be used with indexed views.
Example:
2. DELETE
The DELETE
SQL command removes specific or all records from a table. It allows the use of a WHERE
clause to filter records before deletion. DELETE is a DML (Data Manipulation Language) command.
Key Characteristics of DELETE:
-
Removes specific rows if the
WHERE
clause is used; otherwise, it deletes all rows. -
Uses a row lock, meaning each row is locked and deleted individually.
-
Maintains the transaction log, making it slower than TRUNCATE.
-
Does not reset identity column values.
-
It can be rolled back if used within a transaction.
-
Requires DELETE permission on the table.
-
Uses more transaction log space than TRUNCATE.
-
It can be used with indexed views.
Examples:
Delete all rows:
Delete specific rows:
3. DROP
The DROP
SQL command removes a table completely from the database, including its data, indexes, triggers, constraints, and permissions.
Key Characteristics of DROP:
-
Removes the table definition and all data permanently.
-
It cannot be rolled back once executed.
-
No DML triggers are fired when using DROP.
-
Requires ALTER permission on the schema or CONTROL permission on the table.
-
Deletes all associated indexes, privileges, and constraints.
Example:
4. Summary of Differences
Feature | TRUNCATE | DELETE | DROP |
---|---|---|---|
Type | DDL (Data Definition) | DML (Data Manipulation) | DDL (Data Definition) |
Removes Data? | Yes (All rows) | Yes (Specific rows if WHERE is used, else all) | Yes (Entire table) |
Can use WHERE? | ❌ No | ✅ Yes | ❌ No |
Resets Identity Columns? | ✅ Yes | ❌ No | ❌ No |
Transaction Log | Minimal logging (faster) | Logs each deleted row (slower) | No logging |
Can be Rolled Back? | ❌ No | ✅ Yes (if used inside a transaction) | ❌ No |
Table Structure Remains? | ✅ Yes | ✅ Yes | ❌ No (Table is removed) |
Permission Required | ALTER | DELETE | ALTER, CONTROL |
Conclusion
-
Use TRUNCATE when you need to remove all records quickly and don't need to retain identity values.
-
Use DELETE when you need to remove specific records using a
WHERE
clause or to keep the table structure intact. -
Use DROP when you want to completely remove a table from the database completely.