What is the main difference between
truncate table mytable
and
delete from mytable
What is the main difference between
truncate table mytable
and
delete from mytable
TRUNCATE is executed using a table lock and whole table is locked for remove all records. DELETE is executed using a row lock, each row in the table is locked for deletion. TRUNCATE removes all rows from a table mean to say we cannot use where condition for truncate The DELETE command is used to remove rows from a table based on WHERE condition.
Though this question has been already answered, thought to compare TRUNCATE & DELETE side by side, with some basic points.
+----------------------------------------+----------------------------------------------+
| Truncate | Delete |
+----------------------------------------+----------------------------------------------+
| Its DDL(Data Definition Language) | Its DML(Data Manipulation Language) |
| command. | command. |
+----------------------------------------+----------------------------------------------+
| Generally used to remove all the | Generally used to delete particular rows of |
| data from the TABLE. | data from the TABLE based on WHERE condition |
+----------------------------------------+----------------------------------------------+
| We can't Rollback after performing | We can Rollback after delete. |
| Truncate. | |
+----------------------------------------+----------------------------------------------+
| Truncate reset identity of table. | Delete does not reset identity of table. |
+----------------------------------------+----------------------------------------------+
| It locks the entire table. | It locks the table row. |
+----------------------------------------+----------------------------------------------+
| We can't use WHERE clause with it. | We can use WHERE to filter data to delete. |
+----------------------------------------+----------------------------------------------+
| Trigger is not fired while truncate. | Trigger is fired. |
+----------------------------------------+----------------------------------------------+
| Faster in performance wise, because it |Slower than Truncate because it Keeps logs |
| doesn't keep any logs. | |
+----------------------------------------+----------------------------------------------+
| Syntax : | Syntax : |
| 1) TRUNCATE TABLE Table_Name | 1) DELETE FROM Table_Name |
| | 2) DELETE FROM Table_Name WHERE <Condition> |
+----------------------------------------+----------------------------------------------+