Retrieve primary key columns

From PostgreSQL wiki

Revision as of 14:12, 3 August 2009 by Tgl (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Snippets

Retrieve primary key columns

Works with PostgreSQL

Any version

Written in

SQL

Depends on

Nothing


This query returns the names and datatypes of the columns of the primary key for the TABLENAME table (note that the table name may be qualified if you need to include its schema name).

SELECT               
  pg_attribute.attname, 
  format_type(pg_attribute.atttypid, pg_attribute.atttypmod) 
FROM pg_index, pg_class, pg_attribute 
WHERE 
  pg_class.oid = 'TABLENAME'::regclass AND
  indrelid = pg_class.oid AND
  pg_attribute.attrelid = pg_class.oid AND 
  pg_attribute.attnum = any(pg_index.indkey)
  AND indisprimary

To see all indexed columns, remove the indisprimary restriction.

Personal tools