Sub topic 8
Getting changed values back with RETURNING INTO
This chapter assumes you can write basic INSERT, UPDATE, and DELETE statements, know what a transaction is, and have read simple PL/SQL blocks (DECLARE, BEGIN, END). It uses the emp_demo table from earlier chapters.
Why RETURNING INTO exists
After you change a row, you often need a value that the database computed or that depends on the change. Examples are a new salary after a raise, a key generated by a trigger or a default, or the data of a row you just deleted.
The naive approach is to run the DML statement and then a SELECT to read the result. That costs a second round trip. It also leaves a gap in which another session could change the row between your two statements, so you might read a value that your own statement did not write.
The RETURNING INTO clause removes both problems. It returns column values from the rows the statement just touched, as part of that same statement. No second query is needed.
Basic syntax
The clause goes at the end of an INSERT, UPDATE, or DELETE:
RETURNING expression [, expression ...] INTO variable [, variable ...]- Each expression is usually a column name, but it can be any expression over the affected row, such as
salary * 12. - Each variable receives one value. The variables must match the expressions in number and compatible type.
RETURNis a synonym forRETURNING. Both work.
The clause is available in PL/SQL, and also in client programs that bind output variables, such as OCI, JDBC, or Python drivers. This chapter focuses on PL/SQL.
A single-row UPDATE
The following block raises one employee's salary and reads the new value back.
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;
/Three points are worth noting:
%TYPEgives the variable the same data type as the column, so the block keeps working if the column definition changes.- The value returned is the value after the update. Oracle evaluates the
RETURNINGexpressions against the new row image. - The statement must affect exactly one row for a scalar variable to work. That condition is the source of the most common errors, covered below.
Run SET SERVEROUTPUT ON in SQL*Plus, SQLcl, or SQL Developer first, or you will not see the output.
What each statement returns
The meaning of "the changed value" depends on the statement.
| Statement | Values returned | Typical use |
|---|---|---|
| `INSERT ... VALUES` | The values of the new row, including defaults and values set by a `BEFORE INSERT` trigger | Read a generated key or a default such as `status` |
| `UPDATE` | The values after the change | Read a computed result such as a new salary |
| `DELETE` | The values of the row before it was removed | Log or display what was deleted |
For an INSERT, the clause is useful whenever a column is filled in for you. In the demo schema, status has a default of 'ACTIVE'. You can see what was stored without querying again:
DECLARE
v_status emp_demo.status%TYPE;
BEGIN
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary)
VALUES (3, 'Linus', 20, 8000)
RETURNING status INTO v_status;
DBMS_OUTPUT.PUT_LINE('Stored status: ' || v_status);
ROLLBACK;
END;
/The block prints Stored status: ACTIVE. The ROLLBACK undoes the demo row so later examples are unaffected.
For a DELETE, the returned values are the ones the row held just before deletion:
DECLARE
v_name emp_demo.emp_name%TYPE;
BEGIN
DELETE FROM emp_demo
WHERE emp_id = 2
RETURNING emp_name INTO v_name;
DBMS_OUTPUT.PUT_LINE('Deleted: ' || v_name);
ROLLBACK;
END;
/Returning several values at once
List several expressions and several variables in matching order:
DECLARE
v_name emp_demo.emp_name%TYPE;
v_salary emp_demo.salary%TYPE;
v_annual NUMBER;
BEGIN
UPDATE emp_demo
SET salary = salary * 1.10
WHERE emp_id = 1
RETURNING emp_name, salary, salary * 12
INTO v_name, v_salary, v_annual;
DBMS_OUTPUT.PUT_LINE(v_name || ': ' || v_salary || ' (' || v_annual || ' a year)');
ROLLBACK;
END;
/The third expression, salary * 12, shows that you can compute a value from the new row image during the statement.
What happens when the statement touches the wrong number of rows
A scalar INTO variable holds one value. The number of affected rows therefore decides whether the statement works.
- Zero rows. A single-row
UPDATEorDELETEthat matches nothing does not raise an error. Your variables are left unchanged, which usually meansNULL. CheckSQL%ROWCOUNTright after the statement if a missing row matters. - One row. This is the case scalar variables are designed for.
- Many rows. Oracle raises
ORA-01422: exact fetch returns more than requested number of rows. For a multi-row statement, use a collection andBULK COLLECT, shown next.
The following block guards against the zero-row case:
DECLARE
v_salary emp_demo.salary%TYPE;
BEGIN
UPDATE emp_demo
SET salary = salary + 100
WHERE emp_id = 999
RETURNING salary INTO v_salary;
IF SQL%ROWCOUNT = 0 THEN
DBMS_OUTPUT.PUT_LINE('No such employee');
ELSE
DBMS_OUTPUT.PUT_LINE('New salary: ' || v_salary);
END IF;
ROLLBACK;
END;
/Multi-row changes with BULK COLLECT
When a statement changes many rows, add BULK COLLECT so the values arrive in collections, one element per row:
DECLARE
TYPE t_id_tab IS TABLE OF emp_demo.emp_id%TYPE;
TYPE t_salary_tab IS TABLE OF emp_demo.salary%TYPE;
v_ids t_id_tab;
v_salaries t_salary_tab;
BEGIN
UPDATE emp_demo
SET salary = salary * 1.05
WHERE dept_id = 20
RETURNING emp_id, salary
BULK COLLECT INTO v_ids, v_salaries;
FOR i IN 1 .. v_ids.COUNT LOOP
DBMS_OUTPUT.PUT_LINE(v_ids(i) || ' -> ' || v_salaries(i));
END LOOP;
ROLLBACK;
END;
/With BULK COLLECT, zero affected rows is also safe: the collections come back empty and COUNT is 0. The order of elements is not guaranteed unless you know how the rows were processed, so do not treat the position as meaningful beyond matching one collection to another.
The whole collection sits in session memory. For a statement that changes millions of rows, this can use a lot of memory, so consider batching.
RETURNING and rollback
RETURNING INTO only reads the result of a change that is still part of your open transaction. It does not commit anything. If you ROLLBACK after the statement, the change is undone, but the values you captured stay in your variables. Treat them as a description of work that no longer exists.
This matters when you combine RETURNING with a savepoint. If you roll back to the savepoint, any value you captured after it describes a change that has been undone.
Common mistakes
- Using a scalar variable for a multi-row statement. This raises
ORA-01422. UseBULK COLLECT INTO, or narrow theWHEREclause to a primary key. - Mismatched counts. If the expressions and variables differ in number, compilation fails with
PLS-00394(wrong number of values in the INTO list). - Forgetting that the value is the new one. After an
UPDATE, the clause returns the changed value. If you need the old value, read it first with aSELECT ... FOR UPDATE, or capture it from aDELETE. - Expecting output without
SERVEROUTPUT. The block runs but prints nothing. - Using it with
MERGE. Oracle does not supportRETURNING INTOon aMERGEstatement. To get values from a merge, run theINSERTorUPDATEseparately, or query the table afterward.
Related tools
You can also capture changed values without PL/SQL by binding output variables from a client driver. The pattern is the same: the statement ends with RETURNING column INTO :bind_variable, and the driver declares :bind_variable as an output parameter.
A flow summary of the sequence:
Exercise
An UPDATE with WHERE dept_id = 20 matches three rows and ends with RETURNING salary INTO v_salary, where v_salary is a scalar NUMBER. What happens, and how do you fix it?
Show answer
Oracle raises ORA-01422 because three values cannot fit into one scalar variable. Fix it by declaring a collection type and using RETURNING salary BULK COLLECT INTO v_salaries, or by restricting the WHERE clause to one row, for example with emp_id = 1.
Exercise
You run DELETE FROM emp_demo WHERE emp_id = 2 RETURNING emp_name INTO v_name; and then ROLLBACK;. Does v_name still hold the name, and does the row still exist?
Show answer
Yes to both. The variable keeps the captured name, because rolling back does not clear PL/SQL variables. The row exists again, because the ROLLBACK undid the delete.