Search code examples
sqlpostgresqlplpgsql

How do I get the primary key(s) of a table from Postgres via plpgsql?


Given a table name, how do I extract a list of primary key columns and their datatypes from a plpgsql function?


Solution

  • I would recommend this official version:

    http://wiki.postgresql.org/wiki/Retrieve_primary_key_columns

    if schema is needed the query is as follows

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