Skip to main content

Don't Return Home Without the RETURNING Clause

[That title is, by the way, a fairly lame play on the American Express "Don't leave home without it." tagline. Sorry, can't help myself. SF]

The RETURNING clause allows you to retrieve values of columns (and expressions based on columns) that were modified by an insert, delete or update. Without RETURNING you would have to run a SELECT statement after the DML statement is completed to obtain the values of the changed columns. The RETURNING clause can return multiple rows of data, in which case you will use the RETURNING BULK COLLECT INTO form. You can also call aggregate functions in the RETURNING clause to obtain sums, counts and so on of columns in multiple rows changed by the DML statement.

I explore the feature below. You can execute the same code on LiveSQL.

Set Up Some Data

First, let's create some data with which to play.

CREATE TABLE parts
(
   part_number    INTEGER
 , part_name   VARCHAR2 (100)
)
/

BEGIN
   INSERT INTO parts VALUES (1, 'Mouse');
   INSERT INTO parts VALUES (100, 'Keyboard');
   INSERT INTO parts VALUES (500, 'Monitor');
   COMMIT;
END;
/

CREATE TABLE employees
(
   employee_id   INTEGER
 , last_name     VARCHAR2 (100)
 , salary        NUMBER
)
/

BEGIN
   INSERT INTO employees VALUES (100, 'Gutseriev', 1000);
   INSERT INTO employees VALUES (200, 'Ellison', 2000);
   INSERT INTO employees VALUES (400, 'Gates', 3000);
   INSERT INTO employees VALUES (500, 'Buffet', 4000);
   INSERT INTO employees VALUES (600, 'Slim', 5000);
   INSERT INTO employees VALUES (700, 'Arnault', 6000);
   COMMIT;
END;
/
The Basics of RETURNING

Suppose that after I update a part name, I need to find out which row was changed. Here's one way I could to this:
DECLARE
   l_num   PLS_INTEGER;
BEGIN
   UPDATE parts
      SET part_name = UPPER (part_name)
    WHERE part_name LIKE 'K%';

   SELECT part_number
     INTO l_num
     FROM parts
    WHERE part_name = UPPER (part_name);

   DBMS_OUTPUT.put_line (l_num);
END;
/
This solution issues the update and then in a separate SQL statement retrieves the part number of the row that was just modified - but only by reproducing the logic ("partname = UPPER (partname)") in the WHERE clause. This means that I have introduced repetition in my code, and also inefficiency (an extra context switch). This is logically equivalent to using the RETURNING clause, but definitely inferior to RETURNING. And keep in mind that if you use a SELECT after your DML statement to determine if the correct changes were made, you need to be very careful about how you specify the WHERE clause of your query to be sure that you identify the same rows that were (possibly) changed.

Now take a look at the next block.
DECLARE
   l_num   PLS_INTEGER;
BEGIN
      UPDATE parts
         SET part_name = UPPER (part_name)
       WHERE part_name LIKE 'K%'
   RETURNING part_number
        INTO l_num;

   DBMS_OUTPUT.put_line (l_num);
END;
/
Don't do an unnecessary SELECT simply to see/verify the impact of a non-query DML statement! Just add RETURNING to the statement and get information back from that single context switch between PL/SQL and SQL. Note that this RETURNING INTO only works because the WHERE clause identifies a single row for changing.

RETURNING with Multiple Rows Changed

Now suppose that I am (or could be) updating more than one row with my DML statement. For example, I will simply remove the WHERE clause from the above block. Let's see what happens when I execute it:
DECLARE
   l_num   PLS_INTEGER;
BEGIN
      UPDATE parts
         SET part_name = UPPER (part_name)
   RETURNING part_number
        INTO l_num;

   DBMS_OUTPUT.put_line (l_num);
END;
/
Oh no! I get an error:
ORA-01422: exact fetch returns more than requested number of rows
Exact fetch? Why is it talking about an exact fetch? Isn't this the same error I get when I do a SELECT-INTO that returns more than one row (that is, the TOO_MANY_ROWS exception)? Yes! And that's because RETURNING-INTO acts just like a SELECT-INTO. It expects just one row of information to be returned. So...if you are expecting more than one row, do the same thing you would do with SELECT-INTO: add BULK COLLECT!
DECLARE
   l_part_numbers   DBMS_SQL.number_table;
BEGIN
      UPDATE parts
         SET part_name = part_name || '1'
   RETURNING part_number
        BULK COLLECT INTO l_part_numbers;

   FOR indx IN 1 .. l_part_numbers.COUNT
   LOOP
      DBMS_OUTPUT.put_line (l_part_numbers (indx));
   END LOOP;
END;
/
RETURNING a Record's Worth

OK, so what if I want to return a whole record's worth of information? Can I use the ROW keyword?
DECLARE
   l_part   parts%ROWTYPE;
BEGIN
      UPDATE parts
         SET part_number = -1 * part_number
           , part_name = UPPER (part_name)
       WHERE part_number = 1
   RETURNING ROW      /* WILL NOT WORK */
        INTO l_part;

   DBMS_OUTPUT.put_line (l_part.part_name);
END;
/
No! You can "UPDATE table_name SET ROW =" to perform a record-level update, but you cannot use the ROW keyword in that same way in a RETURNING clause. Sorry, you must list each column, with compatible number and type to the fields of the "receiving" record, as you below.
DECLARE
   l_part   parts%ROWTYPE;
BEGIN
      UPDATE parts
         SET part_number = -1 * part_number
           , part_name = UPPER (part_name)
       WHERE part_number = 1
   RETURNING part_number, part_name
        INTO l_part;

   DBMS_OUTPUT.put_line (l_part.part_name);
END;
/
Aggregate Functions and RETURNING

What if I want to perform some operations on the data returned by the RETURNING? Well, fall back on first principles. From Tom Kyte: "Do it in SQL is possible." Suppose I need to get the total of salaries changed by my update statement. I could execute a SELECT after the UPDATE:
DECLARE
   l_total   INTEGER;
BEGIN
   UPDATE employees
      SET salary = salary * 2
    WHERE INSTR (last_name, 'e') > 0;

   SELECT SUM (salary)
     INTO l_total
     FROM employees
    WHERE INSTR (last_name, 'e') > 0;

   DBMS_OUTPUT.put_line (l_total);
END;
/
Not necessary! You can execute aggregate functions right inside the RETURNING clause!
DECLARE
   l_total   INTEGER;
BEGIN
      UPDATE employees
         SET salary = salary * 2
       WHERE INSTR (last_name, 'e') > 0
   RETURNING SUM (salary)
        INTO l_total;

   DBMS_OUTPUT.put_line (l_total);
END;
/

Comments

  1. Thanks Steven.
    ------------------
    1- a small misprint in paragraph 4 beginning with ( RETURNING with Multiple Rows Changed ) , you forgot to remove the where clause as you said , so it will work without exceptions
    ------------------
    2- you used the table of number type defined in DBMS_SQL package , is it equivalent in performance with our defined types in the block or package specification?
    ------------------
    3- Some readers might be interested , The RETURNING Clause will work also if we used a Collection of records as follows

    DECLARE
    type nt is table of parts%rowtype index by pls_integer;
    l_part_numbers nt;
    BEGIN
    UPDATE parts
    SET part_name = part_name || '1'
    RETURNING part_number,part_name
    BULK COLLECT INTO l_part_numbers;

    FOR indx IN 1 .. l_part_numbers.COUNT
    LOOP
    DBMS_OUTPUT.put_line (l_part_numbers (indx).part_name||' , '||l_part_numbers (indx).part_number);
    END LOOP;
    END;
    /
    ------------------
    4- The Aggregate Functions with RETURNING is wonderful
    ----------
    Sorry for taking long , thank you

    ReplyDelete
  2. Alsayed:

    #1. Thanks so much for pointing out the error. I have removed the WHERE clause.

    #2. There is no difference in performance. I was just a little bit lazy and decided to use a pre-defined collection. From a best practices standpoint, it is probably better to not use the DBMS_SQL types unless you are performing dynamic SQL. Otherwise it will be confusing: "Where's the dynamic SQL?"

    #3. Thanks for adding that information about populating a collection of records. Excellent point!

    ReplyDelete

Post a Comment

Popular posts from this blog

Running out of PGA memory with MULTISET ops? Watch out for DISTINCT!

A PL/SQL team inside Oracle made excellent use of nested tables and MULTISET operators in SQL, blending data in tables with procedurally-generated datasets (nested tables).  All was going well when they hit the dreaded: ORA-04030: out of process memory when trying to allocate 2032 bytes  They asked for my help.  The error occurred on this SELECT: SELECT  *    FROM header_tab trx    WHERE (generated_ntab1 SUBMULTISET OF trx.column_ntab)       AND ((trx.column_ntab MULTISET             EXCEPT DISTINCT generated_ntab2) IS EMPTY) The problem is clearly related to the use of those nested tables. Now, there was clearly sufficient PGA for the nested tables themselves. So the problem was in executing the MULTISET-related functionality. We talked for a bit about dropping the use of nested tables and instead doing everything in SQL, to avoid the PGA error. That would, however require lots of wo...

How to Pick the Limit for BULK COLLECT

This question rolled into my In Box today: In the case of using the LIMIT clause of BULK COLLECT, how do we decide what value to use for the limit? First I give the quick answer, then I provide support for that answer Quick Answer Start with 100. That's the default (and only) setting for cursor FOR loop optimizations. It offers a sweet spot of improved performance over row-by-row and not-too-much PGA memory consumption. Test to see if that's fast enough (likely will be for many cases). If not, try higher values until you reach the performance level you need - and you are not consuming too much PGA memory.  Don't hard-code the limit value: make it a parameter to your subprogram or a constant in a package specification. Don't put anything in the collection you don't need. [from Giulio Dottorini] Remember: each session that runs this code will use that amount of memory. Background When you use BULK COLLECT, you retrieve more than row with each fetch, ...

PL/SQL 101: Three ways to get error message/stack in PL/SQL

The PL/SQL Challenge quiz for 10 September - 16 September 2016 explored the different ways you can obtain the error message / stack in PL/SQL. Note: an error stack is a sequence of multiple error messages that can occur when an exception is propagated and re-raised through several layers of nested blocks. The three ways are: SQLERRM - The original, traditional and (oddly enough) not currently recommended function to get the current error message. Not recommended because the next two options avoid a problem which you are unlikely  to run into: the error stack will be truncated at 512 bytes, and you might lose some error information. DBMS_UTILITY.FORMAT_ERROR_STACK - Returns the error message / stack, and will not truncate your string like SQLERRM will. UTL_CALL_STACK API - Added in Oracle Database 12c, the UTL_CALL_STACK package offers a comprehensive API into the execution call stack, the error stack and the error backtrace.  Note: check out this LiveSQL script if...