+ 1
If we already have the DELETE command in SQL, why do we need TRUNCATE?
Iâm preparing for SQL interviews. Recently, an interviewer asked me: âSince we can remove rows using DELETE, then why does TRUNCATE exist?â From what I know: DELETE removes rows one by one and allows a WHERE condition. TRUNCATE clears all rows much faster and also resets auto-increment. But I still want to clearly understand: In real-time, when should we prefer TRUNCATE over DELETE? What are the exact differences in terms of performance, rollback, and restrictions (like foreign keys, conditions)? Any practical examples or real-world scenarios from the community would be super helpful.
2 Answers
0
Nice question, my friend!
TRUNCATE
* It's a DDL command work with table structure not with data inside the table.
* Due to DDL, it resets the entire table in the name of resets data pages.
* In MySQL, we cannot do rollback.
* It only logs the deallocation of data pages, not for each deleted row. (Minimally logged)
* Mainly, it will reset the auto increment, etc.
DROP
* It's a DML command work with data inside the table.
* Due to DML, it removes records/rows one by one. So it is slower when working with large set of data in the table.
* Here, we can able to do rollback.
* It logs every single row, that we deleted. (Fully logged)
* It doesn't reset the auto increment counter and continues with the last generated value.
0
I'm a hobbyist, but this question is a little bit confusing to me.
DELETE is used to delete records, while TRUNCATE is to clear the table and reset everything (similar to compact DB in MS Access) and keep the table structure and links. The use case is not comparable.
If it is DROP vs TRUNCATE, then this question make more sense.
If Cascading is allowed, then DROP table can delete other tables' records as well, to my knowledge.
Wish a professional can shed some light on this.