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.
Two ways to empty a table that differ in speed, triggers, identity counters and rollback.
Filed under Inserting & updating
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.
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.
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.
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.
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.
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.
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.
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.
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).
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.
Remove the orders of deleted customers: two tables, one DELETE, four syntaxes.
Five engines, five spellings of the column that numbers itself.
Migrating data with its original ids: three engines make you ask first, two just accept the value.
SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.