Thursday 4 December 2014

Difference between Delete and Truncate in SQL Query

Delete
Truncate
In a Delete Query we can use a Where Clause
In a Truncate Query we cannot use a Where Clause
Syntax:

DELETE FROM [Table_Name]
Or
DELETE FROM [Table_Name] WHERE [Condition]
Syntax:

TRUNCATE TABLE [Table_Name]

Comparing the Delete is slower than the Truncate
Comparing the Truncate is faster than the delete query
In a Delete Query we can only delete a single or multiple rows with a where clause.
In a Truncate Query all the row's data is truncated from the table.
We can use triggers when a delete query is executed.
We cannot use triggers when a truncate query is executed.
A Delete query logs the data.
A Truncate cannot log the data.
A Delete query deletes the data from the table row by row.
A Truncate query truncates the data from the table page by page.
A Delete cannot reset the identity value in a table.
A Truncate can reset the identity value in a table.
It does not claim the memory after the deleting operation is performed.

Example:

Create table

CREATE TABLE TempStudent
(
FName varchar(100),
LName varchar(100)
)


Insert some dummy data:

Insert into TempStudent(FName,LName) VALUES('Rakesh','Kalluri')
Go 1000

Check the memory used for this table.

exec sp_spaceused 'TempStudent'





Delete data from table:

DELETE FROM TempStudent

Check the memory used for this table after delete:

exec sp_spaceused 'TempStudent'



It claims the memory after the truncate operation is performed

Example:

Create table
CREATE TABLE TempStudent
(
FName varchar(100),
LName varchar(100)
)


Insert some dummy data:

Insert into TempStudent(FName,LName) VALUES('Rakesh','Kalluri')
Go 1000

Check the memory used for this table.

exec sp_spaceused 'TempStudent'


Truncate data from table:

TRUNCATE TABLE TempStudent

Check the memory used for this table after truncate:

exec sp_spaceused 'TempStudent'