In this blog we will learn how to retrieve the list of Primary Key and Foreign Key for a particular table and for the whole database.

List of Primary Key and Foreign Key for Whole Database:

Query:

  1. SELECT
  2. DISTINCT
  3. Constraint_Name AS [Constraint],
  4. Table_Schema AS [Schema],
  5. Table_Name AS [TableName] FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
  6. GO

Output:


List of Primary Key and Foreign Key for a particular table:

Query:

  1. SELECT
  2. DISTINCT
  3. Constraint_Name AS [Constraint],
  4. Table_Schema AS [Schema],
  5. Table_Name AS [TableName] FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
  6. WHERE INFORMATION_SCHEMA.KEY_COLUMN_USAGE.TABLE_NAME='tblCompany_General_Info'
  7. GO

Output: