Question presented to candidate:
"We need to clear out an audit_log table. A colleague says use DELETE, another says TRUNCATE, and someone suggested just dropping it. What does each one actually do, and how would you choose?"
What a strong answer should cover:
DELETEremoves chosen rows (or all, withoutWHERE), row by row, as normal DML: fires row triggers, checks foreign keys per row, can be rolled back, can return the deleted rowsTRUNCATEremoves all rows at once by replacing the table storage: much faster on big tables, gives the space back immediately, fires noON DELETEtriggers, can reset identity counters, and refuses when another table has a foreign key to itDROP TABLEremoves the table itself: rows, definition, indexes, constraints, triggers and grants- Transactions: in PostgreSQL and SQL Server all three can be rolled back; in MySQL
TRUNCATEandDROPcause an implicit commit; SQLite has noTRUNCATEat all - Locking and concurrency in PostgreSQL:
DELETEtakes a row-level lock mode,TRUNCATEanACCESS EXCLUSIVElock, andTRUNCATEis not MVCC-safe - After a big
DELETEin PostgreSQL the space is only reclaimed byVACUUM
Clarifying questions expected:
- Do we need all rows gone, or only old ones (for example older than 90 days)?
- Do other tables reference this one, and do triggers or replication depend on row-level deletes?
- Is the table being read or written concurrently while we clear it?
Code / implementation expected: Optional β the three statements, and ideally a demonstration of rollback or identity behaviour.
Schema used by the examples: