SQL Server BasicsWhat is SQL Server database?What is RDBMS?What is Normalization?Why we use Denormalization?What_is_SQL?What is PL/SQL?Difference between SQL and PL/SQLDatabase TableOne to One RelationshipOne to Many RelationshipMany to Many RelationshipMany to One RelationshipString Data TypesNumber Data TypesDate Data TypesOther Data TypesCreate DatabaseDrop DatabaseCreating and Managing Users in SQL ServerCreate TableAlter TableDrop TableConstraints in SQL serverPrimary KeyForeign KeyUnique KeyCandidate KeyComposite KeyDifference between primary key and candidate keyPrimary key and foreign key relationshipSurrogate KeyCascading Referential Integrity ConstraintsSelf Referential Integrity ConstraintsInsert into statementInsert multiple recordsUpdate statementDelete statementTruncate statementDifference between Delete and TruncateAlias in SQL ServerSelect statementSelect DistinctSelect TopSelect IntoNull Functions(ISNULL(),NULLIF(),COALESCE())Sub QueryIdentity ColumnSequence objectDifference between sequence and identity columnSQL Server ClausesWHERE ClauseOrder By ClauseTop N ClauseGroup By ClauseHaving ClauseDifference between Where and HavingSQL Server OperatorsArithmetic OperatorsComparison OperatorsLogical OperatorsBitwise OperatorsAny OperatorsAll OperatorsUnion OperatorsUnion All OperatorsDifference between Union and Union AllIntersect OperatorExcept OperatorDifference between Except and IntersectJoinsInner JoinLeft JoinRight JoinFull JoinSelf JoinCross JoinViewsWhat are views?Create views using SSMSIndexed ViewsComplex ViewsCheck Option in ViewCheck Encryption in ViewSchema Binding Option in ViewRead-only ViewsUpdatable ViewsAdvantages and disadvantages of viewsCreate multiple views on one tableCan we implement index on views?Can we Perform Insert, update, delete operation on views?Stored Procedure and FunctionsWhat are Stored Procedures?Why we use stored procedures?Passing parameters to Stored procedureUser-Defined FunctionsDifference between UDF and Stored procedurePre-Defined Functions@@Indentity and Scope_IndentityNULLIF, ISNULL and COALESCE

Difference Between DELETE and TRUNCATE in SQL Server

When working with SQL Server, you’ll often need to remove data from tables. Two common commands for this are DELETE and TRUNCATE. While both commands are used to delete data, they work differently and are suited for different scenarios. In this article, we’ll explore the key differences between DELETE and TRUNCATE, along with examples to help you understand when to use each.

1. How DELETE and TRUNCATE Work

DELETE Statement

The DELETE command removes rows from a table one by one.

  • You can use a WHERE clause to specify which rows to delete. For example:
DELETE FROM Employees WHERE Department = 'HR';

This deletes only the rows where the Department is HR.

  • If you omit the WHERE clause, all rows in the table will be deleted:
DELETE FROM Employees;

TRUNCATE Statement

The TRUNCATE command removes all rows from a table in a single operation.

  • It does not support a WHERE clause, so you cannot selectively delete rows.
TRUNCATE TABLE Employees;

This removes all rows from the Employees table.

2. Speed and Efficiency

DELETE

  • DELETE is slower because it removes rows one by one and logs each deletion in the transaction log.
  • This makes it less efficient for large tables.

TRUNCATE

  • TRUNCATE is faster because it deallocates entire data pages (the storage space used by the table) in a single operation.
  • It generates fewer log entries, making it more efficient for large-scale deletions.

3. Transaction Logging

DELETE

  • DELETE logs each row deletion in the transaction log.
  • This allows you to roll back the operation if needed (if used within a transaction).

TRUNCATE

  • TRUNCATE logs only the deallocation of data pages.
  • It is minimally logged, which makes it faster but also means it cannot be rolled back after execution.

4. Resetting Identity Columns

DELETE

  • DELETE does not reset the identity column value.
  • For example, if the last identity value was 100, the next inserted row will have an identity value of 101.

TRUNCATE

  • TRUNCATE resets the identity column value to its seed value (usually 1).
  • For example, if the last identity value was 100, the next inserted row will have an identity value of 1.

5. Trigger Execution

DELETE

  • DELETE fires triggers associated with the table.
  • If you have a DELETE trigger defined, it will execute for each deleted row.

TRUNCATE

  • TRUNCATE does not fire triggers.
  • It bypasses any DELETE triggers defined on the table.

6. Impact on Table Structure

DELETE

  • DELETE preserves the table structure, including:
    • Constraints (e.g., primary keys, foreign keys).
    • Indexes.
    • Permissions.

TRUNCATE

  • TRUNCATE removes all data but preserves the table structure.
  • However, it resets the identity column and deallocates data pages.

7. Usage Scenarios

When to Use DELETE

  • Use DELETE when you need to selectively remove rows based on conditions.
  • DELETE FROM Orders WHERE OrderDate < '2023-01-01';
  • Use DELETE when you need to log individual row deletions for auditing or rollback purposes.

When to Use TRUNCATE

  • Use TRUNCATE when you want to quickly remove all rows from a table.
  • TRUNCATE TABLE TempData;
  • Use TRUNCATE when you are repopulating a table and no longer need the existing data.

8. Example: DELETE vs. TRUNCATE

Let’s say you have a table called Employees with the following data:

EmployeeID Name Department
1 John Doe HR
2 Jane Smith IT
3 Alice Brown HR

Using DELETE

DELETE FROM Employees WHERE Department = 'HR';

After executing this query, the table will look like this:

EmployeeID Name Department
2 Jane Smith IT

Using TRUNCATE

TRUNCATE TABLE Employees;

After executing this query, the table will be empty:

EmployeeID Name Department

9. Key Differences Summary

Feature DELETE TRUNCATE
Operation Removes rows one by one Removes all rows in one operation
WHERE Clause Supported Not supported
Speed Slower Faster
Transaction Logging Logs each row deletion Logs page deallocation
Rollback Can be rolled back Cannot be rolled back
Identity Column Does not reset identity value Resets identity value
Triggers Fires DELETE triggers Does not fire triggers
Table Structure Preserves structure Preserves structure

10. Conclusion

Both DELETE and TRUNCATE are essential commands in SQL Server, but they serve different purposes:

  • Use DELETE when you need to remove specific rows or log individual deletions.
  • Use TRUNCATE when you want to quickly remove all rows from a table and reset identity values.

By understanding the differences between DELETE and TRUNCATE, you can choose the right command for your specific needs and ensure efficient data management in your database.