oracle-databasedatabase-indexes

Oracle - Create an index only if not exists


Is there any way to create indexes in oracle only if they don't exists ?

Something like

CREATE INDEX IF NOT EXISTS ord_customer_ix
   ON orders (customer_id);

Solution

  • Add an index only if not exists:

    declare 
      already_exists  exception; 
      columns_indexed exception;
      pragma exception_init( already_exists, -955 ); 
      pragma exception_init(columns_indexed, -1408);
    begin 
      execute immediate 'create index ord_customer_ix on orders (customer_id)'; 
      dbms_output.put_line( 'created' ); 
    exception 
      when already_exists or columns_indexed then 
      dbms_output.put_line( 'skipped' );  
    end;