Friday, January 3, 2025

Comparison of TRUNCATE, DELETE, and DROP in SQL


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:


TRUNCATE TABLE my_table;

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:


DELETE FROM my_table WHERE column_name = 'value';

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:


DROP TABLE my_table;

Use Case: When you no longer need the table or its data.


Summary Table:

FeatureTRUNCATEDELETEDROP
Operation TypeDDLDMLDDL
Removes Data?YesYes (conditionally)Yes (completely)
Removes Table Structure?NoNoYes
Can Use WHERE Clause?NoYesNo
Rollback Possible?No (depends on DB)YesNo
Resets Identity Columns?YesNoN/A
SpeedFaster than DELETESlower (fully logged)Fast

No comments:

Search This Blog