Skip to Main Content

Breadcrumb

Question and Answer

Tom Kyte

Thanks for the question, Jen.

Asked: July 25, 2005 - 3:38 pm UTC

Last updated: July 26, 2005 - 5:18 pm UTC

Version: 9.2.0.5

Viewed 1000+ times

You Asked

Hello Tom,

I need a list of Tables that contain columns that reference other tables, but don't use physical constraints.

I tried to write a query of tables's PK columns that also column names in other tables, but are not correctly defined as FKs.

Can you help?

Thanks!




and Tom said...

Well, sort of "different" (I'd never assume that the names meant "join" myself)...

But I think this does it.

The big inline view pivots the primary key columns for all tables in a schema.

Then we join this to every other table in the schema (cartesian join...) and for each table -- see if that other table has all of those columns.

I'm not going to say "it'll be fast", but it should work ;)

The NO_MERGE may or may not be needed depending on an "optimizer" issue (if you get a group by error, you need it)

select p.table_name, c.table_name
from (
select /*+ NO_MERGE */ table_name,
max(decode(rn,1,column_name)) c1,
max(decode(rn,2,column_name)) c2,
max(decode(rn,3,column_name)) c3,
max(decode(rn,4,column_name)) c4,
max(decode(rn,5,column_name)) c5,
max(decode(rn,6,column_name)) c6,
max(decode(rn,7,column_name)) c7,
max(decode(rn,8,column_name)) c8,
count(*) cnt
from (
select a.table_name, b.column_name,
row_number() over (partition by a.table_name order by b.column_name) rn
from user_constraints a,
user_cons_columns b
where a.constraint_type = 'P'
and a.constraint_name= b.constraint_name
)
group by table_name
) P,
user_tables C
where p.table_name <> c.table_name
and (select count(*)
from user_tab_columns
where column_name in ( p.c1, p.c2, p.c3, p.c4, p.c5, p.c6, p.c7, p.c8 )
and table_name = C.table_name
) = p.cnt
/



Is this answer out of date? If it is, please let us know via a Comment

More to Explore

Analytics

Analytic SQL got you confused? Check out Connor McDonald's complete video course.