Here’s a comparison of TRUNCATE, DELETE, and DROP in SQL, highlighting their differences and use cases:
1. TRUNCATE
- Purpose: Removes all rows from a table quickly without logging individual row deletions.
- Key Points:
- DDL (Data Definition Language) operation.
- Does not log individual row deletions (minimally logged).
- Cannot use a
WHERE
clause (it clears the entire table). - Resets any identity/autoincrement columns.
- Cannot be rolled back in some databases (e.g., MySQL without transaction support).
- Preserves the table structure, indexes, and constraints.
Example:
Use Case: When you need to quickly clear all data from a table but retain the structure.
2. DELETE
- Purpose: Removes rows from a table based on a condition.
- Key Points:
- DML (Data Manipulation Language) operation.
- Logs each row deletion (fully logged).
- Supports a
WHERE
clause to selectively delete rows. - Can be rolled back if inside a transaction.
- Does not reset identity/autoincrement columns.
Example:
Use Case: When you need to remove specific rows or perform deletions in a transactional context.
3. DROP
- Purpose: Completely removes a table (or other database objects) from the database.
- Key Points:
- DDL (Data Definition Language) operation.
- Deletes the table structure, data, indexes, constraints, and any dependent objects.
- Cannot be rolled back.
- Requires recreating the table if needed again.
Example:
Use Case: When you no longer need the table or its data.
Summary Table:
Feature | TRUNCATE | DELETE | DROP |
---|---|---|---|
Operation Type | DDL | DML | DDL |
Removes Data? | Yes | Yes (conditionally) | Yes (completely) |
Removes Table Structure? | No | No | Yes |
Can Use WHERE Clause? | No | Yes | No |
Rollback Possible? | No (depends on DB) | Yes | No |
Resets Identity Columns? | Yes | No | N/A |
Speed | Faster than DELETE | Slower (fully logged) | Fast |
No comments:
Post a Comment