Tags

, , , , , ,

One of the frequently asked questions about sequences is “How to return the last sequence inserted?” Now, with the introduction of Identity column, I saw a similar question in Stack Overflow, Returning the value of identity column after insertion in Oracle

Whether Identity column or a typical sequence, the answer remains same.

RETURNING identity_id INTO variable_id;

Let’s look at a test case:

SQL> set serveroutput on
SQL> CREATE TABLE t
  2    (ID NUMBER GENERATED ALWAYS AS IDENTITY, text VARCHAR2(50)
  3    );

Table created.

SQL>
SQL> DECLARE
  2    var_id NUMBER;
  3  BEGIN
  4    INSERT INTO t
  5      (text
  6      ) VALUES
  7      ('test'
  8      ) RETURNING ID INTO var_id;
  9    DBMS_OUTPUT.PUT_LINE('ID returned is = '||var_id);
 10  END;
 11  /
ID returned is = 1

PL/SQL procedure successfully completed.

SQL>

SQL> select * from t;

        ID TEXT
---------- --------------------------------------------
         1 test

SQL>

Hope it helps!