What is the difference between Delete, Truncate, Drop in SQL ?

     Difference between Delete, Truncate and Drop is often an interview question to the novice programmers. Let's see what is the actual difference between these.

DELETE:
1.The DELETE command is used to remove rows from a table.

2. A WHERE clause can be used to only remove some rows.

3. If no WHERE condition is specified, all the rows will be removed.

4. After performing a DELETE operation, you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it.

5. This operation will cause all DELETE triggers on the table to fire.

6. It's a DML command.

DELETE query with WHERE clause
DELETE FROM EMP WHERE EMP_ID = 1; 

DELETE query without WHERE clause, is used to remove all the rows from table.
DELETE FROM EMP;

DELETE EMP;


TRUNCATE:
1. TRUNCATE removes all the rows from a table.

2. The operation cannot be rolled back and no triggers will be fired.

3. TRUNCATE is much faster than DELETE, because, when you execute DELETE, all the data get copied into the Rollback table space first, then delete operation get performed. That is the reason when you type ROLLBACK after deletion of table, you can get the data back. All this process takes time, but when you type TRUNCATE, it removes data directly without copying it into the Rollback table space.

4. TRUNCATE doesn't use much undo space as a DELETE.

5. You can't use the condition in WHERE clause in TRUNCATE.

7. After TRUNCATE, operations on the table are much faster.

8. It's a DDL command.

Example query is below.

TRUNCATE TABLE EMP;

DROP:

1. The DROP command removes a table from the database.

2. All the table's rows, indexes and privileges will also be removed.

3. No DML triggers will be fired.

4. The operation cannot be rolled back.

5. It's a DDL command.

Example query for DROP is
DROP TABLE EMP; 

From Oracle 10g, a table can be "undropped'. Example

SQL > FLASHBACK TABLE emp TO BEFORE DROP; 
Flashback complete.

Comments