Skip to content

Instantly share code, notes, and snippets.

@fa-ahmad
Created February 11, 2022 12:38
Show Gist options
  • Save fa-ahmad/84313b26642955638671c4112c7be307 to your computer and use it in GitHub Desktop.
Save fa-ahmad/84313b26642955638671c4112c7be307 to your computer and use it in GitHub Desktop.
Test if a table has a primary key in Postgres

This returns the names and data types of all columns of the primary key for the tablename table:

FROM   pg_index i
JOIN   pg_attribute a ON a.attrelid = i.indrelid
                     AND a.attnum = ANY(i.indkey)
WHERE  i.indrelid = 'tablename'::regclass
AND    i.indisprimary;

Source

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment