πŸ—οΈ SQL Table & Database Management
Estimated reading: 2 minutes 281 views

🚰 SQL TRUNCATE TABLE – Quickly Delete All Rows from a Table

Introduction – What is SQL TRUNCATE TABLE?

The TRUNCATE TABLE command in SQL is used to delete all rows from a table efficiently, while preserving the table’s structure, columns, and constraints. It’s often faster than DELETE and used for quick, irreversible cleanups.

In this guide, you’ll learn:

  • Syntax and behavior of TRUNCATE TABLE
  • Differences between DELETE, DROP, and TRUNCATE
  • Performance implications and best use cases

1. TRUNCATE TABLE Syntax

TRUNCATE TABLE table_name;

Instantly removes all rows from the table.


2. TRUNCATE vs DELETE vs DROP

CommandDeletes DataKeeps StructureRollback SupportAffects Identity (Autoinc)
DELETE (if in transaction)
TRUNCATE (some DBMS) (resets counter)
DROP TABLE

3. Example – Truncate a Log Table

TRUNCATE TABLE audit_logs;

Clears all records from audit_logs but keeps table definition intact.


4. Behavior Notes

  • Cannot truncate a table referenced by foreign key constraints
  • Often faster than DELETE because it bypasses row-by-row logging
  • May reset IDENTITY/AUTOINCREMENT fields depending on DBMS
  • Not always rollback-safe (e.g., MySQL autocommit mode)

Best Practices

Recommended Avoid This
Use for temp or staging table cleanupTruncating tables with foreign keys
Test on a copy before production executionAssuming rollback is possible
Pair with backup in live environmentsUsing in audit or production tables

Summary – Recap & Next Steps

TRUNCATE TABLE is a quick and efficient method to remove all records from a table. It’s best for non-critical, non-referenced tables where full deletion is required.

Key Takeaways:

  • TRUNCATE is faster and cleaner than DELETE
  • Keeps table structure, drops only the data
  • May reset IDENTITY and bypass transactions

Real-World Relevance:
Used in staging environments, ETL pipelines, testing frameworks, and log cleaning routines.

Next: Learn DROP TABLE to remove table structures or DELETE for selective row deletions.


FAQ – SQL TRUNCATE TABLE

Does TRUNCATE remove the table?

No. It removes all rows but keeps the table structure intact.

Can I roll back a TRUNCATE?

Depends on DBMS. PostgreSQL supports it in transactions. MySQL may not.

Can I truncate a table with a foreign key?

No. Most DBMS prevent it unless the key is dropped or disabled.

Does TRUNCATE reset identity values?

Yes, in SQL Server and PostgreSQL. MySQL depends on engine configuration.


Share Now :
Share

🚰 SQL TRUNCATE TABLE

Or Copy Link

CONTENTS
Scroll to Top