QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › Changing data and transactions

How do DELETE, TRUNCATE and DROP differ?

DELETE removes rows by condition, TRUNCATE quickly empties the whole table, and DROP removes the table with its structure. TRUNCATE fires no row triggers, takes an ACCESS EXCLUSIVE lock in PostgreSQL and does not reset the id counter without RESTART IDENTITY. It can be rolled back in PostgreSQL but not in MySQL and Oracle. CASCADE empties dependent tables too.

SQL · Changing data and transactions

The environment must be cleared before a run. TRUNCATE fails and CASCADE supposedly fixes everything. What else will it wipe?

Before a regression run the orders table must be cleared. The first attempt, TRUNCATE orders, fails with an error and the hint suggests CASCADE. Three commands remove data in different ways: rows, all rows or the whole table, and the difference concerns speed, locks, id counters and related tables.

How it works and why. DELETE processes rows one by one under the WHERE condition, fires row triggers, returns the number of deleted rows and locks only those rows. In PostgreSQL the deleted row versions remain as "dead" until VACUUM cleans them, so a big delete is slow and bloats the table. TRUNCATE does not walk the rows but replaces the table storage with an empty one: it is almost instant regardless of size. There is no condition and no row triggers (ON TRUNCATE triggers exist), but the strongest lock, ACCESS EXCLUSIVE, is taken and blocks even reads. DROP TABLE removes the table itself: data, structure, indexes.

DELETETRUNCATEDROP
What it removesRows by conditionAll rowsThe whole table
WHEREYesNoNo
LockRow-levelACCESS EXCLUSIVEACCESS EXCLUSIVE
Row triggersFireNoNo
Rollback before COMMITYesPostgreSQL, SQL Server: yes. MySQL, Oracle: noPostgreSQL: yes. MySQL, Oracle: no
Id counterNot resetPostgreSQL: only with RESTART IDENTITY; MySQL resetsGone with the table

For PostgreSQL the next insert behaves as follows (the last id was 1000):

Cleared withNext id
DELETE FROM orders1001
TRUNCATE orders1001
TRUNCATE orders RESTART IDENTITY1

A test expecting "the first order has id 1" depends on how the table was cleared.

Example: TRUNCATE and related tables. The order_items table references orders through a foreign key.

TRUNCATE orders;
-- ERROR:  cannot truncate a table referenced in a foreign key constraint
-- DETAIL:  Table "order_items" references "orders".   (shortened)

TRUNCATE orders CASCADE;
-- NOTICE:  truncate cascades to table "order_items"

The error protects: an empty parent table would leave items without orders. CASCADE "fixes" it by clearing order_items too, and every table that references it further down the chain. On a shared environment that is other people's data. The right options depend on the environment:

-- own environment: both tables together
TRUNCATE orders, order_items RESTART IDENTITY;

-- shared: only your own rows, children first
DELETE FROM order_items
WHERE order_id IN (SELECT id FROM orders WHERE user_id = 42);
DELETE FROM orders WHERE user_id = 42;

Clearing orders: two approaches

Wrong

TRUNCATE orders CASCADE

Clears order_items too, and every table further down the chain. On a shared environment other people's data vanishes, and the lock during the command affects everyone.

Right

DELETE children, then parents, by condition

Touches only your rows, returns a count, rolls back until COMMIT, and the locks are row-level.

Figure 1. CASCADE extends the command to tables you may not have thought about.

Limits and alternatives. In MySQL and Oracle TRUNCATE and DROP are not rollback-friendly: they are DDL with an implicit commit. On small tables DELETE without WHERE is often enough and gives a rollback in any database. Test isolation can be built differently: a separate schema or database per run, per-test data with its own marker, a transaction rolled back after the test.

Common mistakes.

  • TRUNCATE … CASCADE "to make it pass": more is cleared than intended.
  • TRUNCATE on a table someone else's test is reading right now: the command waits for the lock or blocks others itself.
  • Expecting a TRUNCATE rollback in MySQL.
  • Forgetting that ids continue after DELETE while the test expects id 1.
  • DELETE of millions of rows in one statement: a long transaction and a bloated table. Delete in batches or use TRUNCATE where allowed.

Check yourself

Why does TRUNCATE orders fail when order_items references orders, and why is that no reason to add CASCADE at once?

Answer

Empty parent rows would leave items without orders, so PostgreSQL refuses. CASCADE clears the child tables and anything that references them further. First find out which tables they are and whether they are yours.

The table was cleared, a row was inserted and its id is 1001 while the test expected 1. What to change?

Answer

The clearing was DELETE or TRUNCATE without RESTART IDENTITY: the sequence continued. Better still, do not depend on the id value: the test should take the id from RETURNING.

In an interview. Junior: DELETE removes rows by condition and rolls back inside a transaction. TRUNCATE quickly clears the whole table with no condition, and DROP removes the table with its structure. Middle/Senior: TRUNCATE does not walk rows, does not fire row triggers, takes ACCESS EXCLUSIVE and does not reset the sequence without RESTART IDENTITY. In PostgreSQL it can be rolled back, in MySQL and Oracle it cannot. CASCADE extends the effect to dependent tables, so on a shared environment I use DELETE by condition and leave TRUNCATE for my own environment.

More articles in this chapter