Skip to content

SQL - PostgreSQL - Get all Primary Keys and Columns

Source: https://gist.github.com/abmmhasan/2f4024922eaea537cd1795223e38c18a

-- Get all primary keys & Columns
select kcu.table_schema,
       kcu.table_name,
       tco.constraint_name,
       kcu.ordinal_position as position,
       kcu.column_name as key_column
from information_schema.table_constraints tco
join information_schema.key_column_usage kcu 
     on kcu.constraint_name = tco.constraint_name
     and kcu.constraint_schema = tco.constraint_schema
     and kcu.constraint_name = tco.constraint_name
where tco.constraint_type = 'PRIMARY KEY'
order by kcu.table_schema,
         kcu.table_name,
         position;

Backlinks:

list from [[SQL - PostgreSQL - Get all Primary Keys and Columns]] AND -"Changelog"