Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 565
jsight Avatar asked Jul 31 '09 20:07

jsight


People also ask

Can Postgres view have primary key?

Views in Postgresql can't have primary keys. You can specify only unique, primary key, and foreign key constraints on views, and they are supported only in DISABLE NOVALIDATE mode.


2 Answers

The query above is very bad as it is really slow.

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 
like image 109
user3094383 Avatar answered Sep 22 '22 12:09

user3094383


To provide a straight bit of SQL, you can list the primary key columns and their types with:

SELECT c.column_name, c.data_type FROM information_schema.table_constraints tc  JOIN information_schema.constraint_column_usage AS ccu USING (constraint_schema, constraint_name)  JOIN information_schema.columns AS c ON c.table_schema = tc.constraint_schema   AND tc.table_name = c.table_name AND ccu.column_name = c.column_name WHERE constraint_type = 'PRIMARY KEY' and tc.table_name = 'mytable'; 
like image 43
Jamie Love Avatar answered Sep 19 '22 12:09

Jamie Love