Search code examples
sqloracle-databasekeyconstraints

add data into primary key


this is my table.In this table i want to add a primary key column name "emp_id" as the first column .I don't know how to do it .So,can you please help me!

EMP_NAME             EMP_POS            SALARY           GENDER 
----------------- ----------------- --------------      ------ 
anand              worker             10000                 M      
balu               manager            50000                 M      
carl               manager            50000                 M      
riya               md                 60000                 F      
prabhu             owner              99999999              M      

Solution

  • The old way of doing this is a multi-step process:

    • add the column which will be the primary key
    • update the column
    • enforce the primary key.

    Something like this:

    create sequence t23_id;
    
    alter table t23 add id number;
    
    update t23 
    set id = t23_id.nextval
    ;
         
    alter table t23 add constraint t23_pk primary key (id);
    

    In 12c Oracle added Identity columns (like SQL Server auto-incrementing columns). This reduces the number of steps to two:

    alter table t23i add id number GENERATED ALWAYS AS IDENTITY primary key;
    
    alter table t23i add constraint t23i_pk primary key (id);
    

    Unfortunately it can't be done in one step. This ...

    alter table t23i add id number GENERATED ALWAYS AS IDENTITY primary key;  
    

    ...hurls ...

    ORA-01758: table must be empty to add mandatory (NOT NULL) column

    Livesql demo