Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why 'delete from table' takes a long time when 'truncate table' takes 0 time?

(I've tried this in MySql)

I believe they're semantically equivalent. Why not identify this trivial case and speed it up?

like image 607
ripper234 Avatar asked Dec 24 '08 18:12

ripper234


People also ask

Why does DELETE take longer than TRUNCATE?

The time taken to delete is also proportional to the number of indexes on the table, and if there are any foreign key constraints (for innodb). Truncate effectively drops the table and recreates it and can not be performed within a transaction. It therefore required fewer operations and executes quickly.

Why TRUNCATE takes a long time?

For some reason, the TRUNCATE TABLE command takes really long time to execute (both on the master and on the slave). It takes about 400K ms to execute!! When it runs on the slave, it causes it to lag from the Master.

How long should it take to TRUNCATE a table?

If there are zero transactions locking the table schema, the TRUNCATE TABLE command will finish near-instantaneously. The most i have waited so far was 0.1 seconds for truncating a 25GB table.

Which is faster TRUNCATE or DELETE or drop?

The TRUNCATE command is faster than both the DROP and the DELETE command.


3 Answers

truncate table cannot be rolled back, it is like dropping and recreating the table.

like image 106
Otávio Décio Avatar answered Nov 15 '22 23:11

Otávio Décio


...just to add some detail.

Calling the DELETE statement tells the database engine to generate a transaction log of all the records deleted. In the event the delete was done in error, you can restore your records.

Calling the TRUNCATE statement is a blanket "all or nothing" that removes all the records with no transaction log to restore from. It is definitely faster, but should only be done when you're sure you don't need any of the records you're going to remove.

like image 27
Dillie-O Avatar answered Nov 15 '22 23:11

Dillie-O


Delete from table deletes each row from the one at a time and adds a record into the transaction log so that the operation can be rolled back. The time taken to delete is also proportional to the number of indexes on the table, and if there are any foreign key constraints (for innodb).

Truncate effectively drops the table and recreates it and can not be performed within a transaction. It therefore required fewer operations and executes quickly. Truncate also does not make use of any on delete triggers.

Exact details about why this is quicker in MySql can be found in the MySql documentation: http://dev.mysql.com/doc/refman/5.0/en/truncate-table.html

like image 27
Pervez Choudhury Avatar answered Nov 15 '22 21:11

Pervez Choudhury