TRUNCATE TABLE
TRUNCATE TABLE

TRUNCATE TABLE

Status
Done

– show you how to delete all data from a table quickly and more efficiently using the TRUNCATE TABLE statement.

Understanding TRUNCATE TABLE

The TRUNCATE TABLE statement in MySQL is used to delete all rows from a table. It is functionally similar to a DELETE statement without a WHERE clause, but it's more efficient because it does not scan each row before deletion. Instead, it quickly removes all data and resets any AUTO_INCREMENT counters.

Basic Syntax:


TRUNCATE [TABLE] table_name;
  • table_name: The name of the table from which you want to delete all rows.
  • The TABLE keyword is optional but recommended for clarity.

Key Points:

  1. Efficiency: TRUNCATE TABLE is faster than DELETE FROM table_name without a WHERE clause because it drops and recreates the table rather than deleting rows one by one.
  2. Auto-Commit: The TRUNCATE TABLE statement causes an implicit commit, meaning it cannot be rolled back.
  3. Triggers: It does not fire any DELETE triggers on the table.
  4. Foreign Keys: If there are foreign key constraints referencing the table, the TRUNCATE TABLE statement will fail.
  5. AUTO_INCREMENT: It resets any AUTO_INCREMENT column values to their initial values.

Example Scenario

Let's assume we have a table named employees:


CREATE TABLE employees (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    position VARCHAR(50)
);

Inserting Some Data:


INSERT INTO employees (name, position) 
VALUES ('Alice', 'Manager'), ('Bob', 'Developer'), ('Charlie', 'Analyst');

Viewing the Data:


SELECT * FROM employees;

Output:

image

Using TRUNCATE TABLE:

TRUNCATE TABLE employees;

After executing the above statement, the employees table will be empty.

Verifying the Deletion:


SELECT * FROM employees;

Output:


Empty set (0.00 sec)

image

Checking AUTO_INCREMENT Value:

After truncating, if we insert a new row, the id will start from 1 again:


INSERT INTO employees (name, position) VALUES ('David', 'Tester');

Viewing the Data Again:


SELECT * FROM employees;

Output:

image

Comparison with DELETE and DROP:

  • Using DELETE:
  • 
    DELETE FROM employees;

    This would also delete all rows but would not reset the AUTO_INCREMENT counter and can be slower for large tables.

  • Using DROP and CREATE:
  • DROP TABLE employees;
    
    CREATE TABLE employees (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100),
        position VARCHAR(50)
    );

    This sequence achieves a similar result but involves dropping the entire table structure and recreating it, which is less convenient.

Summary

The TRUNCATE TABLE statement is a powerful tool for quickly and efficiently clearing all rows from a table, resetting AUTO_INCREMENT values, and ensuring high performance. However, it should be used with caution due to its irreversible nature and potential issues with foreign key constraints.