Oracle identity column and insert into select

Kombajn zbożowy picture Kombajn zbożowy · Jan 25, 2014 · Viewed 8.1k times · Source

Oracle 12 introduced nice feature (which should have been there long ago btw!) - identity columns. So here's a script:

CREATE TABLE test (
    a INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    b VARCHAR2(10)
);

-- Ok
INSERT INTO test (b) VALUES ('x');

-- Ok
INSERT INTO test (b)
SELECT 'y' FROM dual;

-- Fails
INSERT INTO test (b)
SELECT 'z' FROM dual UNION ALL SELECT 'zz' FROM DUAL;

First two inserts run without issues providing values for 'a' of 1 and 2. But the third one fails with ORA-01400: cannot insert NULL into ("DEV"."TEST"."A"). Why did this happen? A bug? Nothing like this is mentioned in the documentation part about identity column restrictions. Or am I just doing something wrong?

Answer

Maheswaran Ravisankar picture Maheswaran Ravisankar · Jan 26, 2014

I believe the below query works, i havent tested!

INSERT INTO Test (b)
SELECT * FROM
(
   SELECT 'z' FROM dual
   UNION ALL
   SELECT 'zz' FROM dual
);

Not sure, if it helps you any way.

For, GENERATED ALWAYS AS IDENTITY Oracle internally uses a Sequence only. And the options on general Sequence applies on this as well.

NEXTVAL is used to fetch the next available sequence, and obviously it is a pseudocolumn.

The below is from Oracle

You cannot use CURRVAL and NEXTVAL in the following constructs:

  • A subquery in a DELETE, SELECT, or UPDATE statement
  • A query of a view or of a materialized view
  • A SELECT statement with the DISTINCT operator
  • A SELECT statement with a GROUP BY clause or ORDER BY clause
  • A SELECT statement that is combined with another SELECT statement with the UNION, INTERSECT, or MINUS set operator
  • The WHERE clause of a SELECT statement
  • DEFAULT value of a column in a CREATE TABLE or ALTER TABLE statement
  • The condition of a CHECK constraint

The subquery and SET operations rule above should answer your Question.

And for the reason for NULL, when pseudocolumn(eg. NEXTVAL) is used with a SET operation or any other rules mentioned above, the output is NULL, as Oracle couldnt extract them in effect with combining multiple selects.

Let us see the below query,

select rownum from dual
union all 
select rownum from dual

the result is

ROWNUM
1
1