tags:

views:

148

answers:

2

Hello!

I was wondering how can I list the user tables name with its primary key name as the second column?

I'm doing half the job but I doesn't know what more to do.

select table_name from user_tables ORDER BY (table_name) ASC

Does anyone knows how?

Thank you

+1  A: 

Try joining USER_TABLES with USER_CONSTRAINTS.

In USER_CONSTRAINTS filter all rows with constraint_type equals to 'P' (primary key). There, you'll get index_name and index_owner values that you could join with USER_INDEXES and get column names from your PRIMARY KEY.

I wish I knew a more straightforward way of doing this... But I don't.

Good luck!

Pablo Santa Cruz
+3  A: 

This simple query gives you a list of tables along with the PK constraint name (but not the column name):

select     ut.table_name, uc.constraint_name
from       user_tables ut
left join  user_constraints uc
  on       ut.table_name = uc.table_name
  and      uc.constraint_type = 'P';

If you want the column name, remember that a PK can have multiple columns! We need to create a utility type first because of the collect() aggregate function:

create type ty_varchar_nt as table of varchar2(4000);

select     ut.table_name, uc.constraint_name, cast(collect (uic.column_name) as ty_varchar_nt) as pk_cols
from       user_tables ut
left join  user_constraints uc
  on       ut.table_name = uc.table_name
  and      uc.constraint_type = 'P'
left join  user_ind_columns uic
  on       uc.index_name = uic.index_name
group by ut.table_name, uc.constraint_name;

If you don't like the formatting of the nested tab, you can write a utility function which will take an NT as input and provide concatenated comma-delimited string as output. Just don't have the time to do it myself ;)

Andrew from NZSG