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
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.
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');
Indexes are stored in datafiles, that is also an database object.
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.
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