List of foreign keys and the tables they reference in Oracle DB

database-metadata, metadata, oracle

Solution

The referenced primary key is described in the columns `r_owner` and `r_constraint_name` of the table `ALL_CONSTRAINTS`. This will give you the info you want:

SELECT a.table_name, a.column_name, a.constraint_name, c.owner, 
       -- referenced pk
       c.r_owner, c_pk.table_name r_table_name, c_pk.constraint_name r_pk
  FROM all_cons_columns a
  JOIN all_constraints c ON a.owner = c.owner
                        AND a.constraint_name = c.constraint_name
  JOIN all_constraints c_pk ON c.r_owner = c_pk.owner
                           AND c.r_constraint_name = c_pk.constraint_name
 WHERE c.constraint_type = 'R'
   AND a.table_name = :TableName

Problem

I'm trying to find a query which will return me a list of the foreign keys for a table and the tables and columns they reference. I am half way there with ``` SELECT a.table_name, a.column_name, a.constraint_name, c.owner FROM ALL_CONS_COLUMNS A, ALL_CONSTRAINTS C where A.CONSTRAINT_NAME = C.CONSTRAINT_NAME and a.table_name=:TableName and C.CONSTRAINT_TYPE = 'R' ``` But I still need to know which table and primary key are referenced by this key. How would I get that?

Original source

Related problems