SQL TRUNCATE
Published Dec 26, 2024
Contribute to Docs
TRUNCATE is a SQL statement used to quickly delete all rows from a table while retaining the table structure. Unlike the DELETE statement, TRUNCATE does not log individual row deletions and does not generate triggers, making it faster for large datasets.
Key Characteristics
- Performance:
TRUNCATEis more efficient thanDELETEbecause it uses minimal logging. - Data Integrity: It resets identity columns (e.g.,
AUTO_INCREMENT) to their seed values. - Irreversibility:
TRUNCATEoperations cannot be rolled back in most database systems, as it does not log row-level changes. - Constraints: Cannot truncate a table that is referenced by a foreign key.
Comparison: TRUNCATE vs. DELETE
| Feature | TRUNCATE |
DELETE |
|---|---|---|
| Row Logging | No | Yes |
| Triggers | Not activated | Activated |
| Rollback | Not supported in many systems | Supported |
| Identity Column Reset | Yes | No |
| Performance | Faster | Slower for large datasets |
Syntax
TRUNCATE TABLE table_name;
table_name: Specifies the name of the table to truncate.
Note: Use
TRUNCATEcarefully in production environments, as it cannot be undone.
Example
The TRUNCATE statement can be used to clear all records from a table while retaining its structure. For instance, to remove all data from a table named employee_data:
TRUNCATE TABLE employee_data;
This removes all rows from the employee_data table without affecting the table’s schema or structure.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn SQL on Codecademy
- Learn to analyze data with SQL and prepare for technical interviews.
- Includes 9 Courses
- With Certificate
- Beginner Friendly.18 hours
- In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.
- Beginner Friendly.5 hours