Sub topic 2
UPDATE with subqueries and correlated values
This chapter assumes you can write SELECT with WHERE, that you know COMMIT and ROLLBACK, and that the dept_demo and emp_demo tables from the earlier setup exist with their sample rows.
UPDATE with subqueries and correlated values
A subquery is a SELECT inside another statement. A correlated subquery refers to a column of the outer row, so it runs once for each row being updated.
UPDATE emp_demo e
SET e.salary = (SELECT ROUND(AVG(x.salary), 2)
FROM emp_demo x
WHERE x.dept_id = e.dept_id)
WHERE e.dept_id = 20;The inner query uses e.dept_id, so each employee in department 20 gets the average salary of that department. If the inner query returns no row, the salary becomes NULL.
Removing rows with DELETE
DELETE removes rows that match a WHERE condition. Without WHERE, every row in the table is removed.
DELETE FROM emp_demo e
WHERE e.status = 'INACTIVE'
AND EXISTS (SELECT 1 FROM emp_archive a WHERE a.emp_id = e.emp_id);The changes are not permanent until you run COMMIT. Run ROLLBACK to undo them.
DELETE versus TRUNCATE
TRUNCATE is a data definition language (DDL) command that empties a whole table. DDL commands commit automatically, so a TRUNCATE cannot be rolled back.
Getting changed values back with RETURNING INTO
The RETURNING INTO clause reads the new value of a changed row in the same statement. The target variable must receive exactly one row.
DECLARE
v_new_salary emp_demo.salary%TYPE;
BEGIN
UPDATE emp_demo
SET salary = salary + 100
WHERE emp_id = 1
RETURNING salary INTO v_new_salary;
DBMS_OUTPUT.PUT_LINE('New salary: ' || v_new_salary);
COMMIT;
END;
/Constraint violations and how to read the errors
Oracle reports a failed constraint with an ORA number. The most common ones are:
| Error | Meaning | Typical cause |
|---|---|---|
| ORA-00001 | Unique or primary key value already exists | Inserting a duplicate emp_id |
| ORA-02291 | Parent key not found | Inserting an emp_demo row with a dept_id that is not in dept_demo |
| ORA-02292 | Child rows exist | Deleting a dept_demo row that employees still reference |
| ORA-01400 | Cannot insert NULL | Leaving emp_name empty |
Running the following statement while employee 1 still belongs to department 20 raises ORA-02292:
DELETE FROM dept_demo WHERE dept_id = 20;Exercise
Exercise
Why does the correlated UPDATE in this chapter use the alias e in the inner query?
Show answer
The alias e identifies the outer row, so the inner query can match each employee's own deptid. Without the alias, the inner query would compare x.deptid to itself and update every row with the same average.