Home >Database >Mysql Tutorial >How to Find a SQL Server Table's Primary Key Using T-SQL?

How to Find a SQL Server Table's Primary Key Using T-SQL?

Linda Hamilton
Linda HamiltonOriginal
2025-01-13 11:16:44205browse

How to Find a SQL Server Table's Primary Key Using T-SQL?

Finding the Primary Key of a SQL Server Table Using T-SQL

This T-SQL query efficiently identifies the primary key column(s) for any given SQL Server table.

<code class="language-sql">SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME = '<your_table_name>'
  AND CONSTRAINT_NAME = (SELECT CONSTRAINT_NAME
                         FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
                         WHERE TABLE_NAME = '<your_table_name>'
                           AND CONSTRAINT_TYPE = 'PRIMARY KEY');</code>

The query uses INFORMATION_SCHEMA.KEY_COLUMN_USAGE to pinpoint columns associated with constraints and INFORMATION_SCHEMA.TABLE_CONSTRAINTS to filter for primary key constraints, ensuring only the primary key column names are returned for the specified table. Replace <your_table_name> with the actual name of your table.

The above is the detailed content of How to Find a SQL Server Table's Primary Key Using T-SQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn