Home > Database > Mysql Tutorial > How to Retrieve a SQL Server Table's Primary Key?

How to Retrieve a SQL Server Table's Primary Key?

DDD
Release: 2025-01-13 11:36:43
Original
694 people have browsed it

How to Retrieve a SQL Server Table's Primary Key?

Discovering SQL Server Primary Keys

Knowing a table's primary key in SQL Server is vital for data integrity and inter-table relationships. This guide demonstrates a simple T-SQL method for identifying this crucial information.

Identifying Primary Key Columns

Use this query to retrieve the primary key column(s) of a specific table:

<code class="language-sql">SELECT Col.Column_Name
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab
JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
ON Col.Constraint_Name = Tab.Constraint_Name
WHERE Col.Constraint_Type = 'PRIMARY KEY'
AND Col.Table_Name = '<Your Table Name>';</code>
Copy after login

Here's a breakdown:

  • INFORMATION_SCHEMA.TABLE_CONSTRAINTS: This system table stores details on table constraints, including primary keys.
  • INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE: This table links constraints to their respective columns.
  • Col.Column_Name: This column returns the name(s) of the primary key column(s).
  • <Your Table Name>: Replace this placeholder with your target table's name.

Practical Example

To find the primary key of the Orders table, use the following query:

<code class="language-sql">SELECT Col.Column_Name
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab
JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
ON Col.Constraint_Name = Tab.Constraint_Name
WHERE Col.Constraint_Type = 'PRIMARY KEY'
AND Col.Table_Name = 'Orders';</code>
Copy after login

The query's output will list the name(s) of the primary key column(s), for example, OrderID or OrderNumber.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template