Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Check for an Index in Oracle

I am writing a schema upgrade script for a product that depends on an Oracle database. In one area, I need to create an index on a table - if that index does not already exist. Is there an easy way to check for the existence of an index that I know the name of in an Oracle script?

It would be similar to this in SQL Server: IF NOT EXISTS (SELECT * FROM SYSINDEXES WHERE NAME = 'myIndex') // Then create my myIndex

like image 391
Doug Avatar asked Mar 12 '09 20:03

Doug


People also ask

How do you find the index of a table?

To see indexes for all tables within a specific schema you can use the STATISTICS table from INFORMATION_SCHEMA: SELECT DISTINCT TABLE_NAME, INDEX_NAME FROM INFORMATION_SCHEMA. STATISTICS WHERE TABLE_SCHEMA = 'your_schema'; Removing the where clause will show you all indexes in all schemas.

How do you find the unique index of a table in Oracle?

To list only the indexes on a table, query the all_indexes view: SELECT index_name, index_type, uniqueness FROM all_indexes WHERE owner = UPPER('&owner') AND table_name = UPPER('&table_name');

Where are indexes stored in Oracle?

Indexes are stored in datafiles, that is also an database object.


Video Answer


1 Answers

select count(*) from user_indexes where index_name = 'myIndex'

sqlplus won't support IF..., though, so you'll have to use anonymous PL/SQL blocks, which means EXECUTE IMMEDIATE to do DDL.

DECLARE
    i INTEGER;
BEGIN
    SELECT COUNT(*) INTO i FROM user_indexes WHERE index_name = 'MYINDEX';
    IF i = 0 THEN
        EXECUTE IMMEDIATE 'CREATE INDEX myIndex ...';
    END IF;
END;
/

Edit: as pointed out, Oracle stores unquoted object names in all uppercase.

like image 185
erikkallen Avatar answered Sep 24 '22 00:09

erikkallen