Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you list the primary key of a SQL Server table?

Simple question, how do you list the primary key of a table with T-SQL? I know how to get indexes on a table, but can't remember how to get the PK.

like image 649
swilliams Avatar asked Oct 03 '22 11:10

swilliams


People also ask

How do I find the primary key in a table?

Primary Keys. The primary key of a table is the column whose values are different in every row. Because they are different, they make each row unique. If no one such column exists, the primary key is a composite of two or more columns whose values, taken together, are different in every row.

How do you check if a table has a primary key in SQL Server?

Show activity on this post. So SELECT TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA. TABLES WHERE TABLE_NAME IN ('TableA','TableB','TableC') EXCEPT SELECT TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA. TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' ?

How can we get list of primary key and foreign key of the table in SQL Server?

If we want to know the table's primary keys and foreign keys. We can simply use an “information_schema. key_column_usage” view, this view will return all of the table's foreign keys and primary keys.


2 Answers

SELECT Col.Column_Name from 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, 
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col 
WHERE 
    Col.Constraint_Name = Tab.Constraint_Name
    AND Col.Table_Name = Tab.Table_Name
    AND Constraint_Type = 'PRIMARY KEY'
    AND Col.Table_Name = '<your table name>'
like image 171
Guy Starbuck Avatar answered Oct 23 '22 12:10

Guy Starbuck


It's generally recommended practice now to use the sys.* views over INFORMATION_SCHEMA in SQL Server, so unless you're planning on migrating databases I would use those. Here's how you would do it with the sys.* views:

SELECT 
    c.name AS column_name,
    i.name AS index_name,
    c.is_identity
FROM sys.indexes i
    inner join sys.index_columns ic  ON i.object_id = ic.object_id AND i.index_id = ic.index_id
    inner join sys.columns c ON ic.object_id = c.object_id AND c.column_id = ic.column_id
WHERE i.is_primary_key = 1
    and i.object_ID = OBJECT_ID('<schema>.<tablename>');
like image 36
Dave Zych Avatar answered Oct 23 '22 11:10

Dave Zych