How to find all primary keys from all tables in a database?


Below script will list all primary keys from all the tables from the database with corresponding table name and column name.

use [Database Name]
GO
SELECT ind.name AS IndexName,
OBJECT_NAME(icl.OBJECT_ID) AS TableName,
COL_NAME(icl.OBJECT_ID,icl.column_id) AS ColumnName
FROM sys.indexes AS ind
INNER JOIN sys.index_columns AS icl
ON ind.OBJECT_ID = icl.OBJECT_ID
AND ind.index_id = icl.index_id
WHERE ind.is_primary_key = 1

Comments