I was wondering how can I add an identity column to existing oracle table? I am using oracle 11g. Suppose I have a table named DEGREE and I am going to add an identity column to that.
FYI table is not empty.
I was wondering how can I add an identity column to existing oracle table? I am using oracle 11g. Suppose I have a table named DEGREE and I am going to add an identity column to that.
FYI table is not empty.
add the column
alter table table_name add (id INTEGER);
create a sequence
table_name_id_seq
withstart with
clause, using number of rows in the table + 1 or another safe value(we don't want duplicate ids);lock the table (no inserts)
alter table table_name lock exclusive mode;
fill the column
update table_name set id = rownum; --or another logic
add a trigger to automaticaly put the id on insert using the sequence(you can find examples on internet, for example this answer)
When you'll fire the create trigger the lock will be released. (it automatically commits). Also, you may add unique constraint on the id column, it is best to do so.
From Oracle 12c you would use an identity column.
For example, say your table is called
demo
and has 3 columns and 100 rows:You could add an identity column using:
Then reset the internal sequence to match the data and prevent manual inserts:
and define it as the primary key:
This leaves the new column at the end of the column list, which shouldn’t normally matter (except for tables with a large number of columns and row chaining issues), but it looks odd when you describe the table. However, we can at least tidy up the dictionary order using the invisible/visible hack:
One thing you can't do (as of Oracle 18.0) is alter an existing column to make it into an identity column, so you have to either go through a process like the one above but copying the existing values and finally dropping the old column, or else define a new table explicitly with the identity column in place and copy the data across in a separate step. Otherwise you'll get:
You can not do it in one step. Instead,
Alter the table and add the column (without primary key constraint)
Fill the new column with data which will fulfill the primary key constraint (unique/not null), e.g. like
Alter the table and add the constraint to the column
After that is done, you can set up a
SEQUENCE
and aBEFORE INSERT
trigger to automatically set the id value for new records.