Oracle 12c: How can I modify an existing primary key column to an identity column?

Samiul Al Hossaini picture Samiul Al Hossaini · Oct 6, 2015 · Viewed 16.1k times · Source

I have a table which contains a primary key column which is auto incremented from application. How can I modify the column to be an identity column in Oracle 12c?

A sample case is provided below-

create table tmp_identity (
   id number(100) primary key,
   value varchar2(100)
);

Say we populated the table with following data-

ID        VALUE
---------------
1         Sample 1
2         Sample 2
3         Sample 3

What we are planning to do is to turn this id column into an identity column which will-

  • Auto increment by 1
  • Start from 4

How can I do it? If it is not possible, then is there any work-around available for this?

Answer

a_horse_with_no_name picture a_horse_with_no_name · Oct 6, 2015

You can't turn an existing column it into a real identity column, but you can get a similar behaviour by using a sequence as the default for the column.

create sequence seq_tmp_identity_id
  start with 4
  increment by 1;

Then use:

alter table tmp_identity 
   modify id 
   default seq_tmp_identity_id.nextval;

to make the column use the sequence as a default value. If you want you can use default on null to overwrite an explicit null value supplied during insert (this is as close as you can get to an identity column)

If you want a real identity column you will need to drop the current id column and then re-add it as an identity column:

alter table tmp_identity drop column id;

alter table tmp_identity 
     add id number(38) 
     generated always as identity;

Note that you shouldn't add the start with 4 in this case so that all rows get a new unique number