1. Home
SQL

SQL Tutorial: Learn Structured Query Language Basics

Learn all SQL tutorial concepts in detail and master your career today.

  • 59
  • 9 Hours
right-top-arrow

Tutorial Playlist

46 Lessons
29

Difference Between DELETE and TRUNCATE in SQL

Updated on 13/06/202461 Views

Introduction

SQL, or Structured Query Language, traces its origins back to the 1970s when researchers at IBM developed the first relational database system known as System R. Over the decades, SQL has evolved into a universal language for managing and querying relational databases, powering everything from small-scale applications to massive enterprise systems.

Relational databases remain the backbone of countless applications and systems worldwide. SQL commands like DELETE and TRUNCATE are paramount to ensuring optimal performance and data integrity in relational databases.

Overview

One fundamental aspect of database administration in SQL is the management of data. DELETE and TRUNCATE are two common SQL commands used to manipulate data. You must understand the difference between these commands, even if they may look alike. This will help you to keep your data adequately managed and maintain the integrity of your database.

Let us explore two essential SQL commands, DELETE & TRUNCATE, using examples around them. A light will also be shone on their internal working and its implications on performance.

At the end of this guide, you should know how to use DELETE & TRUNCATE commands in SQL to optimize your database performance.

What is the DELETE Command in SQL? 

When you execute a DELETE command, you're essentially instructing the database to find and eliminate data that meets certain conditions. Depending on your query, this could involve deleting a single row, multiple rows, or even all rows from a table.

This is the DELETE command syntax in SQL:

DELETE FROM table_name

WHERE condition:

Suppose you have a table named Customers that stores information about your customers, including their names, email addresses, and purchase history.

CustomerID

FirstName

LastName

Email

PhoneNumber

RegistrationDate

1

John

Doe

john@example.com

555-1234

2022-03-01

2

Jane

Smith

jane@example.com

555-5678

2022-03-02

3

Alice

Johnson

alice@example.com

555-9876

2022-03-03

4

Bob

Williams

bob@example.com

555-4321

2022-03-04

If John decides to unsubscribe from your service, you can make use of the DELETE command to remove their record from the Customer table

In SQL, the delete command is used to remove the record for John from the Customers table. The SQL DELETE command should thus read as follows:

DELETE FROM Customers

WHERE CustomerID = 1:

If you run this command, John’s record will be deleted from this table. In executing this query, the database will delete the corresponding row in the Customers table, erasing all of the customer’s information within your database.

Also, know that the DELETE operation has a transactional aspect that allows rollbacks where necessary. This way, you have double safety and flexibility, enabling you to restore your deleted records in case of any errors or undesired effects.

One would typically employ a transaction with a rollback statement to roll back a delete operation in SQL. Below presents how:

BEGIN TRANSACTION: -- Start a transaction

DELETE FROM TableName

WHERE Condition: -- Your delete statement

ROLLBACK TRANSACTION: -- Rollback the transaction

What is TRUNCATE Command in SQL?

SQL’s TRUNCATE command is powerful and can be rapidly used to delete all rows from a table, effectively making it look like when it was initially created. 

TRUNCATE works faster and more efficiently than DELETE, providing a compelling mass data purging method. It is particularly useful for big tables with millions of records. Truncate in DBMS is also widely used.

SQL syntax for the TRUNCATE command is:

TRUNCATE TABLE table_name:

For example, let's say that you are managing a database for an e-commerce platform, and at the end of the day, you need to clear the “orders” table after processing shipments. Instead of deleting each order entry manually one by one, we can truncate this table just by executing the following command:

TRUNCATE TABLE Orders:

This single command immediately removes all order records from the table, allowing you to begin without logging each delete operation.

While fast and efficient, TRUNCATE has certain limitations and possible impacts. You must realize that unlike delete statements, truncation is not logged, meaning that it cannot be undone. After truncating a table, it becomes impossible to get the records back, so it is vital to double-check your actions before proceeding with the operation.

Additionally, TRUNCATE doesn't fire any triggers associated with the table or invoke any cascading referential integrity constraints. If your database relies on triggers or cascading deletes to maintain data consistency, you must handle these aspects manually when using TRUNCATE.

When to Use DELETE and TRUNCATE Commands in SQL

Knowing when to use the DELETE and TRUNCATE commands in SQL database management is important for efficiently managing your data. 

Both commands remove records from a table, but they do so in different ways, each with its own set of considerations and implications. Here are some scenarios where you should use each command:

1. Scenarios to Use DELETE 

(i) You need to selectively remove specific rows

DELETE is suitable when removing only certain rows from a table based on specific conditions. Use this command if you have a client database and need to remove old inoperative accounts that have been operating for over a year.

DELETE FROM customers

WHERE status = 'inactive' AND registration_date < DATE_SUB(NOW(), INTERVAL 1 YEAR):

(ii) If you need to enforce referential integrity

It is desirable to use DELETE If you need to enforce referential integrity constraints and trigger cascading deletes in related tables. 

For instance, in case an orders table has a foreign key referencing a customer table, then deleting a record of the customer should also result in the deletion of all connected orders:

DELETE FROM customers WHERE customer_id = 123:

(iii) You require transactional control

You can wrap delete operations within transactions so that if changes are not successful, these can be rolled back, which helps give more command on data manipulations. Suppose you're deleting records as part of a multi-step process. Using transactions ensures all steps are completed successfully before committing the changes:

START TRANSACTION:

DELETE FROM table1 WHERE condition:

DELETE FROM table2 WHERE condition:

COMMIT::

2. Scenarios to Use TRUNCATE 

(i) You want to remove all rows from a table quickly 

TRUNCATE is ideal when you need to clear the contents of a table without specifying conditions for row removal.

(ii) You need to reset auto-increment columns

TRUNCATE resets auto-increment columns to their initial value, making it suitable for resetting primary key sequences. If you have a table called my_table with an auto-incremented primary key and you want to reset it after data cleanup:

TRUNCATE TABLE my_table:

(iii) You seek improved performance and reduced transaction logs

TRUNCATE is generally faster than DELETE because it deallocates data pages without logging individual row deletions, making it more efficient for large tables. For example, when dealing with a large log table that accumulates millions of records, truncating the table periodically can help manage its size and improve performance: 

Key Differences Between DELETE and TRUNCATE

Now, let us look at the differences between delete and truncate commands. If you are wondering, “What is the difference between truncate and delete?”, here are the key differences:

Features

TRUNCATE

DELETE

Works with indexed views?

No, TRUNCATE removes all rows from a table, including those referenced by indexed views.

Yes, DELETE allows you to specify conditions for row deletion, making it compatible with indexed views.

Speed

TRUNCATE is generally faster than DELETE because it deallocates data pages without logging individual row deletions in the transaction log.

DELETE records one deletion after another on each row at a time, potentially slowing down the system, especially with large datasets.

Table Dependencies

TRUNCATE removes all rows from a table, effectively resetting the table to its original state without retaining any data. As a result, all table dependencies are severed, and any associated records in other tables are also removed.

DELETE removes specific rows from a table while preserving the table structure and associated constraints, maintaining table dependencies.

Rollback Capabilities

TRUNCATE is not a transaction and hence cannot be reversed. Once executed, the data is permanently removed from the table.

DELETE operates within a transaction and can be rolled back if necessary, allowing for the restoration of deleted records.

Transactional Consistency

TRUNCATE works as a single transaction, deleting all rows from the table at once, which may affect transactional consistency temporarily.

DELETE treats each deletion as an individual transaction, ensuring transactional consistency even with multiple deletions.

Triggers

TRUNCATE does not invoke any DELETE triggers associated with the table, as it bypasses row-level processing.

DELETE triggers any associated DELETE triggers, allowing for the execution of triggers associated with row-level operations.

WHERE Clause

TRUNCATE does not support WHERE clause and deletes all rows from the table.

DELETE can be used with a WHERE clause to select specific rows for deletion based on conditions.

Language Type

TRUNCATE is classified as a DDL statement because it changes the table structure by freeing up memory.

DELETE is classified as a DML statement since it removes data by deleting rows from the table.

Conclusion

A clear understanding of the difference between delete and truncate in SQL will assist you in effectively managing your SQL database. Delete involves removing some piece in a block, while truncate erases everything within an entire table.

Therefore, remember that each has its unique place depending on your requirements, even though delete may be more flexible but slower, while truncate can be faster but rigid.

Once you know how to apply these orders to your SQL databases, you can work with your data much faster. Keep learning, and soon enough, you will be a pro!

Frequently Asked Questions

1. Can we rollback DELETE and TRUNCATE?

If you are still in a transaction, DELETE can be undone or rolled back. But, executing TRUNCATE cannot be reversed because it is an irreversible act.

2. Which is faster DELETE or TRUNCATE?

TRUNCATE is significantly quicker than DELETE, particularly on large volumes of data. This implies that all rows from a table are removed as one action, whereas the DELETE operation deletes them one by one, leading to slower performance.

3. Can we recover data after TRUNCATE?

The fact is, once you have done TRUNCATE, nothing will bring back the lost information. As a rule, when this command is issued, all records in the table are therefore deleted forever; hence, an individual needs to be certain before taking any action.

4. Is TRUNCATE permanent?

Yes, this process is irreversible. When you truncate a table, all its contents disappear completely. Deleted records cannot be recovered or undone.

5. Does TRUNCATE remove all rows?

Yes, it’s true that TRUNCATE removes all rows from a table at once. Resetting, like button pressing, blanks out everything from the table unconditionally and without using filters.

6. Can we rollback DROP?

No, we cannot roll back DROP operations. Once such a table is dropped or any other database object is dropped, it is deleted from the database forever and there’s no way you can get it back.

7. What is the purpose of TRUNCATE?

The main aim of TRUNCATE is to quickly remove all data from a table so that it can be reset to its original state. It’s efficient when you want to clean up a table but don’t have time for individual row deletions.

8. Is TRUNCATE reversible?

Sorry but TRUNCATE cannot be undone once executed. The data will be deleted permanently after execution and in-built mechanisms are unavailable for undoing or recovery of the truncated records.

Kechit Goyal

Kechit Goyal

Developer

Team Player and a Leader with a demonstrated history of working in startups. Strong engineering professional with a Bachelor of Technology (BTech… Read More

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...