環境: PostgresQL9.5
やりたいこと:PostgreSQLで、テーブルのPrimaryKeyを取得。
SQLは以下の通り
SELECT ccu.column_name as COLUMN_NAME
FROM information_schema.table_constraints tc
INNER JOIN information_schema.constraint_column_usage ccu
ON (tc.table_catalog=ccu.table_catalog
and tc.table_schema=ccu.table_schema
and tc.table_name=ccu.table_name
and tc.constraint_name=ccu.constraint_name
)
WHERE tc.table_catalog='データベース名'
and tc.table_schema='スキーマ名'
and tc.table_name='テーブル名'
and tc.constraint_type='PRIMARY KEY'
追記
スキーマが複数個ある場合、スキーマ名(publicなど)の条件も必要。
constraint_typeは、CHECK、FOREIGN KEY、PRIMARY KEY、UNIQUEのいずれかです。