aspose file tools*
The moose likes JDBC and the fly likes to find the primary key of a table Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "to find the primary key of a table" Watch "to find the primary key of a table" New topic
Author

to find the primary key of a table

Shobana Sukumar
Greenhorn

Joined: Nov 24, 2005
Posts: 17
which table can i refer to find the primary key of a table?i need a tablename to be refered other than the desc command as i hav to access the table name's primary key value from a code....
Balaguru Krish
Greenhorn

Joined: Sep 23, 2005
Posts: 9
Originally posted by Shobana Sukumar:
which table can i refer to find the primary key of a table?i need a tablename to be refered other than the desc command as i hav to access the table name's primary key value from a code....


In order to know the primary keys of a table,we have a table called USER_CONSTRAINTS.

Example :

select * from user_constraints where table_name = 'EMP' and constraint_type = 'P'
Balaguru Krish
Greenhorn

Joined: Sep 23, 2005
Posts: 9
In order to know the column name which is the primary key , we can use
USER_CONS_COLUMNS table.

Example:

SELECT COLUMN_NAME FROM USER_CONS_COLUMNS WHERE CONSTRAINT_NAME = 'EMP_PRIMARY_KEY'
stu derby
Ranch Hand

Joined: Dec 15, 2005
Posts: 333
Originally posted by Balaguru Krish:
In order to know the column name which is the primary key , we can use
USER_CONS_COLUMNS table.

Example:

SELECT COLUMN_NAME FROM USER_CONS_COLUMNS WHERE CONSTRAINT_NAME = 'EMP_PRIMARY_KEY'

That works on only a few databasees, maybe even only Oracle; it certainly doesn't work on many many other databases. Other databases have other DB-specific approaches; in general, you can use jva.sql.DatabaseMetaData methods to find such things.
saivenu madhav
Greenhorn

Joined: Nov 15, 2007
Posts: 29
Hi i am using DB2, i would like to know the primarykey of one table.

Could you please reply in SQL query format

The above didn't work for me..


ThanksInadvance
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: to find the primary key of a table