Thursday, February 4, 2010

Difference between truncate and delete in mysql

Truncate and Delete are both SQL commands which result in removing the table records. So lets list the differences one by one :
Type of Command – Truncate is a DDL command and Delete is a Dml command
RollBack - As mentioned above Truncate is DDL command, so the changes made by it are committed automatically hence there is nothing called rollback when you use truncate, while Delete commands can be rolled back
Table Structure – When you use Truncate command, all the rows in the table are delete and the structure of the table is recreated and so does the indexes. On the contrary if you use Delete command only the desired rows or all the rows are deleted and the structure remains unchanged.
Syntax - The syntax for both the commands is :
Truncate table #command to truncate a table.
Delete from #command to delete all the records from table.
Practical example -
#creates a table with 2 columns, 1st column is auto incremented
Create table mysqlDemo (id integer not null auto_increment,name varchar(100),PRIMARY KEY(id));

#now insert two records in the table
insert into mysqlDemo(name)values ('sachin');
insert into mysqlDemo(name)values ('digimantra');

#check the records and note their auto_increment values
select * from mysqlDemo;

#Let us try delete it using Delete command
delete from mysqlDemo;

#Now the table is empty, lets insert values from the first row.
insert into mysqlDemo(name)values ('new_sachin');
insert into mysqlDemo(name)values ('new_digimantra');

#check the records and note their auto_increment values
select * from mysqlDemo; #the aut_increment values will continue from the last records, as the table structure is preserved.

#Now let us Truncate the table and re-insert the values.
Truncate table mysqlDemo;
insert into mysqlDemo(name)values ('sachin');
insert into mysqlDemo(name)values ('digimantra');

#check the records and note their auto_increment values
select * from mysqlDemo;

#this time the auto_increment value will start from one, as the table structure is recreated because we used Truncate instead of Delete.
So this is what the difference is, in short always remember Truncate command recreates the structure of the table and deletes all the records of the table. However Delete command does not recreates the structure and deletes the complete or partial records (as desired) from the table.

So this is what the difference is, in short always remember Truncate command recreates the structure of the table and deletes all the records of the table. However Delete command does not recreates the structure and deletes the complete or partial records (as desired) from the table.

No comments:

Post a Comment