(I've tried this in MySql)
I believe they're semantically equivalent. Why not identify this trivial case and speed it up?
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.
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.
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.
The TRUNCATE command is faster than both the DROP and the DELETE command.
truncate table cannot be rolled back, it is like dropping and recreating the table.
...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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With