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
28

Better Data Management: The Efficiency of TRUNCATE in SQL

Updated on 13/06/202455 Views

Introduction

In the realm of database management, efficiency is paramount. To optimize resources and minimize overhead, you must execute every operation, whether retrieving, updating, or deleting data, in a certain manner. When it comes to deleting large volumes of data from a table in SQL, developers often debate between using the DELETE statement and the TRUNCATE in SQL. In this comprehensive guide, we'll delve into the intricacies of TRUNCATE in SQL, exploring its syntax, functionality, and the scenarios where it outshines DELETE.

Overview

A Data Definition Language (DDL) procedure called TRUNCATE TABLE in SQL designates a table's extents for DE allocation (empty for reuse). This process easily deletes every piece of data from a table while avoiding most integrity checkers. The SQL: 2008 standard covered it for the first time.

Use the SQL TRUNCATE TABLE order to eliminate every piece of data from an existing table. A table can also be completely removed with the DROP TABLE command. However, if you want to store any data, you will have to reconstruct the table because TRUNCATE will erase the entire table structure from the database.

TRUNCATE Command in SQL

The SQL TRUNCATE Command offers a streamlined approach to remove all records from a table efficiently. Unlike the DELETE statement, which removes rows one by one, TRUNCATE operates at the table level. It deallocates the data pages used by the table, thus resulting in faster execution, particularly with large datasets.

SQL TRUNCATE Syntax: 

The syntax for using TRUNCATE in SQL is straightforward:

TRUNCATE TABLE table_name;

Where table_name is the name of the table from which you want to remove all records.

SQL TRUNCATE Example 1

First, we will use the SQL build TABLE and INSERT commands to build a student table for the class that will store the record of a student who received the highest marks in a given topic.

CREATE TABLE Student(

    RollNo int PRIMARY KEY,

    Name VARCHAR(100) NOT NULL,

    Gender TEXT NOT NULL;

    Subject VARCHAR(30),

    MARKS INT (3)

);


INSERT INTO Student VALUES (1, Vaibhav, M, Mathematic, 100);

INSERT INTO Student VALUES (2, Vishal, M, Physics, 79);

INSERT INTO Student VALUES (3, Saumya, F, Chemistry, 95);

INSERT INTO Student VALUES (4, Arun, M, English, 78);

INSERT INTO Student VALUES (5, Anjum, F, Hindi, 83);

INSERT INTO Student VALUES (6, Radhika, F, Biology, 57);

INSERT INTO Student VALUES (7, Harpreet, F, Physical Education, 68);


SELECT * FROM Student;

The Output:

Roll No

Name

Gender

Subject

Marks

1

Vaibhav

M

Mathematics

100

2

Vishal

M

Physics

79

3

Saumya

F

Chemistry

95

4

Arun

M

English

78

5

Anjum

F

Hindi

83

6

Radhika

F

Biology

57

7

Harpreet

F

Physical Education

68

Now let’s use the TRUNCATE TABLE command to remove all the records in the above table:

Code:

TRUNCATE TABLE Student;

SELECT * FROM Student;

Output: 

No Data Found

Next, let’s try using the SQL TRUNCATE database command over a partition. We’ll remove columns 1 and 3-5.

Query:

TRUNCATE TABLE Student

WITH PARTITIONS (1, 3 TO 5);

The Output:

Roll No

Name

Gender

Subject

Marks

NULL

Vaibhav

NULL

NULL

NULL

NULL

Vishal

NULL

NULL

NULL

NULL

Saumya

NULL

NULL

NULL

NULL

Arun

NULL

NULL

NULL

NULL

Anjum

NULL

NULL

NULL

NULL

Radhika

NULL

NULL

NULL

NULL

Harpreet

NULL

NULL

NULL

Removing All the Records Using DELETE Command in SQL

We can delete every record from the table without compromising the properties, indexes, or structure of the table by using the DELETE command.

The Query:

DELETE FROM Student;

DELETE and TRUNCATE in SQL

It's crucial to understand the distinction between DELETE and TRUNCATE in SQL to make informed decisions regarding data management strategies. Both DELETE and TRUNCATE are used for deleting data from a table. 

However, DELETE removes rows one by one, generating more transaction log entries and taking longer to execute, especially with large datasets. On the other hand, TRUNCATE removes all records from a table in one go, making it significantly faster and more efficient, albeit with certain limitations. Now let’s see the major difference.

Advantages of the TRUNCATE Over the DELETE Command

The advantages of the TRUNCATE TABLE over the DELETE statement are as follows:

  1. A table's rows are all deleted using the TRUNCATE command. There is no WHERE clause available here.
  2. It's a DDL order.
  3. The SQL TRUNCATE statement locks the table and page to remove all data.
  4. Every deleted row is not recorded in the transaction log by the TRUNCATE command.
  5. Compared to the remove command, it is faster.
  6. The DELETE statement deletes rows one at a time and also logs each deletion in the transaction log. Relocating the data pages that were used to store the table data is how the TRUNCATE TABLE deletes data; just the page relocation is recorded in the transaction log.
  7. When the DELETE command is used with a row lock, every row in the table is locked for deletion. The table and page (including a schema (SCH-M) lock) are locked when using TRUNCATE TABLE, but not every row.
  8. Even after a DELETE statement has been performed, the table may still have empty pages. For example, you cannot deallocate empty pages in a heap without first obtaining an exclusive (LCK M X) table lock. If a table lock is not used during the delete operation, the table (heap) will have several empty pages. Although empty pages may be left behind by the deletion operation for indexes, these pages will be handled promptly.

Should You Use TRUNCATE in SQL?

The TRUNCATE query deletes the record from the tables. It may not always be able to modify data records.

The restrictions for using the TRUNCATE query are as follows:

  • For them, there is a foreign major restriction. It is possible to truncate a table that has a self-referential foreign key.
  • To incorporate into an indexed view.
  • Merge replication or transactional replication publishes the data.
  • Versioned system-wide temporarily.
  • They are referred to as an EDGE restriction.
  • You cannot TRUNCATE TABLE with the EXPLAIN query.
  • It is not permitted to use a TRUNCATE TABLE within a transaction.

More SQL TRUNCATE Example

Let's further explore the scenario where you manage an e-commerce platform with a database containing an orders table to track customer transactions. Over time, this table accumulates a vast number of records, impacting database performance. To efficiently clear out this table, you decide to utilize the TRUNCATE command:

Query:

TRUNCATE TABLE orders;

Upon execution of this command, all records within the orders table are promptly removed, leaving behind an empty table ready to store new transactions. This operation significantly enhances database performance and frees up storage space.

Suppose the orders table has the following structure and data:

order_id

customer_id

product_id

quantity

order_date

1

1001

101

2

2024-03-15

2

1002

102

1

2024-03-16

3

1003

103

3

2024-03-17

Executing the TRUNCATE TABLE orders; command removes all records from the orders table, resulting in an empty table:

order_id

customer_id

product_id

quantity

order_date

This process enhances database performance by deallocating data pages used by the orders table, improving overall system efficiency. Additionally, it's essential to note that TRUNCATE resets any identity columns in the table to their seed value, ensuring consistency in data insertion.

The Differences Between DELETE and TRUNCATE

There are several differences between the DELETE and TRUNCATE commands. Here is a summary:

DELETE

TRUNCATE

Removes individual rows from a table

Removes all rows from a table

Slower, especially for large datasets

Faster, particularly with large datasets

Fully logged, generates log entries for each row

Minimal logging does not log individual row deletions

Can be rolled back within a transaction

Cannot be rolled back, commits immediately

Does not reset identity/sequence

Resets identity/sequence to initial seed value

Can be used on tables with foreign key constraints

Cannot be used on tables with active foreign key constraints, requires constraints to be dropped or disabled before execution

Does not release allocated space

Releases allocated space, making it available for reuse

Fires triggers associated with DELETE operation

Does not fire triggers associated with the table

Can be used within a transaction

Cannot be used within a transaction

DML (Data Manipulation Language) operation

DDL (Data Definition Language) operation

SQL TRUNCATE Database

Although TRUNCATE primarily operates at the table level, it's also possible to truncate an entire database in SQL Server by leveraging dynamic SQL and system tables. 

Truncating an entire database in SQL Server involves removing all data and resetting the database to an empty state. The SQL TRUNCATE command typically operates at the table level, meaning it removes all records from a specific table. But, to truncate an entire database requires a different approach.

To truncate a database in SQL Server, you can utilize dynamic SQL, which involves constructing SQL statements dynamically at runtime, and system tables. These tables store metadata about the database objects.

Here's a high-level overview of how you can truncate a database in SQL Server:

  • Identify Tables: Firstly, you need to identify all the tables within the database that you want to truncate. This can be achieved by querying system tables such as sys.tables or information_schema.tables, which contain information about all the tables in the database.
  • Construct TRUNCATE Statements Dynamically: Once you have identified the tables, you can dynamically generate TRUNCATE TABLE statements for each table in the database. 
  • Execute TRUNCATE Statements: After constructing the TRUNCATE TABLE statements for all the tables, you can execute them dynamically using dynamic SQL. 
  • Verify Results: Finally, you should verify that the database has been truncated successfully by checking the tables to ensure they are empty.

Conclusion

Since TRUNCATE in SQL often executes very quickly, it's ideal for deleting data from a temporary table. In contrast to drop tables, which completely remove a table's structure, TRUNCATE tables in SQL preserve their structure for potential future use.

Both the SQL DELETE and SQL TRUNCATE commands are effective for extracting rows from a table. This article addresses all of your queries on the DELETE and TRUNCATE SQL Server commands, along with explaining their distinctions. The TRUNCATE command removes every row from a table, so use it carefully.

FAQ

Q: What is the difference between DELETE and TRUNCATE in MySQL?

A: DELETE: Removes individual rows from a table based on specified conditions. It is a DML (Data Manipulation Language) operation and generates a log entry for each deleted row, which can impact performance.

TRUNCATE: Removes all rows from a table, resetting table data without logging individual row deletions. It is a DDL (Data Definition Language) operation and is faster than DELETE, especially for large datasets.

Q: Can TRUNCATE be rolled back?

A: No, TRUNCATE cannot be rolled back. It is a non-transactional operation, meaning it commits immediately upon execution and cannot be undone using a rollback statement. 

Q: Does TRUNCATE reset table identity/sequence?

A: Yes, TRUNCATE resets any identity columns or sequences associated with the table to their initial seed value. This means that after truncating a table, the identity column or sequence will start from its initial value specified during table creation.

Q: Can TRUNCATE be used on a table with foreign key constraints?

A: No, TRUNCATE cannot be used on a table with active foreign key constraints. The presence of foreign key constraints prevents TRUNCATE from executing successfully. Before truncating a table with foreign key constraints, the constraints must be dropped or disabled to avoid integrity constraint violations.

Q: Does TRUNCATE release table space?

A: Yes, TRUNCATE releases the storage space allocated to the table, making it available for reuse. When TRUNCATE is executed, it deallocates the data pages used by the table, effectively releasing the associated storage space back to the database for future use. 

Q: Is TRUNCATE logged?

A: TRUNCATE is minimally logged at the level of the table's allocation units. Unlike DELETE, which generates a log entry for each deleted row, TRUNCATE does not log individual row deletions. Instead, it logs the deallocation of the data pages used by the table. 

Q: Does TRUNCATE fire triggers?

A: No, TRUNCATE does not fire triggers associated with the table. Triggers are database objects that automatically perform specified actions in response to certain events, such as INSERT, UPDATE, or DELETE operations. 

Q: Is TRUNCATE recommended for large tables?

A: Yes, TRUNCATE is highly recommended for large tables due to its efficiency in removing all records at once. Unlike DELETE, which can be resource-intensive and time-consuming, especially with large datasets, TRUNCATE operates much faster as it bypasses the need to evaluate each row. 

Q: Can TRUNCATE be used within a transaction?

A: No, TRUNCATE cannot be used within a transaction. It is a non-transactional operation, meaning it commits immediately upon execution and cannot be rolled back. Attempting to execute TRUNCATE within a transaction will result in an error. 

Q: Is TRUNCATE DDL or DML?

A: TRUNCATE is a DDL (Data Definition Language) operation because it alters the structure of the table by removing all its rows. Unlike DML operations such as INSERT, UPDATE, or DELETE, which manipulate data within the table, TRUNCATE operates at the table level, effectively resetting the table's data without logging individual row deletions.

Ankit Mittal

Ankit Mittal

Senior Software Engineer

Working as an Senior Software Engineer at upGrad, with proven experience across various industries. 

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...