Sub topic 6
Removing rows with DELETE
This chapter covers how DELETE removes rows from an Oracle table, how it interacts with foreign keys and transactions, and how to run it safely. It assumes you can write a SELECT with a WHERE clause, know primary key, foreign key, and NOT NULL constraints, and can run SQL in SQL*Plus, SQL Developer, or SQLcl. The examples use the dept_demo, emp_demo, emp_stage, and emp_archive tables from earlier in the tutorial.
The basic statement
DELETE removes whole rows. It cannot remove single column values. To blank out a column, use UPDATE ... SET column = NULL.
DELETE FROM emp_demo
WHERE status = 'INACTIVE';The FROM keyword is optional in Oracle, but most teams write it. The WHERE clause chooses the rows. Any condition you can use in a SELECT works here, including AND, OR, IN, BETWEEN, LIKE, and subqueries.
If you leave out WHERE, every row in the table is deleted:
DELETE FROM emp_demo;Oracle does not ask for confirmation. The statement succeeds and reports the number of rows removed. Nothing is permanent until you commit, so a mistake can still be undone with ROLLBACK if you notice before committing.
You can give the table an alias and use it in the condition. The alias comes right after the table name, with no AS:
DELETE FROM emp_demo e
WHERE e.salary < 5000;How DELETE behaves inside a transaction
A DELETE starts a transaction if one is not already open. Until you commit, the following holds:
- The deleted rows are still visible to your own session only as gone. Other sessions keep seeing them.
- Oracle keeps the old row images in undo data, which is what makes
ROLLBACKpossible. - Every deleted row is locked, so other sessions cannot update or delete it until you finish.
You can combine DELETE with a savepoint to undo part of your work:
SAVEPOINT before_cleanup;
DELETE FROM emp_demo WHERE status = 'INACTIVE';
ROLLBACK TO SAVEPOINT before_cleanup;After the rollback to the savepoint, the rows are back and the transaction is still open. You still have to COMMIT or ROLLBACK to end it.
A safe workflow
Most accidental data loss comes from a wrong WHERE clause. Build the habit of previewing the rows before deleting them.
In practice:
SELECT COUNT(*) FROM emp_demo WHERE status = 'INACTIVE';
DELETE FROM emp_demo WHERE status = 'INACTIVE';SQL*Plus, SQL Developer, and SQLcl print a message such as 1 row deleted. Compare it with the count. In PL/SQL, the implicit cursor attribute SQL%ROWCOUNT holds the number of rows the last DML statement affected:
SET SERVEROUTPUT ON
BEGIN
DELETE FROM emp_demo WHERE status = 'INACTIVE';
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT || ' rows deleted');
ROLLBACK;
END;
/This block ends with ROLLBACK, so it is a dry run. Replace it with COMMIT when you are satisfied.
Deleting based on other tables
Often the rows to remove are identified by data in another table. Two patterns cover most cases.
IN with a subquery
DELETE FROM emp_demo
WHERE dept_id IN (SELECT dept_id
FROM dept_demo
WHERE dept_name = 'Sales');EXISTS with a correlated subquery
A correlated subquery refers to a column of the outer table. This statement deletes only the inactive employees that have already been copied to the archive:
DELETE FROM emp_demo e
WHERE e.status = 'INACTIVE'
AND EXISTS (SELECT 1
FROM emp_archive a
WHERE a.emp_id = e.emp_id);Archiving first and deleting second is a common pattern. Because the EXISTS test checks the archive, a row that failed to archive is not deleted.
Prefer NOT EXISTS over NOT IN
NOT IN has a trap. If the subquery returns even one NULL, the condition is never true for any row, and the DELETE removes nothing. In emp_demo, dept_id is nullable, so this statement is unsafe:
DELETE FROM dept_demo d
WHERE d.dept_id NOT IN (SELECT dept_id FROM emp_demo);If any employee has a null dept_id, zero rows are deleted and no error appears. The safe version uses NOT EXISTS:
DELETE FROM dept_demo d
WHERE NOT EXISTS (SELECT 1
FROM emp_demo e
WHERE e.dept_id = d.dept_id);This removes departments that have no employees, whether or not some employees have a null department.
Foreign keys and ORA-02292
A foreign key stops you from deleting a parent row while child rows still point to it. Try to delete the Engineering department while Ada works there:
DELETE FROM dept_demo WHERE dept_id = 20;Oracle rejects the statement:
ORA-02292: integrity constraint (SCHEMA.SYS_C0012345) violated - child record foundThe constraint name and schema in your output will differ. You have three ways to resolve this:
- Delete the child rows first, then the parent.
- Reassign the children with an
UPDATE, for example to anotherdept_id, then delete the parent. - Define the foreign key with an
ON DELETErule, so Oracle handles children automatically.
| Foreign key rule | Effect when a parent row is deleted |
|---|---|
| No `ON DELETE` clause (default) | The delete fails with ORA-02292 if children exist |
| `ON DELETE CASCADE` | The child rows are deleted too |
| `ON DELETE SET NULL` | The child foreign key column is set to `NULL` |
The rule belongs to the foreign key, not to the DELETE statement. Here is a table that detaches its rows instead of blocking:
CREATE TABLE project_demo (
project_id NUMBER PRIMARY KEY,
project_name VARCHAR2(50) NOT NULL,
dept_id NUMBER REFERENCES dept_demo (dept_id) ON DELETE SET NULL
);A failed DELETE does not leave partial changes. Oracle rolls back the whole statement, so either all matching rows are deleted or none are. Earlier statements in your transaction are not affected.
Removing duplicate rows
emp_stage was created with CREATE TABLE ... AS SELECT, which does not copy the primary key. It can therefore contain duplicate emp_id values. Every Oracle row has a ROWID pseudocolumn that identifies it uniquely, and you can use it to keep one row per key:
DELETE FROM emp_stage s
WHERE s.ROWID NOT IN (SELECT MIN(ROWID)
FROM emp_stage
GROUP BY emp_id);ROWID is never NULL, so the NOT IN problem described earlier does not apply here. This keeps the physically lowest row for each emp_id. If you want to keep the newest or highest-paid row instead, use ROW_NUMBER() in a subquery and delete where the rank is greater than 1.
Deleting large amounts of data
Deleting many rows is slow compared with the work you might expect, for these reasons:
- Each row is locked and written to undo.
- Indexes on the table are maintained for every deleted row.
- Foreign key checks run against child tables.
- Redo is generated for all of it.
A long-running delete also holds its locks for the whole time, so other sessions that touch those rows must wait. If you delete only a small part of a big table, keep the WHERE clause selective and indexed where possible. If you need to empty a whole table, DELETE is usually the wrong tool, and the next chapter compares it with TRUNCATE.
Common mistakes
- Missing
WHERE. The whole table is deleted. Run the matchingSELECTfirst. - Committing too early. In clients with auto-commit on, each statement is permanent immediately. Check your client setting before experimenting on real data.
- Using
NOT INagainst a nullable column. UseNOT EXISTS. - Ignoring the row count. A result of
0 rows deleted.often means the condition did not match, for examplestatus = 'inactive'when the stored value is'INACTIVE'. String comparisons in Oracle are case sensitive. - Forgetting child tables. ORA-02292 tells you a child row exists. It does not tell you which table, so look up the constraint name in
USER_CONSTRAINTS.
Exercise
You run DELETE FROM deptdemo d WHERE d.deptid NOT IN (SELECT deptid FROM empdemo); to remove empty departments. It reports 0 rows deleted, although department 10 has no employees. One employee row in empdemo has a NULL deptid. Why did nothing happen, and how do you fix the statement?
Show answer
The subquery returns a NULL, so the NOT IN comparison evaluates to unknown for every department row and no row qualifies. Rewrite it with NOT EXISTS: DELETE FROM deptdemo d WHERE NOT EXISTS (SELECT 1 FROM empdemo e WHERE e.deptid = d.deptid); NOT EXISTS ignores the NULL because the correlated comparison simply finds no match for department 10.
Exercise
Write a safe sequence that removes inactive employees from emp_demo, checks the number of rows deleted, and undoes the deletion if the number is not what you expected.
Show answer
First run SELECT COUNT(*) FROM empdemo WHERE status = 'INACTIVE'; to see the expected count. Then run DELETE FROM empdemo WHERE status = 'INACTIVE'; and read the "rows deleted" message, or use SQL%ROWCOUNT in PL/SQL. If the numbers match, run COMMIT; otherwise run ROLLBACK; and review the WHERE clause. You can also set a SAVEPOINT before the delete and ROLLBACK TO SAVEPOINT if you want to keep the rest of the transaction.