[MySQL] The difference between delete from table and truncate table of MySQL database

DELETE FROM tableand TRUNCATE TABLEare two different database operations used to delete data from a table in a MySQL database. They have the following differences:

  1. Operation mode : DELETE FROM tableIt is a row-by-row delete operation, which will delete each row of data in the table one by one, and can be filtered with conditions. The TRUNCATE TABLEoperation is to clear the contents of the entire table at one time, which is equivalent to deleting and recreating an empty table.

  2. Efficiency : TRUNCATE TABLEOperations are usually DELETE FROM tablemore efficient than . Because DELETE FROM tablethe operation is to delete row by row, each deletion needs to record the transaction log to support the rollback operation, and also needs to trigger related triggers and foreign key constraints. The TRUNCATE TABLEoperation directly releases the storage space of the table, and does not record logs, and does not trigger triggers and foreign key constraints.

  3. Permission requirements : DELETE FROM tableFor users, they need to have permission to delete data row by row and sufficient resources (disk space, memory, etc.). For TRUNCATE TABLEthe operation, the user only needs to have TRUNCATEthe permission of the corresponding table.

  4. Preserve the structure : DELETE FROM tablethe operation only deletes the data in the table and does not change the structure of the table, including the metadata, indexes, triggers, etc. of the table will be preserved. The TRUNCATE TABLEoperation will keep the table structure, indexes, triggers, etc., and only clear the data content.

  5. Auto-increment primary key : DELETE FROM tableAfter the operation deletes data, the auto-increment primary key in the table will still continue to increment. The TRUNCATE TABLEoperation will reset the auto-increment primary key, and the next time data is inserted, the auto-increment primary key will start from the initial value.

In summary, DELETE FROM tableand TRUNCATE TABLEhave different behaviors and effects when deleting data. The choice of which operation to use depends on your needs and considerations for database resource consumption. If you only need to delete data while retaining the structure of the table, and have high performance requirements, you can consider using TRUNCATE TABLEthe operation. If you need to delete data row by row or preserve other information about the data and structure of the table, you can use DELETE FROM tablethe operation.

In addition, to delete the entire table, you can use the MySQL DROP TABLEstatement. The DROP TABLE statement can completely delete tables in the database, including the structure, data, indexes, and triggers of the tables.

Guess you like

Origin blog.csdn.net/weixin_44624036/article/details/132298167