// SQL snippet

List primary keys and their columns

Primary keys drive joins, replication and ORM assumptions. This recipe lists every primary key in a schema together with the column or columns that form it.

Main statement
PostgreSQL
次もカバーします
SQL Server SQLite

The task

You are mapping an unfamiliar schema or checking that every key matches what the application expects, and you need the key columns for all tables in one result.

The snippet

Written for PostgreSQL. Versions for SQL Server and SQLite are under Variations.

PostgreSQL
SELECT tc.table_schema, tc.table_name, tc.constraint_name,
       kcu.column_name, kcu.ordinal_position
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu
  ON kcu.constraint_schema = tc.constraint_schema
 AND kcu.constraint_name = tc.constraint_name
 AND kcu.table_name = tc.table_name
WHERE tc.constraint_type = 'PRIMARY KEY'
  AND tc.table_schema = 'public'
ORDER BY tc.table_name, kcu.ordinal_position;

仕組み

table_constraints tells you which tables have a primary key; key_column_usage names the columns inside it. A composite key appears as one row per column, ordered by ordinal_position, so table_name plus ordinal_position reconstructs the key exactly. The join matches on schema, constraint name and table name. The table name looks redundant on PostgreSQL, but MySQL names every primary key PRIMARY, and without it each key would pair with the columns of every other table's key.

Variations

SQL Server

SQL Server
SELECT t.name AS table_name,
       kc.name AS constraint_name,
       c.name AS column_name,
       ic.key_ordinal
FROM sys.key_constraints kc
JOIN sys.tables t ON t.object_id = kc.parent_object_id
JOIN sys.index_columns ic ON ic.object_id = t.object_id AND ic.index_id = kc.unique_index_id
JOIN sys.columns c ON c.object_id = t.object_id AND c.column_id = ic.column_id
WHERE kc.type = 'PK'
ORDER BY t.name, ic.key_ordinal;

SQLite

SQLite
PRAGMA table_info(users);
-- pk column: 0 = not in the key, otherwise 1-based position in the key

Questions that come up

How do I spot composite primary keys in the output?

A composite key is the same constraint_name appearing more than once for one table. Sort by table and ordinal_position and the columns read in key order.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.