views:

65

answers:

1

Hi all,

I am working on a database middleware application again. I want to retrieve the names of all key values of a given table.

For instance:

CREATE TABLE foo(A INTEGER PRIMARY KEY, B VARCHAR(255))

I want to ask Oracle for the primary keys of 'foo' and I want to get 'A'.

Is this possible in Oracle at all? I tried to search their documentation but wasn't able to find anything of value.

Thanks in advance

Kage

+2  A: 

Source:

SELECT       cols.table_name
             , cols.column_name
             , cols.position
             , cons.status
             , cons.owner
FROM         all_constraints cons
             , all_cons_columns cols
WHERE        cols.table_name = 'TABLE_NAME'
AND          cons.constraint_type = 'P'
AND          cons.constraint_name = cols.constraint_name
AND          cons.owner = cols.owner
ORDER BY     cols.table_name, cols.position;

Make sure to type the table_name in uppercase, as Oracle stores all table names in uppercase. Let's quickly explain the output from this query. table_name is the name of the table (stored in uppercase). column_name is the name of the column that is a part of the primary key. (also stored in uppercase) position is the position in the primary key. A primary key can contain more than one column, so understanding the order of the columns in the primary key is very important. status indicates whether the primary key is currently enabled or disabled. owner indicates the schema that owns the table.

ALL_CONSTRAINTS - here is a very good description of ALL_CONSTRAINTS

ALL_CONS_COLUMNS - here is a very good description of ALL_CONS_COLUMNS

Svetlozar Angelov
Wow, thanks. I think this is will help. Thanks Svetlozar :-). What would have been appropriate search terms for this on the Oracle documentation page? Constraints?
Kage
Primary Key is constraint, so yes - it is a good choice
Svetlozar Angelov
Thanks again :-).
Kage
Small comment - **Oracle does not store all of its table names in upper case**. It defaults all object names to upper case on creation, however if you wrap an object name in quotes [e.g. `create table "lower" (col_id number);`] then Oracle will keep the defined case [i.e. `select * from lower` will fail for the table created above, but `select * from "lower"` will succeed]. I've come across this for some auto-generation scripts when I couldn't work out why I couldn't see a table. You can also have some fun by adding spaces to the start and end of table names to mess with the DBAs minds!
Chris Gill
Evil >:). I've run across the uppercase "problem" before, but adding spaces is one layer up. Hrr. Thanks, Chris ^^
Kage