Search code examples
sqloracleplsqloracle-sqldeveloperplsqldeveloper

Is it possible to add a primary key to a table from a PL/SQL block?


I Was Working in an exercise and this question popup to my mind is there a specific function in pl/SQL can add a primary key constraint or any kind of constraints in an existing table?


Solution

  • Possible? Yes, with dynamic SQL.

    SQL> create table test (id number);
    
    Table created.
    
    SQL> begin
      2    execute immediate 'alter table test add constraint pk_test primary key (id)';
      3  end;
      4  /
    
    PL/SQL procedure successfully completed.
    
    SQL> select constraint_name from user_constraints
      2  where table_name = 'TEST';
    
    CONSTRAINT_NAME
    ------------------------------
    PK_TEST
    
    SQL>