// dialect comparison

TRUNCATE vs DELETE: emptying a table

Two ways to empty a table that differ in speed, triggers, identity counters and rollback.

Filed under Inserting & updating

The verdict

Use TRUNCATE when you mean all of it and no DELETE triggers need to run; use DELETE when you need a WHERE, per-row triggers or a rollback on MySQL and Oracle. SQLite picks the fast path for you.

Where they differ

TRUNCATE deallocates the table's storage instead of deleting row by row, so it is near-instant. It fires no DELETE triggers, resets identity counters in SQL Server and MySQL, and commits implicitly in MySQL and Oracle. SQLite has no TRUNCATE; an unfiltered DELETE takes a similar fast path.

How each engine writes it

SQL Server

TRUNCATE TABLE orders;

Near-instant, resets IDENTITY, fires no triggers, and can be rolled back inside a transaction. Fails while any foreign key references the table, even from an empty table.

PostgreSQL

TRUNCATE TABLE orders RESTART IDENTITY CASCADE;

Can truncate several tables in one call. RESTART IDENTITY resets sequences; CASCADE reaches referencing tables that would otherwise block it.

MySQL

TRUNCATE TABLE orders;

Implicit commit, so it can't be rolled back. Resets AUTO_INCREMENT. Fails while another table's foreign key references this one, unless foreign_key_checks = 0.

SQLite

DELETE FROM orders;
DELETE FROM sqlite_sequence WHERE name = 'orders';

No TRUNCATE. An unfiltered DELETE uses the truncate optimization unless the table has triggers. The second statement resets the counter and only applies to AUTOINCREMENT tables.

Oracle

TRUNCATE TABLE orders;

DDL, so it commits implicitly and can't be rolled back. Frees the space by default; REUSE STORAGE keeps it. 12c+ adds TRUNCATE … CASCADE for ON DELETE CASCADE foreign keys.

Questions that come up

Can TRUNCATE roll back?

In SQL Server and PostgreSQL, yes, inside an explicit transaction. MySQL and Oracle treat it as DDL with an implicit commit, so the rows are gone once it runs.

Does TRUNCATE reset the identity counter?

Yes in SQL Server and MySQL. PostgreSQL keeps the sequence unless you add RESTART IDENTITY. Oracle keeps it too; reset it with ALTER TABLE orders MODIFY id GENERATED ALWAYS AS IDENTITY (START WITH 1).

Why does TRUNCATE fail with foreign keys?

It skips row-by-row processing, so the engine can't check child rows one at a time and refuses when another table's foreign key points at this one. Truncate the child tables first (PostgreSQL's CASCADE does it in one call), drop the constraint, or use DELETE.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.