Monday, May 18, 2015

How to find out which column are used in a referential integrity constraint

I had to generate a script for generating index on columns that used as foreign key.

Lets remind us that indexing foreing key columns is a good practice - see Tom Kyte's blog entry on this topic.

I knew that you can query the data dictionary to find out all the data in order to generate a script -  in particular the views USER_CONSTRAINTS and USER_CONS_COLUMNS.

SELECT UCC1.TABLE_NAME
, UCC1.COLUMN_NAME
, UCC1.CONSTRAINT_NAME
, UC.R_CONSTRAINT_NAME, UCC2.TABLE_NAME

FROM USER_CONSTRAINTS UC 
, USER_CONS_COLUMNS UCC1
, USER_CONS_COLUMNS UCC2
WHERE UC.CONSTRAINT_TYPE = 'R'
AND UCC1.CONSTRAINT_NAME = UC.CONSTRAINT_NAME
AND UCC2.CONSTRAINT_NAME = UC.R_CONSTRAINT_NAME