Video in progress

How do the DELETE, TRUNCATE and DROP TABLE commands differ?

DELETE / TRUNCATE / DROP — Pick rows with WHERE: yes / no / no; Speed on a big table: slow / very fast / very fast; Triggers: ON DELETE fires / does not fire / —; Structure stays: yes / yes / no

📖 Answer

DELETE TRUNCATE DROP
Pick rows with WHERE yes no no
Speed on a big table slow very fast very fast
Triggers ON DELETE fires does not fire —
Structure stays yes yes no

DELETE FROM logs on 50 million rows can take hours: every row is marked as "deleted", written to the WAL, and then VACUUM has to clean up. TRUNCATE logs swaps the files, so it's instant.

In PostgreSQL both work inside a transaction, which means you can even ROLLBACK a TRUNCATE. Some other databases (Oracle, MySQL, for example) don't allow that. Mentioning it in an interview leaves a good impression.

Be careful: if another table references this one with an FK, TRUNCATE fails, while TRUNCATE ... CASCADE empties the dependent tables too.