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

Quick Guide to User-Defined Types in Oracle PL/SQL

A Twitter follower recently asked for more information on user-defined types in the PL/SQL language, and I figured the best way to answer is to offer up this blog post. PL/SQL is a strongly-typed language . Before you can work with a variable or constant, it must be declared with a type (yes, PL/SQL also supports lots of implicit conversions from one type to another, but still, everything must be declared with a type). PL/SQL offers a wide array of pre-defined data types , both in the language natively (such as VARCHAR2, PLS_INTEGER, BOOLEAN, etc.) and in a variety of supplied packages (e.g., the NUMBER_TABLE collection type in the DBMS_SQL package). Data types in PL/SQL can be scalars, such as strings and numbers, or composite (consisting of one or more scalars), such as record types, collection types and object types. You can't really declare your own "user-defined" scalars, though you can define subtypes  from those scalars, which can be very helpful from the p...

Three tips for getting started right with Oracle Database development

By "Oracle Database development", I mean, more or less, writing SQL and PL/SQL. I assume in this post that you have access to Oracle Database (which you can get via Cloud services, Docker , GitHub and OTN ). A. Use a powerful IDE, designed with database programming in mind. There are lots of editors out there, and many IDEs that work with Oracle Database. Sure, you could use Notepad, but OMG the productivity loss. You could also use a popular editor like Sublime, and then it get it working with Oracle. I suggest, however, that you  download  and install Oracle's own own, free, powerful IDE: SQL Developer . If you like to complement your graphical IDE with a command line tool (or OMG if you actually prefer  a command line tool to a graphical interface), you should also check out the relatively new and generating-lots-of-excitement SQLcl . B. Enable compile-time warnings and PL/Scope. The database has tons of useful functionality burned right into it, ready for...

Why DBMS_OUTPUT.PUT_LINE should not be in your application code

A database developer recently came across my  Bulletproof PL/SQL  presentation, which includes this slide. That first item in the list caught his attention: Never put calls to DBMS_OUTPUT.PUT_LINE in your application code. So he sent me an email asking why I would say that. Well, I suppose that is the problem with publishing slide decks. All the explanatory verbiage is missing. I suppose maybe I should do a video. :-) But in the meantime, allow me to explain. First, what does DBMS_OUTPUT.PUT_LINE do? It writes text out to a buffer, and when your current PL/SQL block terminates, the buffer is displayed on your screen. [Note: there can be more to it than that. For example, you could in your own code call DBMS_OUTPUT.GET_LINE(S) to get the contents of the buffer and do something with it, but I will keep things simple right now.] Second, if I am telling you not to use this built-in, how could text from your program be displayed on your screen? Not without a lot o...