Sub topic 13
DROP, TRUNCATE and DELETE compared
This chapter assumes you can write basic SELECT, INSERT, UPDATE and DELETE statements, and that you know primary keys and foreign keys. The examples use PostgreSQL unless a comment says otherwise. Run them on a test database, not on data you care about.
Three ways to empty or remove a table
DELETE, TRUNCATE and DROP TABLE all make data disappear, but they act on different things:
DELETEremoves rows. The table, its columns and its constraints stay.TRUNCATEremoves all rows quickly. The table definition stays.DROP TABLEremoves the table itself: its rows, columns, indexes, triggers and the constraints defined on it.
Choosing the wrong one is a common cause of lost data or failed deployments, so it helps to know how each works internally.
DELETE: row-by-row removal
DELETE is a DML statement (Data Manipulation Language), the same family as INSERT and UPDATE. It is the only one of the three that accepts a WHERE clause.
CREATE TABLE log_entries (
id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
message TEXT NOT NULL
);
INSERT INTO log_entries (message) VALUES ('a'), ('b'), ('c');
DELETE FROM log_entries WHERE id = 2; -- removes one row
DELETE FROM log_entries; -- removes the remaining rowsCharacteristics of DELETE:
- The database processes each matching row. It checks foreign keys, fires row-level
DELETEtriggers and writes log records for each row. - It runs inside a transaction in every major database, so you can roll it back.
- It does not reset auto-increment or identity counters. After the statements above, the next inserted row gets
id4, not 1. - On a table with millions of rows it is slow, and it can leave dead space that the database must reclaim later (
VACUUMin PostgreSQL).
TRUNCATE: remove all rows at once
TRUNCATE discards the table's data without examining rows one at a time. It has no WHERE clause.
TRUNCATE TABLE log_entries RESTART IDENTITY;
INSERT INTO log_entries (message) VALUES ('d') RETURNING id; -- returns 1RESTART IDENTITY is PostgreSQL syntax that resets the counter. MySQL and SQL Server reset it by default. In PostgreSQL the default is CONTINUE IDENTITY.
Typical behavior, which varies by database:
- It is much faster than an unfiltered
DELETEon large tables, because it releases the table's storage instead of logging each row. - It does not fire row-level
DELETEtriggers. PostgreSQL has a separateTRUNCATEtrigger type. - It usually needs stronger privileges than
DELETE, and it takes a heavy lock. In PostgreSQL that isACCESS EXCLUSIVE, which blocks evenSELECTuntil the transaction ends. - SQLite has no
TRUNCATEstatement. UseDELETE FROM table_name;instead.
TRUNCATE and foreign keys
A table referenced by a foreign key generally cannot be truncated, even when the child table is empty. In PostgreSQL there are two ways around this:
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (id)
);
TRUNCATE TABLE customers; -- ERROR: cannot truncate a table referenced in a foreign key constraint
TRUNCATE TABLE customers, orders; -- works: both tables are truncated in one statement
TRUNCATE TABLE customers CASCADE; -- works: also truncates ordersCASCADE here empties every table that references the target, so use it with care. MySQL also refuses to truncate a referenced table. SQL Server requires you to drop the foreign key first.
TRUNCATE and transactions
Whether TRUNCATE can be rolled back depends on the database:
-- PostgreSQL
BEGIN;
TRUNCATE TABLE log_entries;
ROLLBACK;
SELECT count(*) FROM log_entries; -- the rows are backPostgreSQL and SQL Server allow this. In MySQL and Oracle, TRUNCATE is treated as DDL and commits implicitly, so it cannot be undone.
DROP TABLE: remove the table itself
DROP TABLE IF EXISTS log_entries;After this, SELECT * FROM log_entries fails because the table no longer exists. The statement also removes the table's indexes, triggers and its own constraints. Other objects that depend on the table, such as foreign keys in other tables and views, block a plain DROP TABLE unless you use CASCADE, as covered in earlier chapters.
Side-by-side comparison
| Feature | DELETE | TRUNCATE | DROP TABLE |
|---|---|---|---|
| Statement type | DML | DDL (or DDL-like) | DDL |
| `WHERE` clause | Yes | No | No |
| Removes rows | Selected or all | All | All |
| Keeps table structure | Yes | Yes | No |
| Resets identity counter | No | Usually yes | Not applicable |
| Fires row `DELETE` triggers | Yes | No | No |
| Rollback in PostgreSQL | Yes | Yes | Yes |
| Rollback in MySQL | Yes | No (implicit commit) | No (implicit commit) |
| Speed on large tables | Slowest | Fast | Fast |
| Works with foreign keys | Checked per row | Blocked if referenced | Blocked if referenced |
Choosing the right statement
- Remove some rows:
DELETE ... WHERE. Always run the same condition as aSELECTfirst to see what it matches. - Empty a table you will reuse, such as a staging table before a data load:
TRUNCATE. - Remove the table because the feature is gone:
DROP TABLE, after you have confirmed that nothing reads it. - Remove all rows but need triggers to run, or need the operation to be rolled back in MySQL:
DELETE FROM table_name;.
Common errors
- Running
DELETE FROM orders;without aWHEREclause. Wrapping the statement in a transaction lets you check the row count before you commit. - Expecting
TRUNCATEto runON DELETEtriggers that write audit records. They do not run. - Expecting identity values to restart after
DELETE. They do not. - Running
TRUNCATE ... CASCADEagainst a parent table and emptying child tables you did not intend to touch. - Assuming a
TRUNCATEorDROPcan be rolled back on MySQL or Oracle. It cannot.
Exercise
A table staging_events is referenced by a foreign key from event_details. You want to empty both tables in PostgreSQL before tomorrow's load, keep their definitions, and restart their identity counters. Which single statement does this, and why does TRUNCATE TABLE staging_events; alone fail?
Show answer
Use TRUNCATE TABLE staging_events, event_details RESTART IDENTITY;. The single-table form fails because staging_events is referenced by a foreign key from event_details, and PostgreSQL refuses to truncate a referenced table unless the referencing table is truncated in the same statement or CASCADE is given. Listing both tables, or adding CASCADE, satisfies the check. RESTART IDENTITY resets the counters, and the table definitions stay in place.
Exercise
You run DELETE FROM log_entries; on a PostgreSQL table with an identity column whose last value was 3, and then insert a new row. What id does the new row get, and which statement would make it get 1 instead?
Show answer
The new row gets 4, because DELETE does not reset the identity counter. TRUNCATE TABLE log_entries RESTART IDENTITY; empties the table and resets the counter, so the next row gets 1.