Skip to content

Instantly share code, notes, and snippets.

@xivSolutions
Last active January 3, 2016 17:39
Show Gist options
  • Save xivSolutions/8497272 to your computer and use it in GitHub Desktop.
Save xivSolutions/8497272 to your computer and use it in GitHub Desktop.
Postgres Table Primary Keys: retrieves the primary keys for the user tables in the database (or filter with additional WHERE criteria). Includes composite primary key columns
SELECT
ctu.table_name table_name,
ctu.constraint_name key_name,
ccu.column_name
FROM information_schema.table_constraints tc
INNER JOIN information_schema.constraint_table_usage ctu
ON ctu.constraint_name = tc.constraint_name
INNER JOIN information_schema.constraint_column_usage ccu
ON ccu.constraint_name = ctu.constraint_name
WHERE tc.constraint_type = 'PRIMARY KEY'
AND tc.table_schema NOT IN ('pg_catalog', 'information_schema')
ORDER BY ctu, key_name, column_name;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment