Home >Database >Mysql Tutorial >What is the difference between MySQL TRUNCATE and DELETE commands?

What is the difference between MySQL TRUNCATE and DELETE commands?

WBOY
WBOYforward
2023-09-12 14:13:02931browse

MySQL TRUNCATE 和 DELETE 命令有什么区别?

As we all know, TRUNCATE will delete all rows without removing the structure of the table from the database. The same thing can be done with the help of DELETE command to delete all the rows from the table. But there are significant differences in PRIMARY KEY AUTO_INCRMENT reinitialization between the two commands.

Assuming that a column is defined with AUTO_INCRMENT with PRIMARY KEY CONSTRAINT, then the initialization table will not be reinitialized when all rows are deleted using the DELETE command, that is, when a new row is entered, the AUTO_INCREMENT number will be removed from the last inserted row. start. In contrast, when using TRUNCATE, the table is reinitialized like a newly created table. This means that after using the TRUNCATE command and inserting a new row, the AUTO_INCRMENT numbers will start at 1.

Example

The 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)

The above is the detailed content of What is the difference between MySQL TRUNCATE and DELETE commands?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete