Sub topic 7
DELETE versus TRUNCATE
This chapter compares two ways to empty a table: DELETE and TRUNCATE TABLE. It assumes you can write a DELETE ... WHERE statement, know what COMMIT and ROLLBACK do, and understand primary key and foreign key constraints. The chapter uses the dept_demo, emp_demo, emp_stage, and emp_archive tables from earlier chapters.
The core difference
DELETE is a DML (data manipulation language) statement. It removes rows one at a time, writes undo and redo for each row, fires row-level triggers, and can be rolled back. It can take a WHERE clause, so it can remove some rows or all of them.
TRUNCATE TABLE is a DDL (data definition language) statement. It removes all rows at once by resetting the table's storage, not by touching each row. It cannot take a WHERE clause. Oracle commits before and after it runs, so you cannot roll it back.
-- DML: removes only matching rows, can be rolled back
DELETE FROM emp_stage WHERE status = 'INACTIVE';
ROLLBACK;
-- DDL: removes every row, commits implicitly, cannot be rolled back
TRUNCATE TABLE emp_stage;The rest of this chapter explains the consequences of that split.
Comparison table
| Feature | DELETE | TRUNCATE TABLE |
|---|---|---|
| Statement type | DML | DDL |
| `WHERE` clause | Yes | No |
| Rollback | Yes, until you commit | No. Commits implicitly |
| Row-level `DELETE` triggers | Fire | Do not fire |
| Undo and redo generated | Per row | Minimal |
| Speed on large tables | Slow | Fast |
| High-water mark | Stays where it was | Reset (by default, space is released) |
| Works on a table that foreign keys reference | Yes, if no child rows exist | No, even if the child table is empty (the parent must have its constraints disabled, or use `TRUNCATE ... CASCADE`) |
| Needed privilege | `DELETE` on the table | You own the table, or have `DROP ANY TABLE` |
| Flashback to the old data | Possible with flashback query within undo retention | Not possible with flashback query |
Why DELETE is slower
When DELETE removes a row, Oracle records the old row image in undo so that you can roll back and so that other sessions still see a consistent view. It also generates redo for both the data change and the undo change. For a table with millions of rows, this is a lot of logging. Indexes are also maintained entry by entry.
TRUNCATE skips this work. It deallocates the table's extents (the units of storage the table occupies) and resets the high-water mark. The high-water mark is the boundary between space that has been used and space that has never been used. Because a full table scan reads every block up to the high-water mark, a table emptied by DELETE can still be slow to scan even when it holds zero rows. A truncated table scans instantly.
-- After deleting every row, the table still owns its blocks
DELETE FROM emp_archive;
COMMIT;
-- Release the space and reset the high-water mark
TRUNCATE TABLE emp_archive;Space options
By default, TRUNCATE TABLE releases space except for the table's minimum extents. You can control this:
TRUNCATE TABLE emp_archive DROP STORAGE; -- default: release space
TRUNCATE TABLE emp_archive REUSE STORAGE; -- keep the allocated spaceUse REUSE STORAGE when you reload the table right away. A staging table that is emptied and refilled every night is a typical case, since the space is needed again anyway.
Behavior you can see: rollback
The difference in rollback is the one that causes most accidents. Compare these two sessions:
DELETE FROM emp_stage;
ROLLBACK;
SELECT COUNT(*) FROM emp_stage; -- the rows are backTRUNCATE TABLE emp_stage;
ROLLBACK; -- nothing to undo
SELECT COUNT(*) FROM emp_stage; -- 0Notice that TRUNCATE also commits any uncommitted work you did earlier in the same transaction. If you updated rows in another table and had not committed, those updates are now permanent as well.
Triggers and side effects
A BEFORE DELETE or AFTER DELETE trigger runs for each deleted row. If your application uses such triggers for auditing or for maintaining summary tables, TRUNCATE bypasses them and leaves the audit trail incomplete. Check for triggers before you replace a DELETE with a TRUNCATE.
TRUNCATE also resets nothing about sequences. A sequence is a separate object, so the next value it returns continues from where it was. If you want ids to start again, you must reset the sequence yourself.
Foreign keys
A DELETE on a parent table succeeds when no child row refers to the deleted rows. Otherwise Oracle raises ORA-02292, the child record found error, which you saw in the constraint chapter.
TRUNCATE is stricter. Oracle refuses to truncate a table that an enabled foreign key references, even if the child table is empty:
TRUNCATE TABLE dept_demo;
-- ORA-02266: unique/primary keys in table referenced by enabled foreign keysYou have three ways to proceed:
- Truncate the child table first, then disable the foreign key, truncate the parent, and enable the key again.
- Use
DELETEon the parent instead, after you remove child rows. - Use
TRUNCATE TABLE dept_demo CASCADE, which also truncates child tables whose foreign keys are declaredON DELETE CASCADE. This option is available in Oracle Database 12c and later.
ALTER TABLE emp_demo DISABLE CONSTRAINT sys_c0012345; -- use your real constraint name
TRUNCATE TABLE dept_demo;
ALTER TABLE emp_demo ENABLE NOVALIDATE CONSTRAINT sys_c0012345;Look up the real name in USER_CONSTRAINTS. Generated names such as SYS_C0012345 differ in every database. Re-enabling with ENABLE NOVALIDATE skips checking existing rows, so only use it when you know no child rows are left. Plain ENABLE validates every row and is safer.
Locks and concurrency
DELETE locks only the rows it removes, and other sessions can keep working on other rows. TRUNCATE needs an exclusive lock on the whole table. It fails with ORA-00054 (resource busy) if another session has an open transaction on the table. On a busy system, a scheduled TRUNCATE can therefore fail at random times.
Because TRUNCATE is DDL, it also invalidates dependent objects such as views and PL/SQL programs that refer to the table, and they recompile on next use.
Using TRUNCATE inside PL/SQL
PL/SQL cannot contain a plain DDL statement. Use dynamic SQL:
BEGIN
EXECUTE IMMEDIATE 'TRUNCATE TABLE emp_stage';
END;
/Table names cannot be bind variables, so if the name comes from user input, validate it with DBMS_ASSERT.SQL_OBJECT_NAME before you concatenate it into the statement.
Choosing between them
Pick DELETE when:
- you need a
WHEREclause; - you need to roll back or use a savepoint;
- delete triggers must fire;
- other sessions are using the table;
- foreign keys from other tables point at it.
Pick TRUNCATE when:
- you want to empty the entire table;
- the table is a staging or work table that nobody else is using;
- the table is large and the logging cost of
DELETEis a problem; - you accept that the change is permanent at once.
A middle path exists for large partitioned tables: ALTER TABLE ... TRUNCATE PARTITION empties one partition and leaves the rest alone.
Common errors
| Error | Cause | Fix |
|---|---|---|
| `ORA-02266` | An enabled foreign key references the table you are truncating | Disable the key, use `CASCADE`, or use `DELETE` |
| `ORA-02292` | A `DELETE` removes a parent row that still has children | Delete child rows first, or define the key with `ON DELETE CASCADE` |
| `ORA-00054` | Another session holds a lock on the table | Retry after that session commits or rolls back |
| `ORA-01031` | You lack the privilege to truncate a table in another schema | Ask for `DROP ANY TABLE`, or have the owner run it |
Exercise
A nightly job loads emp_stage and then must empty it before the next run. Nobody else queries the table, and no foreign keys point at it. Which statement should the job use, and what would you check first if a teammate suggests switching to TRUNCATE for emp_demo instead?
Show answer
Use TRUNCATE TABLE emp_stage REUSE STORAGE, because the whole table is emptied, it is a private work table, and the space is needed again for the next load. For emp_demo, check three things first. The table is referenced by no enabled foreign key. No DELETE trigger must fire for auditing. Nobody needs to roll the change back or use a WHERE clause. Since other tables may refer to emp_demo and sessions use it, DELETE is the safer choice.
Exercise
You run UPDATE emp_demo SET salary = salary + 1; without committing, then run TRUNCATE TABLE emp_stage; and then ROLLBACK;. Is the salary change undone?
Show answer
No. TRUNCATE is DDL and commits the open transaction before it runs, so the salary update is already permanent when ROLLBACK executes.