Wednesday, 26 May 2021

How to find primary key of a table in different databases?

Here are the queries to find primary key of a table in Postgres, SQL Server and Oracle. Replace the <TABLE_NAME> with the table name that we are interested in.


Postgre

SELECT a.attname, format_type(a.atttypid, a.atttypmod) AS data_type
FROM   pg_index i
JOIN   pg_attribute a ON a.attrelid = i.indrelid
                     AND a.attnum = ANY(i.indkey)
WHERE  i.indrelid = '<TABLE_NAME>'::regclass
AND    i.indisprimary;

SQL Server

select C.COLUMN_NAME FROM  
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS T  
    JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE C  
    ON C.CONSTRAINT_NAME=T.CONSTRAINT_NAME  
    WHERE  
    C.TABLE_NAME='<TABLE_NAME>'  
    and T.CONSTRAINT_TYPE='PRIMARY KEY'  

Oracle

SELECT COLUMN_NAME FROM all_cons_columns WHERE constraint_name = (
  SELECT constraint_name FROM user_constraints
  WHERE UPPER(table_name) = UPPER('<TABLE_NAME>') AND CONSTRAINT_TYPE = 'P')