Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Truncate Table vs Delete From Table

When do we use the DELETE command versus the TRUNCATE command? I am trying to find on the Internet but both commands delete the data; I can't tell the difference.

like image 271
Adnan Siddique Avatar asked Nov 28 '14 07:11

Adnan Siddique


People also ask

What is the difference between delete table and TRUNCATE table command in mysql?

Conclusion. Both the SQL DELETE and SQL TRUNCATE commands can be used to remove records from a table. However, the DELETE command employs the WHERE clause to specify rows in a table for deletion action, whereas the TRUNCATE command does not use any clause and deletes rows all at once.

Which is better delete or TRUNCATE?

Truncate removes all records and doesn't fire triggers. Truncate is faster compared to delete as it makes less use of the transaction log. Truncate is not possible when a table is referenced by a Foreign Key or tables are used in replication or with indexed views.

Is TRUNCATE faster than delete mysql?

TRUNCATE is faster than DELETE , as it doesn't scan every record before removing it. TRUNCATE TABLE locks the whole table to remove data from a table; thus, this command also uses less transaction space than DELETE . Unlike DELETE , TRUNCATE does not return the number of rows deleted from the table.


1 Answers

DELETE FROM TABLE

1. DELETE is a DML Command.
2. DELETE statement is executed using a row lock, each row in the table is locked for deletion.
3. We can specify filters in where clause
4. It deletes specified data if where condition exists.
5. Delete activates a trigger because the operation are logged individually.
6. Slower than truncate because, it keeps logs.
7. Rollback is possible.
8. LIMIT clause can also be used to set a limit on the number of rows to be deleted.
9. ORDER BY clause can be used in DELETE statement. In this case, the rows are deleted in the specified order.

TRUNCATE TABLE

1. TRUNCATE is a DDL command.
2. TRUNCATE TABLE always locks the table and page but not each row.
3. Cannot use Where Condition.
4. It Removes all the data reset the auto increment number.
5. TRUNCATE TABLE cannot activate a trigger because the operation does not log individual row deletions.
6. Faster in performance wise, because it doesn't keep any logs.
7. Rollback is possible.
8. Cannot use LIMIT and ORDER BY.

DELETE and TRUNCATE both can be rolled back when used with TRANSACTION. If there is a primary key with auto increment, truncate will reset the counter.

like image 86
Saharsh Shah Avatar answered Oct 02 '22 06:10

Saharsh Shah