Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 868
Adelin Avatar asked Jun 14 '17 08:06

Adelin


People also ask

How do you create a table only if it does not exist in Oracle?

You can do it using PL/SQL Block. Check for table name in user_tables and if table does not exists then create it using Dynamic Query.

How do you check if index exists on a table in Oracle?

To show indexes for a particular table in Oracle use the following command: select index_name from dba_indexes where table_name='tablename'; When showing indexes, make sure that you are giving the right <tablename>.

What does != Mean in Oracle?

It (<>) is a function that is used to compare values in database table. != (Not equal to) functions the same as the <> (Not equal to) comparison operator.

What is create unique index in Oracle?

A unique index is a form of constraint. It asserts that you can only store a given value once in a table. When you create a primary key or unique constraint, Oracle Database will automatically create a unique index for you (assuming there isn't an index already available).


2 Answers

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;     
like image 88
user7294900 Avatar answered Sep 20 '22 05:09

user7294900


CREATE INDEX IN ORACLE IF NOT EXISTS.

ALTER SESSION SET CURRENT_SCHEMA = PROD_INTG;
DECLARE
  INDEX_EXISTS NUMBER;
BEGIN
  SELECT COUNT(1)
  INTO INDEX_EXISTS
  FROM ALL_INDEXES AI,
    ALL_IND_COLUMNS AIC
  WHERE AI.TABLE_OWNER = 'PROD_INTG'
        AND AI.TABLE_NAME = 'PROCESS_APPLICATION'
        AND AI.INDEX_NAME = AIC.INDEX_NAME
        AND AI.OWNER = AIC.INDEX_OWNER
        AND AIC.COLUMN_NAME IN ('PST_CODE', 'PIZ_TYPE_ID');
  IF (INDEX_EXISTS) > 0
  THEN
    DBMS_OUTPUT.PUT_LINE('INDEX EXISTS  :');
  ELSE
    EXECUTE IMMEDIATE 'ALTER SESSION SET CURRENT_SCHEMA = PROD_INTG';
    EXECUTE IMMEDIATE 'CREATE INDEX PROD_INTG.IDX_IQC_APPS_IN_PROC_PST_PIZ
      ON PROD_INTG.PROCESS_APPLICATION (PST_CODE, PIZ_TYPE_ID) PARALLEL 16';
    EXECUTE IMMEDIATE 'ALTER INDEX PROD_INTG.IDX_IQC_APPS_IN_PROC_PST_PIZ NOPARALLEL';
    DBMS_OUTPUT.PUT_LINE('INDEX created  :');
  END IF;
  EXCEPTION
  WHEN OTHERS THEN
  IF SQLCODE IN (-2275, -955, -02431, -01430, -01451, -01408)
  THEN
    NULL;
  ELSE
    RAISE;
  END IF;
END;
/
like image 25
Kumar Abhishek Avatar answered Sep 22 '22 05:09

Kumar Abhishek