What is the difference between DELETE, TRUNCATE and DROP?
EasyConceptDBMS Fundamentals
Answer
DELETE removes selected rows, TRUNCATE removes all rows but keeps the empty table, and DROP removes the whole table, including its structure, indexes and constraints.
DELETEis DML: it accepts aWHEREclause, removes rows one at a time, fires delete triggers and can be rolled back.TRUNCATEis DDL: it deallocates the data pages at once, so it is much faster on large tables. It takes noWHEREclause, does not fire delete triggers, and resets the auto-increment counter in MySQL and SQL Server.DROPis DDL: afterwards, any query on the table fails because the table no longer exists.- Rolling back
TRUNCATEorDROPworks inside a transaction in PostgreSQL and SQL Server, but not in MySQL or Oracle, where DDL commits implicitly.
Example: For an orders table with 3 rows:
DELETE FROM orders WHERE id = 2; -- 2 rows remain
TRUNCATE TABLE orders; -- 0 rows, table still exists
DROP TABLE orders; -- the table itself is gone