List all primary keys (PKs) and their columns

The query below lists all the primary key constraints (PK) in the database along with their columns (one row per column).

See also: list of all primary keys (one row per PK).

Query

select schema_name(tab.schema_id) as [schema_name],
    pk.[name] as pk_name,
    ic.index_column_id as column_id,
    col.[name] as column_name,
    tab.[name] as table_name
from sys.tables as tab
    inner join sys.indexes as pk
        on tab.object_id = pk.object_id
        and pk.is_primary_key = 1
    inner join sys.index_columns as ic
        on ic.object_id = pk.object_id
        and ic.index_id = pk.index_id
    inner join sys.columns as col
        on pk.object_id = col.object_id
        and col.column_id = ic.column_id
order by schema_name(tab.schema_id),
    pk.[name],
    ic.index_column_id

Columns

  • schema_name - PK schema name
  • pk_name - PK constraint name
  • column_id - id of column in index (1, 2, ...). 2 or higher means key is composite (contains more than one column)
  • column_name - primary key column name
  • table_name - PK table name

Rows

  • One row represents one primary key column
  • Scope of rows: columns of all PK constraints in a database
  • Ordered by schema name, PK constraint name, column id

Sample results

You could also get this

Get this interactive HTML data dictionary in minutes with Dataedo.

See live HTML data dictionary sample

Try for free

Comments are only visible when the visitor has consented to statistics cookies. To see and add comments please accept statistics cookies.
0
There are no comments. Click here to write the first comment.