Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle get foreign keys

I'd like to get all foreign keys in a schema, like this. Let's say I have tables

users(id, username, pass, address_id)

and

addresses(id, text)

I have defined a FK on users-address_id to the id column in addresses. How should I write a query that would return me the FK columns like : users, address_id, addresses, id ?

Thanks!

SELECT *
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.R_OWNER = 'TRWBI'
like image 403
maephisto Avatar asked Apr 04 '11 08:04

maephisto


People also ask

How do you find the foreign key of a table in SQL Oracle?

First method is with table Constraints tab (select table and select Constraints tab). Tab lists table constraints - primary, unique and foreign keys and check constraints - all in one grid. Foreign keys are the ones with 'Foreign_Key' value in CONSTRAINT_TYPE column.

How do you find foreign keys?

To view the foreign key attributes of a relationship in a specific table. Open the Table Designer for the table containing the foreign key you want to view, right-click in the Table Designer, and choose Relationships from the shortcut menu.

Does Oracle index foreign keys?

Unlike other database systems, Oracle does not automatically create an index for the foreign key columns.

How do I get a foreign key in Toad?

In the Viewer go to Constraints tab. You can find now Foreign Keys in the list of constraints by looking at the Type of constraints. If you click on foreign key row at the bottom will appear FK's details like Columns and Properties with parent table.


1 Answers

found it!

this is what i was looking for, thanks everybody for helping.

SELECT a.table_name, a.column_name, uc.table_name, uc.column_name 
                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
                join USER_CONS_COLUMNS uc on uc.constraint_name = c.r_constraint_name
                WHERE  C.R_OWNER = 'myschema'
like image 58
maephisto Avatar answered Oct 20 '22 18:10

maephisto