Both the TRUNCATE and DELETE statements are used to remove data from a table, but they operate in different ways and have distinct characteristics. Here’s a detailed comparison of the two, along with explanations and examples.

1. DELETE Statement

  • Purpose: The DELETE statement is used to remove specific rows from a table based on a condition specified in the WHERE clause. If no condition is specified, all rows will be deleted.
  • Transaction Log: Each row deleted is logged in the transaction log, which means it can be rolled back if necessary.
  • Triggers: The DELETE statement can activate triggers defined on the table.
  • Performance: Generally slower than TRUNCATE for large tables because it processes each row individually.
  • Usage: Can be used with a WHERE clause to delete specific records.

Example:

sql
1-- Create a sample table 2CREATE TABLE Employees ( 3 EmployeeID INT PRIMARY KEY, 4 FirstName VARCHAR(50), 5 LastName VARCHAR(50) 6); 7 8-- Insert sample data 9INSERT INTO Employees (EmployeeID, FirstName, LastName) VALUES (1, 'John', 'Doe'); 10INSERT INTO Employees (EmployeeID, FirstName, LastName) VALUES (2, 'Jane', 'Smith'); 11INSERT INTO Employees (EmployeeID, FirstName, LastName) VALUES (3, 'Alice', 'Johnson'); 12 13-- Delete a specific record 14DELETE FROM Employees WHERE EmployeeID = 2; 15 16-- Check remaining records 17SELECT * FROM Employees;

After executing the DELETE statement, the Employees table will contain only the records for John Doe and Alice Johnson.

2. TRUNCATE Statement

  • Purpose: The TRUNCATE statement is used to remove all rows from a table quickly and efficiently. It does not allow for a WHERE clause.
  • Transaction Log: It logs the deallocation of the data pages rather than individual row deletions, making it faster for large tables.
  • Triggers: The TRUNCATE statement does not activate triggers defined on the table.
  • Performance: Generally faster than DELETE for large tables because it does not log individual row deletions.
  • Usage: Cannot be used when a table is referenced by a foreign key constraint.

Example:

sql
1-- Truncate the Employees table 2TRUNCATE TABLE Employees; 3 4-- Check the table (it will be empty) 5SELECT * FROM Employees;

After executing the TRUNCATE statement, the Employees table will be empty, and all rows will be removed without logging each deletion.

Leave a Reply

Your email address will not be published. Required fields are marked *


Talk to us?

Post your blog

F.A.Q

Frequently Asked Questions