Sub topic 14
DELETE versus TRUNCATE
This chapter assumes you can write DELETE ... WHERE, know what a transaction is, and understand primary keys, foreign keys, and identity (auto-increment) columns at a basic level. It uses the customers and orders tables from earlier in the tutorial. The examples are PostgreSQL unless a note says otherwise.
Two ways to empty a table
Both statements remove rows, and both can leave a table empty. They differ in what they promise and what they skip.
DELETEis a data manipulation statement. It finds rows, optionally filtered byWHERE, and removes them one at a time.TRUNCATEremoves every row at once. It has noWHEREclause. Most databases do this by releasing the table's storage instead of visiting each row.
The result looks the same, but transaction behavior, triggers, identity counters, foreign key handling, and required permissions all differ.
DELETE FROM orders;
TRUNCATE TABLE orders;After either statement, SELECT COUNT(*) FROM orders returns 0. Everything else about them is different.
How DELETE works
DELETE processes each matching row individually:
- It locks each row it removes.
- It writes a log record for each row, so the change can be rolled back or recovered.
- It fires any row-level
DELETEtriggers. - It checks foreign keys and applies their delete actions.
- It reports how many rows it removed.
This is why DELETE is safe and flexible. It is also why DELETE FROM big_table is slow on millions of rows: the database does per-row work and writes a log entry for each one. In most systems DELETE also leaves the freed space allocated to the table, and the database reuses that space for later inserts.
How TRUNCATE works
TRUNCATE skips the per-row work. It deallocates the table's data pages (or swaps in a new empty storage file) and logs only that deallocation. As a result:
- It runs fast, and its cost barely depends on the row count.
- It takes a stronger lock on the whole table. In PostgreSQL that is an
ACCESS EXCLUSIVElock, which blocks even plainSELECTstatements until the transaction ends. - Row-level
DELETEtriggers do not fire. PostgreSQL offers separateTRUNCATEtriggers. - It usually returns no useful row count. MySQL, for example, reports 0 rows affected.
- It requires its own privilege in many systems. PostgreSQL has a
TRUNCATEprivilege, and SQL Server requiresALTERpermission on the table.
Identity counters
Auto-numbering behaves differently, and this is a common surprise. The next example uses a new table with an identity column.
CREATE TABLE audit_log (
id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
message VARCHAR(200) NOT NULL
);
INSERT INTO audit_log (message) VALUES ('a'), ('b'), ('c');
DELETE FROM audit_log;
INSERT INTO audit_log (message) VALUES ('d');
SELECT id, message FROM audit_log;
-- id = 4: DELETE did not reset the counter
TRUNCATE TABLE audit_log RESTART IDENTITY;
INSERT INTO audit_log (message) VALUES ('e');
SELECT id, message FROM audit_log;
-- id = 1: the counter restartedDELETE never rewinds the counter. TRUNCATE rewinds it in SQL Server and MySQL automatically. PostgreSQL keeps the counter unless you add RESTART IDENTITY, and the default is CONTINUE IDENTITY.
Resetting a counter is not always desirable. If other systems stored the old ids, such as exported files or logs, reusing them can create confusing duplicates.
Rollback behavior
Earlier in this tutorial you wrapped a DELETE in a transaction and used ROLLBACK to undo it. Whether the same works for TRUNCATE depends on the database.
BEGIN;
TRUNCATE TABLE orders;
SELECT COUNT(*) FROM orders; -- 0
ROLLBACK;
SELECT COUNT(*) FROM orders; -- the original count is backThis works in PostgreSQL and SQL Server, where TRUNCATE is transactional. In MySQL and Oracle, TRUNCATE counts as a schema-changing statement. It commits any open transaction first, and it cannot be rolled back afterward.
Foreign keys
A foreign key makes TRUNCATE harder to use. The orders table has a foreign key to customers, so customers is the parent table.
TRUNCATE TABLE customers;
-- PostgreSQL: ERROR: cannot truncate a table referenced in a foreign key constraintThe database refuses because it skips the per-row checks that would catch orphaned rows. The rules differ by system:
- PostgreSQL refuses unless you truncate every referencing table in the same statement, or you add
CASCADE. - SQL Server refuses to truncate a table that a foreign key references, even if the child table is empty. You must delete the rows, or drop the constraint first.
- MySQL (InnoDB) refuses for referenced tables, unless foreign key checks are disabled.
In PostgreSQL, you can list both tables in a single statement:
TRUNCATE TABLE customers, orders;TRUNCATE ... CASCADE truncates every table that references the target, including tables you did not name. Run TRUNCATE without CASCADE first and read the error before you add it.
DELETE handles foreign keys with no special rules. Deleting from customers while orders still references those customers fails, or triggers whatever ON DELETE action the constraint defines (see the earlier chapter on foreign keys and deleting parent rows).
Side-by-side comparison
| Feature | DELETE | TRUNCATE |
|---|---|---|
| Category | Data manipulation | Usually treated as schema-level (data definition) |
| `WHERE` clause | Yes | No |
| Speed on a large table | Slow, per-row work | Fast, nearly constant |
| Row-level triggers | Fire | Do not fire |
| Rollback | Always | PostgreSQL and SQL Server yes. MySQL and Oracle no. |
| Identity counter | Unchanged | Reset in SQL Server and MySQL. PostgreSQL only with `RESTART IDENTITY`. |
| Rows affected reported | Yes | Usually not meaningful |
| Table referenced by a foreign key | Allowed, rows are checked | Restricted |
| Locking | Row locks | Table-level lock |
SQLite has no TRUNCATE
SQLite does not support the TRUNCATE statement. Use DELETE FROM table_name instead. When there is no WHERE clause, SQLite takes a shortcut and clears the table without visiting each row, so it is fast. Because SQLite's DELETE is already transactional, ROLLBACK works as usual.
If the table has an AUTOINCREMENT column, the counter lives in the internal sqlite_sequence table. You can reset it with this statement:
DELETE FROM sqlite_sequence WHERE name = 'audit_log';Where DROP TABLE fits
DROP TABLE goes further than either statement. It removes the rows and the table's definition: columns, constraints, and indexes. Use DELETE or TRUNCATE to empty a table you will keep using, and use DROP TABLE only when the table should no longer exist.
Choosing between them
Use DELETE when:
- You need to remove only some rows.
- Triggers must fire, for example to write an audit trail.
- You need a row count to confirm the result.
- The table is referenced by foreign keys.
- You need guaranteed rollback in every database.
Consider TRUNCATE when:
- You want every row gone, such as in a staging table cleared before each data load.
- The table is large and
DELETEis too slow. - No other table references it, or you can handle those references.
- You have the permission and understand its rollback behavior in your database.
For a very large table where you need DELETE ... WHERE, some teams delete in batches (for example, a few thousand rows per statement) to keep each transaction and lock short. The syntax for limiting a DELETE varies by dialect, so check yours.
Exercise
A staging table import_rows has 50 million rows and no foreign keys referencing it. You run TRUNCATE TABLE import_rows; in MySQL inside a transaction, then run ROLLBACK;. What is the state of the table, and why would the result differ in PostgreSQL?
Show answer
In MySQL the table is empty and stays empty. TRUNCATE implicitly commits, so the ROLLBACK has nothing to undo. In PostgreSQL TRUNCATE is transactional, so the ROLLBACK restores all 50 million rows.
Exercise
You run DELETE FROM audit_log; and then insert a new row into a PostgreSQL table with an identity column. The new row gets id 4 instead of 1. What command would have reset the counter, and how would you write it?
Show answer
TRUNCATE TABLE audit_log RESTART IDENTITY; resets the counter. DELETE never rewinds an identity counter, and PostgreSQL's TRUNCATE keeps the counter unless you add RESTART IDENTITY.
Exercise
In PostgreSQL, TRUNCATE TABLE customers; fails because orders has a foreign key to customers. Name two ways to remove all customer rows, and state one risk of each.
Show answer
Option 1: TRUNCATE TABLE customers, orders; empties both tables together. The risk is that you also lose all orders, even if you only meant to clear customers. Option 2: DELETE the rows (after deleting or handling the child rows in orders). The risk is that it is slower on a large table and fails if any child rows still reference the customers. TRUNCATE ... CASCADE also works, but it can empty tables you did not name.