Junior — Middle
What is the difference between executing the TRUNCATE command and using the DELETE command when clearing a table?
sobes.tech AI
Answer from AI
The TRUNCATE and DELETE commands are both used to remove data from a table, but they have significant differences:
-
TRUNCATE:
- A fast operation that removes all rows from the table entirely.
- Usually operates without logging the deletion of each row, which speeds up the process.
- Does not invoke DELETE triggers.
- Does not allow the use of WHERE — it deletes all data.
- Can reset auto-increment counters.
- Restoring data after TRUNCATE is more difficult, as the operation is often not logged row-by-row.
-
DELETE:
- Removes rows based on a condition (if WHERE is specified), or all rows if WHERE is absent.
- Logs the deletion of each row, which can be slower.
- Invokes DELETE triggers.
- Allows more flexible data removal.
Example:
-- Quickly delete all records from a table
TRUNCATE TABLE employees;
-- Delete only employees from the 'Sales' department
DELETE FROM employees WHERE department = 'Sales';
Thus, TRUNCATE is suitable for quickly clearing an entire table, while DELETE is used for selective removal.