Sub topic 11
Subqueries in INSERT, UPDATE and DELETE
This chapter assumes you can write single-row, multi-row and correlated subqueries, and that you know the EMPLOYEES and DEPARTMENTS tables of the Oracle HR sample schema. Everything you already know about subqueries still applies. This chapter covers the new places they can appear: the data source of an INSERT, the new value in an UPDATE, and the filter in an UPDATE or DELETE. It also covers the failure modes that matter once a statement changes data.
Practice on copies
Data-changing statements are hard to undo. Run the examples on copies of the HR tables, not on the originals.
CREATE TABLE emp_copy AS SELECT * FROM employees;
CREATE TABLE dept_copy AS SELECT * FROM departments;
CREATE TABLE emp_archive AS SELECT * FROM employees WHERE 1 = 0;WHERE 1 = 0 is never true, so emp_archive has the same columns as employees but no rows.
Rows are not permanent until you commit. If a statement does something unexpected, run ROLLBACK; and the changes disappear.
Where subqueries fit in DML
A data manipulation (DML) statement can use a subquery in these places:
| Statement | Place | Typical use |
|---|---|---|
| `INSERT` | The query that supplies the rows | Copy or archive rows |
| `INSERT` | A scalar subquery inside `VALUES` | Look up a value while inserting |
| `UPDATE` | `SET column = (subquery)` | Take the new value from another table |
| `UPDATE` | `SET (a, b) = (subquery)` | Take several values from one row |
| `UPDATE`, `DELETE` | `WHERE` clause | Choose which rows to change |
INSERT with a subquery
INSERT ... SELECT
The most common form replaces the VALUES list with a query. The column list of the query must match the column list of the target in number and compatible data types.
INSERT INTO emp_archive
SELECT *
FROM employees
WHERE hire_date < DATE '1990-01-01';The subquery can be as complex as you need, with joins, aggregates and its own subqueries. Do not put parentheses around it. Parentheses would turn it into a scalar subquery, which has different rules.
Scalar subqueries inside VALUES
When you insert one row, a scalar subquery can compute a value in place of a literal. It must return one column and at most one row.
INSERT INTO dept_copy (department_id, department_name, location_id)
VALUES ((SELECT MAX(department_id) + 10 FROM dept_copy),
'Analytics',
(SELECT location_id FROM locations WHERE city = 'Seattle'));Two edge cases can surprise you:
- If a subquery matches no row, it evaluates to
NULL. InsertingNULLinto aNOT NULLcolumn raises ORA-01400. - If it matches more than one row, you get ORA-01427 (single-row subquery returns more than one row).
In production code, computing MAX(...) + 10 this way is unsafe, because two sessions can read the same maximum. Use a sequence or an identity column for real keys.
Inserting through an inline view
The target of an INSERT can itself be a subquery. Adding WITH CHECK OPTION makes Oracle reject any row that the subquery's WHERE clause would not return.
INSERT INTO (SELECT department_id, department_name, location_id
FROM dept_copy
WHERE location_id = 1700
WITH CHECK OPTION)
VALUES (290, 'Compliance', 1700);Inserting 1800 as the location would fail with ORA-01402, because the new row would fall outside the view's WHERE clause.
UPDATE with subqueries
Subquery in SET
SET column = (subquery) takes a new value from another table. A correlated subquery looks up the value for each row being updated.
UPDATE emp_copy e
SET e.salary = (SELECT j.min_salary
FROM jobs j
WHERE j.job_id = e.job_id)
WHERE EXISTS (SELECT 1
FROM jobs j
WHERE j.job_id = e.job_id
AND e.salary < j.min_salary);This raises salaries that are below the minimum for the job. The WHERE EXISTS part is not optional decoration. Without it, the SET subquery runs for every row of emp_copy. Rows with no matching job get NULL as their salary, and rows with a matching job get their salary reset to the minimum, even if it was higher.
The SET subquery must return at most one row per target row. If jobs.job_id were not unique, you would get ORA-01427 and the whole statement would roll back.
Setting several columns at once
To set several columns from one row, put a column list on the left and a subquery returning the same number of columns on the right. This is usually better than writing two separate subqueries, because the lookup runs once instead of twice.
UPDATE dept_copy d
SET (manager_id, location_id) =
(SELECT o.manager_id, o.location_id
FROM departments o
WHERE o.department_id = d.department_id)
WHERE d.department_id IN (SELECT department_id FROM departments);This restores two columns of dept_copy from the original table. Only departments that exist in both tables are touched. The department added earlier, 280, has no match in departments, so the WHERE clause protects it from having its columns set to NULL.
Subquery in WHERE
This is the same as in a query. The statement from the spine, which gives a 5% raise to everyone paid below their own department's average, uses a correlated subquery:
UPDATE employees e
SET e.salary = e.salary * 1.05
WHERE e.salary < (SELECT AVG(i.salary)
FROM employees i
WHERE i.department_id = e.department_id);Oracle evaluates the WHERE clause against the data as it was when the statement began. The averages do not drift as rows are updated, so each employee is compared with the original average of their department. Run it against emp_copy first.
Employees whose department_id is NULL are never updated. The subquery's condition i.department_id = NULL is never true, so AVG returns NULL, and salary < NULL is unknown.
DELETE with subqueries
DELETE supports a subquery only in its WHERE clause. Both the IN and EXISTS forms work.
Archive, then delete
A typical pattern copies rows to an archive table, then removes them using that table as the filter:
DELETE FROM emp_copy
WHERE employee_id IN (SELECT employee_id FROM emp_archive);Delete rows with no parent
DELETE FROM emp_copy e
WHERE NOT EXISTS (SELECT 1
FROM departments d
WHERE d.department_id = e.department_id);This deletes employees whose department does not exist. It also deletes the employee with a NULL department. NOT EXISTS returns true when no matching row is found, and a NULL never matches. If that is not what you want, add AND e.department_id IS NOT NULL.
Remove duplicates
A subquery on ROWID keeps one row from each group of duplicates:
DELETE FROM emp_copy
WHERE ROWID NOT IN (SELECT MIN(ROWID)
FROM emp_copy
GROUP BY email);NOT IN is safe here because ROWID is never NULL. Compare it with the trap in the NOT IN chapter. The same trap applies to DELETE, and the damage is bigger. With a NULL in the subquery, a DELETE ... NOT IN deletes nothing. The reverse mistake, a condition that is true more often than you intended, deletes too much.
Common errors
| Error | Cause | Fix |
|---|---|---|
| ORA-01427 | A `SET` or `VALUES` subquery returned more than one row | Make the correlation unique, or use `MAX`, `MIN` or `FETCH FIRST 1 ROW ONLY` |
| ORA-01407 | A `SET` subquery returned no row, so the column became `NULL`, and the column is `NOT NULL` | Add `WHERE EXISTS`, or wrap the subquery in `NVL` |
| ORA-01400 | `NULL` inserted into a `NOT NULL` column | Check that the lookup subquery finds a row |
| ORA-01733 | The inline-view target is not updatable, for example because it uses `GROUP BY` | Update the base table and put the aggregate in a subquery |
| ORA-01402 | The row violates `WITH CHECK OPTION` | Insert values that satisfy the view's `WHERE` clause |
Exercises
Exercise
Write an UPDATE on empcopy that sets each employee's commissionpct to the highest commissionpct in their own department, but only for employees whose commissionpct is NULL and whose department has at least one non-NULL commission_pct. Explain why the WHERE clause is needed.
Show answer
UPDATE empcopy e SET e.commissionpct = (SELECT MAX(i.commissionpct) FROM empcopy i WHERE i.departmentid = e.departmentid) WHERE e.commissionpct IS NULL AND EXISTS (SELECT 1 FROM empcopy i WHERE i.departmentid = e.departmentid AND i.commission_pct IS NOT NULL); Without the WHERE clause, the SET subquery would run for every employee and overwrite existing commissions. In departments with no commission, it would produce NULL.
Exercise
This statement deletes no rows, although several employees do not manage anyone. Why? Rewrite it so it works. DELETE FROM empcopy WHERE employeeid NOT IN (SELECT managerid FROM empcopy);
Show answer
The top-level employee has a NULL managerid, so the subquery returns a NULL. For every row, NOT IN then evaluates to unknown, and a row is deleted only when the condition is true. Fix: use NOT EXISTS: DELETE FROM empcopy e WHERE NOT EXISTS (SELECT 1 FROM empcopy r WHERE r.managerid = e.employeeid); Adding WHERE managerid IS NOT NULL to the subquery also works.