How can I find which column is the primary key of a table by using a query?
For MSSQL: SELECT DISTINCT C.TABLE_NAME,C.COLUMN_NAME,C.DATA_TYPE FROM sys.indexes I INNER JOIN sys.index_columns IC ON I.OBJECT_ID = IC.OBJECT_ID AND I.INDEX_ID = IC.INDEX_ID INNER JOIN information_schema.columns C ON COL_NAME(IC.OBJECT_ID,IC.COLUMN_ID) = C.COLUMN_NAME WHERE I.IS_PRIMARY_KEY = 1
LEFT joining table_constraints seems to take more time on mine. i use Information_schema.COLUMNS
SELECT TABLE_SCHEMA , TABLE_NAME , COLUMN_NAME FROM Information_schema.Columns WHERE COLUMN_KEY = "PRI" AND TABLE_SCHEMA = DATABASE()
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 (,
)
The following query gives the list of all the primary keys in the given database.
SELECT DISTINCT TABLE_NAME ,column_name
FROM INFORMATION_SCHEMA.key_column_usage
WHERE TABLE_SCHEMA IN ('*your_db_name*');
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.
In mySQL
SHOW COLUMNS FROM `table_name`;
This show the details of the columns ie field, data-type, key etc.