Sub topic 5
UPDATE with subqueries and correlated values
A plain UPDATE ... SET column = literal WHERE ... only works when you already know the new values. Often the new value, or the set of rows to change, comes from another query. This chapter covers the three places a subquery can appear in an UPDATE, how correlated subqueries are evaluated, and the errors that appear when a subquery returns too many or too few rows.
This chapter assumes you can write a basic UPDATE ... WHERE, you know what a subquery is, and you understand the dept_demo, emp_demo, and emp_stage tables created earlier in this tutorial.
Where a subquery can appear
An UPDATE can use a subquery in three positions:
| Position | Purpose | Rows the subquery may return |
|---|---|---|
| `WHERE` clause | Choose which rows to change | Any number (with `IN`, `EXISTS`) |
| `SET col = (subquery)` | Compute a new value for one column | At most one row, one column |
| `SET (c1, c2) = (subquery)` | Compute new values for several columns | At most one row, matching column count |
The following sections cover each in turn.
A subquery in the WHERE clause
Use a subquery in WHERE when the rows to change are identified by data in another table. The Sales raise from earlier works this way:
UPDATE emp_demo
SET salary = salary * 1.05
WHERE dept_id IN (SELECT dept_id
FROM dept_demo
WHERE dept_name = 'Sales');The subquery runs and produces a list of department IDs. Oracle changes only the emp_demo rows whose dept_id is in that list. The subquery may return many rows because IN accepts a list.
EXISTS is the alternative. It tests whether a related row exists and ignores the values in it:
UPDATE emp_demo e
SET e.status = 'ACTIVE'
WHERE EXISTS (SELECT 1
FROM emp_stage s
WHERE s.emp_id = e.emp_id
AND s.status = 'ACTIVE');The inner query refers to e.emp_id, a column of the outer table. That reference makes it a correlated subquery, described below.
The NOT IN trap
NOT IN behaves unexpectedly when the subquery can return a NULL. Suppose you want to flag employees whose department is not in a list:
UPDATE emp_demo
SET status = 'REVIEW'
WHERE dept_id NOT IN (SELECT dept_id FROM emp_stage);If even one emp_stage.dept_id is NULL, the comparison dept_id NOT IN (..., NULL) is never true. The statement then updates zero rows and raises no error. Use NOT EXISTS, or add WHERE dept_id IS NOT NULL inside the subquery.
A scalar subquery in SET
A scalar subquery returns one row with one column. Used in SET, it supplies the new value:
UPDATE emp_stage s
SET s.salary = (SELECT e.salary
FROM emp_demo e
WHERE e.emp_id = s.emp_id)
WHERE EXISTS (SELECT 1
FROM emp_demo e
WHERE e.emp_id = s.emp_id);This statement is correlated: the inner query uses s.emp_id from the row being updated. Two rules control its behavior.
- If the subquery returns more than one row, Oracle raises ORA-01427 ("single-row subquery returns more than one row"). Here
emp_idis the primary key ofemp_demo, so the match is unique. - If the subquery returns no row, the result is
NULL, and Oracle assignsNULLto the column. It does not skip the row.
The second rule is the more dangerous one, because nothing signals it. The EXISTS condition in the WHERE clause above is a guard. Without it, every emp_stage row with no match in emp_demo would have its salary set to NULL. If the target column is NOT NULL, the statement fails with ORA-01407 instead.
How a correlated subquery is evaluated
A correlated subquery cannot run once and be done, because its result depends on the current outer row. Conceptually, Oracle works like this:
This is the logical model. The optimizer may rewrite the query, for example by turning it into a join, but the result must match this model. The model also explains the performance advice at the end of this chapter.
Aggregates and statement-level consistency
A correlated subquery can compute an aggregate over related rows. This statement raises every employee who earns less than their department average up to that average:
UPDATE emp_demo e
SET e.salary = (SELECT AVG(x.salary)
FROM emp_demo x
WHERE x.dept_id = e.dept_id)
WHERE e.salary < (SELECT AVG(x.salary)
FROM emp_demo x
WHERE x.dept_id = e.dept_id);The table emp_demo is both updated and queried inside the same statement. This is safe because Oracle provides statement-level read consistency. The subqueries see the data as it was when the statement began, so rows changed earlier in the same statement do not alter the averages used for later rows. The result does not depend on row order.
Note that NUMBER(8,2) rounds the average to two decimal places when it is assigned.
Updating several columns at once
When several columns come from the same source row, use a column list on the left of SET and one subquery on the right:
UPDATE emp_demo e
SET (e.salary, e.status) = (SELECT s.salary, s.status
FROM emp_stage s
WHERE s.emp_id = e.emp_id)
WHERE EXISTS (SELECT 1
FROM emp_stage s
WHERE s.emp_id = e.emp_id);This runs one subquery per row instead of two. The number and order of columns in the list must match the subquery's select list. A mismatch raises ORA-00913 ("too many values") or ORA-00947 ("not enough values").
The EXISTS clause repeats the join condition, which is a known cost of this pattern. The MERGE statement, covered in a later chapter, avoids the repetition.
Name resolution: always use aliases
Inside a subquery, Oracle resolves an unqualified column name against the subquery's own tables first, and only then against the outer statement. This causes a quiet bug:
-- Wrong: both sides refer to the inner emp_stage row
UPDATE emp_demo e
SET e.salary = (SELECT s.salary
FROM emp_stage s
WHERE emp_id = emp_id);Because emp_stage has an emp_id column, both unqualified names resolve to it. The condition is true for every row that has a non-null emp_id. The subquery then returns every row, and Oracle raises ORA-01427 if emp_stage has more than one. Give each table an alias and qualify every column, as the earlier examples do.
Updating through an inline view
A third form updates a join through an inline view:
UPDATE (SELECT e.salary AS old_sal, s.salary AS new_sal
FROM emp_demo e
JOIN emp_stage s ON s.emp_id = e.emp_id)
SET old_sal = new_sal;This works only if the table being changed is key-preserved. Each row of emp_demo must appear at most once in the join result, which Oracle can only guarantee when emp_stage.emp_id has a unique or primary key constraint. The emp_stage table was created with CREATE TABLE ... AS SELECT, which copies no constraints. This statement therefore fails with ORA-01779 ("cannot modify a column which maps to a non-key-preserved table"). The correlated forms above do not have this restriction, and MERGE is usually the better choice.
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
| ORA-01427 | Scalar subquery in `SET` returned more than one row | Make the join condition unique, or aggregate with `MAX`/`MIN` if that is the intent |
| ORA-01407 | Subquery returned no row, and the column is `NOT NULL` | Add a `WHERE EXISTS` guard |
| ORA-00913 / ORA-00947 | Column list and subquery select list differ in size | Match the counts |
| ORA-01779 | Inline view update on a non-key-preserved table | Add a unique constraint, or use `MERGE` |
| Zero rows updated, no error | `NOT IN` with a `NULL` in the subquery | Use `NOT EXISTS` |
Safe working habits
- Run the subquery as a
SELECTfirst, joined to the target, to see what the update will do. - Check the "rows updated" count the client reports. If it differs from what you expected, run
ROLLBACKinstead ofCOMMIT. - Index the columns used in the correlation, such as
emp_stage.emp_id. By the evaluation model above, the subquery may run once per candidate row, so an unindexed correlation column can lead to a full scan of the inner table for every row. - Remember that the update takes row locks on every row it changes. A large correlated update holds those locks until you commit or roll back.
Exercise
You run UPDATE empdemo e SET e.deptid = (SELECT d.deptid FROM deptdemo d WHERE d.deptname = 'Sales'). The statement succeeds, but every employee, including those who were in Engineering, is now in Sales. What caused this, and how would you change the statement so only employees in empstage are moved?
Show answer
The subquery is not correlated and the statement has no WHERE clause, so every row of empdemo receives the single value the subquery returns. Add a WHERE clause that limits the rows, for example WHERE EXISTS (SELECT 1 FROM empstage s WHERE s.empid = e.empid). Run ROLLBACK first to undo the unwanted change if you have not committed.
Exercise
A statement sets empstage.salary from a matching empdemo row using a scalar subquery in SET, with no WHERE clause. After it runs, some salaries in emp_stage are NULL. Why, and what is the fix?
Show answer
Rows in empstage that have no matching empid in empdemo make the subquery return no row, and Oracle assigns NULL in that case. Add WHERE EXISTS (SELECT 1 FROM empdemo e WHERE e.empid = s.empid) so only rows with a match are updated.