What is the difference between MySQL TRUNCATE and DELETE command?


As we know that TRUNCATE will remove all the rows without removing table’s structure from the database. Same work can be done with the help of DELETE command on removing all the rows from the table. But there is a significant difference of re-initialization of PRIMARY KEY AUTO_INCREMENT between both the commands.

Suppose a column is defined AUTO_INCREMENT having PRIMARY KEY CONSTRAINT, then on deleting all the rows with DELETE command would not re-initialize the table i.e. on entering the new rows, the AUTO_INCREMENT number will start after the last inserted row. In contrast, on using TRUNCATE, the table will be re-initializing like a newly created table. It means after using TRUNCATE command and on inserting new rows the AUTO_INCREMENT number will start from 1.

Example

Following example will demonstrate the above concept −

mysql> Create table Testing(Id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, Name Varchar(20));
Query OK, 0 rows affected (0.15 sec)

mysql> Insert into testing(Name) values('Gaurav'),('Rahul'),('Aarav'),('Yashraj'),('Manak');
Query OK, 5 rows affected (0.09 sec)
Records: 5 Duplicates: 0 Warnings: 0

mysql> Select * from testing;

+----+---------+
| Id | Name    |
+----+---------+
| 1  | Gaurav  |
| 2  | Rahul   |
| 3  | Aarav   |
| 4  | Yashraj |
| 5  | Manak   |
+----+---------+

5 rows in set (0.00 sec)

mysql> Delete from testing where id >=4;
Query OK, 2 rows affected (0.04 sec)

mysql> Select * from testing;

+----+--------+
| Id | Name   |
+----+--------+
| 1  | Gaurav |
| 2  | Rahul  |
| 3  | Aarav  |
+----+--------+

3 rows in set (0.00 sec)

mysql> Insert into testing(Name) values('Harshit'),('Lovkesh');
Query OK, 2 rows affected (0.06 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> Select * from testing;

+----+---------+
| Id | Name    |
+----+---------+
| 1  | Gaurav  |
| 2  | Rahul   |
| 3  | Aarav   |
| 6  | Harshit |
| 7  | Lovkesh |
+----+---------+

5 rows in set (0.00 sec)

mysql> Truncate table testing;
Query OK, 0 rows affected (0.10 sec)

mysql> Insert into testing(Name) values('Harshit'),('Lovkesh'),('Ram'),('Gaurav');
Query OK, 4 rows affected (0.11 sec)
Records: 4 Duplicates: 0 Warnings: 0

mysql> Select * from testing;

+----+---------+
| Id | Name    |
+----+---------+
| 1  | Harshit |
| 2  | Lovkesh |
| 3  | Ram     |
| 4  | Gaurav  |
+----+---------+

4 rows in set (0.00 sec)

Updated on: 20-Jun-2020

284 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements