Need Help: Query to find primary key of table

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
rajsekar2u
Forum Commoner
Posts: 71
Joined: Thu Nov 20, 2008 4:23 am

Need Help: Query to find primary key of table

Post by rajsekar2u »

Hi friends

Is there any any to find column name to which primary key is set using mysql query...

Please Help me in this....

Thanks in advance
User avatar
viraj
Forum Newbie
Posts: 11
Joined: Wed Nov 19, 2008 7:52 am
Location: Colombo - Sri Lanka

Re: Need Help: Query to find primary key of table

Post by viraj »

Hi

Try this one

Code: Select all

 
SELECT COLUMN_NAME FROM KEY_COLUMN_USAGE WHERE TABLE_NAME = 'name_of_your_table' AND TABLE_SCHEMA = 'name_of_your_database' AND CONSTRAINT_NAME = 'Primary'
 
Viraj
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Need Help: Query to find primary key of table

Post by VladSun »

[sql]SELECT       *FROM     `information_schema`.`columns`WHERE     `information_schema`.`columns`.`table_schema` = 'my_database_name'     AND `information_schema`.`columns`.`table_name` = 'my_table_name'     AND `information_schema`.`columns`.`column_key` = 'PRI'[/sql]

Or you can use the output of:
[sql]DESCRIBE MY_TABLE_NAME;[/sql]

EDIT: Nice one viraj. I like yours more than mine ;)
There are 10 types of people in this world, those who understand binary and those who don't
Post Reply