Skip to Main Content
  • Questions
  • Is feasible to add column as IDENTITY if the data in the table is too large.

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question.

Asked: January 07, 2025 - 1:13 pm UTC

Last updated: January 08, 2025 - 6:09 am UTC

Version: 12g

Viewed 100+ times

You Asked

Hi Senior,
My database is 12C PLSQL.
Is it possible to alter table and add IDENTITY for primary key, if the data in the table is beyond 200Crore or 2Billion data. As I am concerned about database crashing or Cache overflow.


Please guide me.


In the code I am creating identity in table "fac_fix_original"

ALTER TABLE fac_fix_original ADD (SEQ_ID NUMBER GENERATED ALWAYS AS IDENTITY(START WITH 1 INCREMENT BY 1));

and Connor said...

It is possible be aware that it can be expensive to do so. You can do it one hit, eg

SQL> CREATE Table test_alter
  2   (id INTEGER,
  3   name varchar2(10),
  4   PRIMARY KEY (id));

Table created.

SQL>
SQL> insert into test_alter
  2  select rownum*10,rownum*10
  3  from dual
  4  connect by level <= 10;

10 rows created.

SQL>
SQL>
SQL>  ALTER Table Test_alter  ADD new_id INTEGER GENERATED ALWAYS AS IDENTITY ;

Table altered.

SQL>
SQL> select * from test_alter;

        ID NAME           NEW_ID
---------- ---------- ----------
        10 10                  1
        20 20                  2
        30 30                  3
        40 40                  4
        50 50                  5
        60 60                  6
        70 70                  7
        80 80                  8
        90 90                  9
       100 100                10

10 rows selected.


but you could also consider a three step process

- alter table fac_fix_original add my_new_id integer generated by default on null as identity;
- update fac_fix_original set my_new_id = rownum;
- alter table fac_fix_original modify my_new_id generated always as identity start with limit value;

to separate out the expensive part (the second step) since we're updating every row. You'd need to do some experimenting to make sure that will complete in reasonable time, won't lock out users for too long, won't get too much row chaining etc.

If the expense is too large, then consider something like dbms_redefinition to minimise the outage and avoid the row chaining

More to Explore

DBMS_REDEFINITION

More on PL/SQL routine DBMS_REDEFINITION here