Hi all,
How to find the primary key of a table using query?
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Ashutosh Chaturvedi93 reputationPosted Jun 2, 2013, 10:34 PM EDT
SELECT column_name FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1 AND table_name = 'TableName'Kiresh Gangariya52 reputationPosted Jun 2, 2013, 10:39 PM EDT
Execute this Query
select
* from information_schema.Table_Constraints
where Table_Name = 'Table'
Sunny SharmaRank #223 · 11.1K reputationPosted Jun 2, 2013, 10:47 PM EDT
Use the query below, it will give you the Name of the primary key column name.
----------------------------------------------------------------------------
SELECT COL_NAME(a.object_id,b.column_id) as Column_Name from sys.indexes a
INNER JOIN sys.index_columns b
ON a.object_id=b.object_id
WHERE
a.is_primary_key=1 and OBJECT_NAME(a.object_id)='
------------------------------------------------------------------------------
*
Please accept this as answer if it helps :)
Thanks.
Jignesh TrivediRank #16 · 50.3K reputationPosted Jun 2, 2013, 11:18 PM EDT
try following Query..
SELECT kc.name KeyName, c.NAME AS ColumnName, c.object_id, o.name
FROM sys.key_constraints kc
INNER JOIN sys.index_columns ic ON kc.parent_object_id = ic.object_id
INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
INNER JOIN sys.objects o ON o.object_id = c.object_id
WHERE kc.type = 'PK' and o.name like '%table Name%'
hope this will help you.