I'm a very beginner to relations, so this may sound dumb. But, what is the difference (in MySQL) between truncating a table and removing all the records (this answer says only about performance)?
I was playing (in phpMyAdmin) with one of my test tables, to check, how can I reset auto_increment
value of table and run into situation, where I was able to delete all the records:
DELETE from managers;
But when I tried to truncate this table (TRUNCATE managers
), I've got warning: Cannot truncate a table referenced in a foreign key constraint (probes, CONSTRAINT probes_ibfk_4 FOREIGN KEY (manager_id) REFERENCES managers (id));
.
I had to "reset" the auto_increment
value with ALTER TABLE managers AUTO_INCREMENT = 1;
.
Isn't that something odd? Up until now, I thought, that TRUNCATE
= DELETE from managers
(in terms of checking and effects, because performance can be different, but this is not the key here).
How can constraint warning pop on TRUNCATE
but not on "delete all"?
truncate resets auto_increment after deleting all rows. so it's not the same as deleting all rows with DELETE command.
from mysql reference:
Although TRUNCATE TABLE is similar to DELETE, it is classified as a DDL statement rather than a DML statement. It differs from DELETE in the following ways:
Truncate operations drop and re-create the table, which is much faster than deleting rows one by one, particularly for large tables.
Truncate operations cause an implicit commit, and so cannot be rolled back. See Section 13.3.3, “Statements That Cause an Implicit Commit”.
Truncation operations cannot be performed if the session holds an active table lock.
TRUNCATE TABLE fails for an InnoDB table or NDB table if there are any FOREIGN KEY constraints from other tables that reference the table. Foreign key constraints between columns of the same table are permitted.
Truncation operations do not return a meaningful value for the number of deleted rows. The usual result is “0 rows affected,” which should be interpreted as “no information.”
As long as the table format file tbl_name.frm is valid, the table can be re-created as an empty table with TRUNCATE TABLE, even if the data or index files have become corrupted.
Any AUTO_INCREMENT value is reset to its start value. This is true even for MyISAM and InnoDB, which normally do not reuse sequence values.
When used with partitioned tables, TRUNCATE TABLE preserves the partitioning; that is, the data and index files are dropped and re-created, while the partition definitions (.par) file is unaffected.
The TRUNCATE TABLE statement does not invoke ON DELETE triggers.
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