β‘ SQL TRUNCATE TABLE β Quickly Delete All Rows from a Table
Need to remove all records from a table β fast and efficiently? The
TRUNCATE TABLEstatement is your go-to SQL command for quickly deleting all data from a table without logging each row deletion.
π What is SQL TRUNCATE TABLE?
The TRUNCATE TABLE statement removes all rows from a table instantly. Unlike DELETE, which logs each deleted row, TRUNCATE works like a reset β it’s faster, uses fewer system resources, and doesnβt fire DELETE triggers.
π§Ύ SQL TRUNCATE TABLE Syntax
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE employees;
This removes all data from the employees table, while keeping the table structure (columns, constraints, etc.) intact.
β οΈ Key Differences: TRUNCATE vs DELETE
| Feature | TRUNCATE TABLE | DELETE |
|---|---|---|
| Removes all rows? | β Yes | β
Yes (with or without WHERE) |
Can use WHERE clause? | β No | β Yes |
| Logs individual deletions? | β No (minimal logging) | β Yes |
| Triggers activated? | β No | β Yes |
| Faster performance? | β Very fast | β Slower for large tables |
| Rollback supported? | β Yes (in most RDBMS with transactions) | β Yes |
β
Use Cases for TRUNCATE TABLE
- Resetting a staging or temporary table before reloading fresh data
- Clearing audit logs or user activity history periodically
- Purging test data from a development environment
- Cleaning large tables during ETL processes
π‘ Things to Know
- You cannot truncate a table referenced by a foreign key constraint (even if empty).
- In SQL Server,
TRUNCATEresets identity columns to their seed value. - In PostgreSQL,
TRUNCATEsupportsCASCADEto truncate dependent tables. - Some databases (e.g., Oracle) require specific privileges to use
TRUNCATE.
π§ Real-World Example
Letβs say you have a table sales_temp used to store daily imported sales data for reporting. Before loading the next dayβs data, you can run:
TRUNCATE TABLE sales_temp;
This clears the table instantly, without affecting its schema β keeping your ETL process smooth and efficient.
π Summary
TRUNCATE TABLEis a fast, efficient way to delete all rows from a table.- It keeps the table structure but clears the data.
- Ideal for bulk cleanup tasks in development, testing, or staging environments.
- Not suitable if you need fine-grained deletions or trigger execution.