Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 844
Samiul Al Hossaini Avatar asked Oct 06 '15 18:10

Samiul Al Hossaini


People also ask

How do I change an existing column to an identity in Oracle?

Sadly you can't alter an existing column to become an identity. This assigns a value from the sequence to all existing rows.

How do I add an identity column to an existing column?

You cannot alter a column to be an IDENTITY column. What you'll need to do is create a new column which is defined as an IDENTITY from the get-go, then drop the old column, and rename the new one to the old name.

Can we modify an existing table column to add the identity property?

You can add and drop the generated or identity property of a column in a table using the ALTER COLUMN clause in the ALTER TABLE statement.

Can primary key column be updated in Oracle?

Yes, there is a way to do the cascading update in Oracle, even within a transaction (which does not hold true for the option of enabling/disabling constraints). However, you'll have to implement it yourself. It can be done via before/after-row-update triggers.


1 Answers

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

like image 191
a_horse_with_no_name Avatar answered Nov 15 '22 08:11

a_horse_with_no_name