;

How to Check or Find the Column Name Which Is Primary Key Column in SQL Server


Tutorialsrack 22/02/2021 SQL SQL Server

In this article, you will learn how to check or find the column name which is the primary key column of a specific table in SQL Server.  There are various ways to find the primary key column in SQL server.

Here are some examples to check or find the Primary Key column name in SQL Server

Example 1: 

Example 1
SELECT 
    Col.Column_Name as 'PRIMARY KEY COLUMN' 
FROM
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, 
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col 
WHERE 
    Col.Constraint_Name = Tab.Constraint_Name
    AND Col.Table_Name = Tab.Table_Name
    AND Constraint_Type = 'PRIMARY KEY'
    AND Col.Table_Name = '';

Example 2: 

Example 2
SELECT 
     KU.table_name as TABLENAME
    ,column_name as 'PRIMARY KEY COLUMN'
FROM 
     INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC 
     INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU
    ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' 
    AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME 
    AND KU.table_name=''
ORDER BY 
     KU.TABLE_NAME,
     KU.ORDINAL_POSITION; 

Example 3:

Example 3
SELECT
	 COLUMN_NAME as 'PRIMARY KEY COLUMN' 
FROM 
         INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
WHERE 
	 TABLE_NAME = '';

I hope this article will help you to understand how to check or find the column name which is the primary key column of a specific table in SQL Server.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags