Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a List of all Primary Keys in a Database

Is this the best way to - Get a List of all Primary Keys in a Database - or is there something better?

SELECT
KCU.TABLE_NAME AS Table_Name,
KCU.CONSTRAINT_NAME AS Constraint_Name,
KCU.COLUMN_NAME AS COLUMN_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU
ON KCU.CONSTRAINT_SCHEMA = TC.CONSTRAINT_SCHEMA
AND KCU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME
AND KCU.TABLE_SCHEMA = TC.TABLE_SCHEMA
AND KCU.TABLE_NAME = TC.TABLE_NAME
WHERE
TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
ORDER BY
KCU.TABLE_SCHEMA, KCU.TABLE_NAME, KCU.CONSTRAINT_NAME
like image 444
Sam P Avatar asked May 24 '11 09:05

Sam P


People also ask

How do I view all the primary keys and foreign keys in my database?

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.

How many primary keys are in a database?

Primary keys must contain UNIQUE values, and cannot contain NULL values. A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).

How do I get a list of all tables in a database?

The easiest way to find all tables in SQL is to query the INFORMATION_SCHEMA views. You do this by specifying the information schema, then the “tables” view. Here's an example. SELECT table_name, table_schema, table_type FROM information_schema.


2 Answers

USE databasename; 

GO

SELECT i.name AS IndexName, OBJECT_NAME(ic.OBJECT_ID) AS TableName, 
       COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic
ON i.OBJECT_ID = ic.OBJECT_ID
AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1

This query will extract the all primary key constraints from the database... u just need to execute this query and type the database name in first line

like image 167
Kapil Avatar answered Oct 07 '22 18:10

Kapil


The following syntax give you all constraints in database in use.

select * from sys.key_constraints;
like image 38
Ashraf Sada Avatar answered Oct 07 '22 16:10

Ashraf Sada