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);
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.
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>.
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.
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).
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;
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;
/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With