Sub topic 4
Changing rows with UPDATE
What this chapter covers
UPDATE changes column values in rows that already exist. This chapter covers the syntax, how Oracle evaluates the SET list, what the row count means, the errors you will meet most often, and the locking behavior that follows from changing a row. Subqueries in UPDATE, RETURNING INTO, and MERGE have their own chapters.
It assumes you can write a SELECT with a WHERE clause and know what primary key, foreign key, and NOT NULL constraints do. The examples use the emp_demo and dept_demo tables from the setup script, with Ada (employee 1, department 20, salary 9000) and Grace (employee 2, department 10, salary 7000, INACTIVE).
The basic form
UPDATE table_name
SET column1 = expression1,
column2 = expression2
WHERE condition;The WHERE clause picks the rows. The SET list says what each picked row becomes. Without a WHERE clause, every row in the table is updated.
UPDATE emp_demo
SET salary = 9500
WHERE emp_id = 1;SQL*Plus and SQLcl answer with 1 row updated. The change is visible only to your session until you run COMMIT.
Expressions can use the current value
The right side of an assignment can refer to columns of the row being changed.
UPDATE emp_demo
SET salary = salary * 1.10,
status = 'ACTIVE'
WHERE emp_id = 2;Any column can appear on the right side, and any expression Oracle supports is allowed: arithmetic, functions, CASE, and concatenation.
UPDATE emp_demo
SET salary = CASE
WHEN salary < 8000 THEN salary * 1.10
ELSE salary * 1.03
END
WHERE status = 'ACTIVE';All right-hand sides see the old row
Oracle evaluates every expression in the SET list against the row as it was before the statement changed it. Assignment order does not matter.
UPDATE emp_demo
SET salary = salary + 100,
emp_name = emp_name || ' (was ' || salary || ')'
WHERE emp_id = 1;Here emp_name records the old salary, even though salary is also being changed. Run ROLLBACK; afterward if you do not want the new name. The same rule lets you swap two columns in one statement, which would be impossible if assignments ran one after another.
Setting NULL and DEFAULT
Assign NULL to clear a value. Use the DEFAULT keyword to apply the column's declared default.
UPDATE emp_demo
SET salary = NULL
WHERE emp_id = 2;
UPDATE emp_demo
SET status = DEFAULT
WHERE emp_id = 2;The second statement sets status back to 'ACTIVE', because that is the default in the table definition.
The WHERE clause follows the usual NULL rules. WHERE salary = NULL matches no rows, because the comparison is never true. Write WHERE salary IS NULL.
How a row gets changed
Two details in this flow matter in practice.
- A failed statement undoes only itself. If an
UPDATEtouches 500 rows and fails on row 400, Oracle reverses the statement's changes to all 500 rows. Earlier statements in your transaction stay pending. - Rows are locked as they are found. Other sessions can still read them (they see the old values), but they cannot change them until you end your transaction.
Counting what changed
Zero matching rows is not an error. The statement reports 0 rows updated. and carries on. A mistyped key in a WHERE clause therefore fails silently. In PL/SQL, SQL%ROWCOUNT gives the number of rows affected so that your code can check.
SET SERVEROUTPUT ON
BEGIN
UPDATE emp_demo
SET salary = salary * 1.03
WHERE dept_id = 20;
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT || ' row(s) updated');
ROLLBACK;
END;
/The count includes rows whose new values equal the old ones. Setting status = 'ACTIVE' on a row that is already ACTIVE still counts, still locks the row, and still generates undo and redo. Adding AND status <> 'ACTIVE' to the WHERE clause avoids that work. Be careful with nullable columns in such a filter, because <> never matches a NULL.
Errors you will meet
Constraints are checked when you run the statement, not at commit (unless a constraint is deferrable). The common failures:
| Error | Typical cause | Example |
|---|---|---|
| ORA-02291: integrity constraint violated - parent key not found | New foreign key value has no parent row | `SET dept_id = 99` when department 99 does not exist |
| ORA-02292: child record found | Changing a primary key value that child rows still reference | `UPDATE dept_demo SET dept_id = 11 WHERE dept_id = 10` while employees reference 10 |
| ORA-01407: cannot update to NULL | Assigning NULL to a `NOT NULL` column | `SET emp_name = NULL` |
| ORA-01438: value larger than specified precision | Number does not fit the column definition | `SET salary = 12345678` in a `NUMBER(8,2)` column |
| ORA-12899: value too large for column | String longer than the column allows | A 60-character name in `VARCHAR2(50)` |
| ORA-00001: unique constraint violated | New value duplicates an existing unique or primary key value | `SET emp_id = 2 WHERE emp_id = 1` |
Each message names the constraint or column involved. Read the name first. For ORA-02291 and ORA-02292, the constraint name tells you which foreign key fired, and USER_CONSTRAINTS shows the tables on each side.
UPDATE emp_demo
SET dept_id = 99
WHERE emp_id = 1;This raises ORA-02291, and Ada's row keeps its old department. Changing primary key values is legal but rarely wise, because every reference to the old value has to change with it.
Updating and locking
When your UPDATE changes a row, Oracle places a row-level lock on it. If a second session tries to update the same row before you finish, it waits.
Session B does not fail, and it does not hang forever. It continues once session A commits or rolls back. A common cause of a session that seems frozen is a colleague, or your own second window, with an uncommitted update on the row. Readers are never blocked: a SELECT in another session returns the last committed values.
You can keep a transaction short by committing as soon as a unit of work is complete. You can also undo part of a transaction with a savepoint, as covered in the transactions chapter.
Common mistakes
- Running
UPDATEwithoutWHERE, or with aWHEREthat is broader than intended. - Reading
0 rows updatedas success. Check that the count matches what you expected. - Assuming
SET a = b, b = acopiesbinto both columns. It swaps them, because Oracle uses the old values. - Using
= NULLinstead ofIS NULLin theWHEREclause. - Leaving a transaction open, which holds row locks and blocks other sessions.
- Putting a string literal in the wrong case.
'inactive'does not match'INACTIVE'.
Exercise
Ada (empid 1) has salary 9000. In one statement you run UPDATE empdemo SET salary = salary + 1000, empname = empname || ' ' || salary WHERE emp_id = 1; What are her new salary and name, and what does another session see before you commit?
Show answer
Her salary becomes 10000 and her name becomes 'Ada 9000', because every right-hand expression uses the row's values from before the statement. Another session sees the old committed values (salary 9000, name 'Ada') until you COMMIT, and it cannot update that row until you COMMIT or ROLLBACK.
Exercise
You run UPDATE empdemo SET status = 'TERMINATED' WHERE empid = 77; and Oracle prints "0 rows updated." No error appears. What happened, and how could PL/SQL code detect it?
Show answer
No row has emp_id 77, so the WHERE clause matched nothing. Matching zero rows is not an error. In PL/SQL, test SQL%ROWCOUNT immediately after the UPDATE and raise an error or log a message if it is 0.