Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query to find Primary Key of a table?

How can I find which column is the primary key of a table by using a query?

like image 944
sky scraper Avatar asked Sep 11 '12 23:09

sky scraper


3 Answers

This is a duplicate question:

credit to Lukmdo for this answer:

It might be not advised but works just fine:

show index from TABLE where Key_name = 'PRIMARY' ; 

The solid way is to use information_schema:

SELECT k.COLUMN_NAME FROM information_schema.table_constraints t LEFT JOIN information_schema.key_column_usage k USING(constraint_name,table_schema,table_name) WHERE t.constraint_type='PRIMARY KEY'     AND t.table_schema=DATABASE()     AND t.table_name='owalog'; 
like image 144
ajon Avatar answered Dec 15 '22 03:12

ajon


For Oracle, you can look it up in the ALL_CONSTRAINTS table:

SELECT a.COLUMN_NAME
FROM all_cons_columns a INNER JOIN all_constraints c 
     ON a.constraint_name = c.constraint_name 
WHERE c.table_name = 'TBL'
  AND c.constraint_type = 'P';

DEMO.

For SQL Server, it was already answered here, and for MySQL check @ajon's answer.

like image 23
João Silva Avatar answered Dec 15 '22 02:12

João Silva


For MySQL:

SELECT GROUP_CONCAT(COLUMN_NAME), TABLE_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  TABLE_SCHEMA = '**database name**'
  AND CONSTRAINT_NAME='PRIMARY'
GROUP BY TABLE_NAME;

Warning a primary key with two columns will have them separated by a coma (,)

like image 42
Romuald Brunet Avatar answered Dec 15 '22 02:12

Romuald Brunet