SQL Queries - Common SQL Queries - How to retrieve the primary key of a table

Purpose of Query

The query retrieves the primary key of a table

Applicable CAST Version
Release
Yes/No
8.3.x (tick)
8.2.x (tick)
8.1.x (tick)
8.0.x (tick)
Applicable RDBMS
RDBMS
Yes/No
Oracle Server(error) 
Microsoft SQL Server (error) 
CSS2 (tick)
Query for CSS
Query result example

SELECT constraint_name, 
       table_name, 
       column_name, 
       ordinal_position 
FROM   information_schema.key_column_usage 
WHERE  constraint_schema = 'schema_name' 
       AND table_name = 'table_name'

You need to replace <table_name> with the name of the table, and <schema_name> with the name of the schema hosting the table

SELECT constraint_name, 
       table_name, 
       column_name, 
       ordinal_position 
FROM   information_schema.key_column_usage 
WHERE  constraint_schema = 'my_local_schema' 
       AND table_name = 'objdsc' 
Query result interpretation
 The query returns the primary key name and the table name, if no primary key exists on the table then the query returns no rows
Query for Oracle
Query result example

 

 
Query result interpretation
 
Query for SQL Server
Query result example

 

 
Query result interpretation

 

Notes/comments
 
Related Pages