parsed.org

Tips by tag: primary

Show Tables Without Primary Keys by cygnus on Jul 21, 2005 01:13 PM

Use the following query to show all tables without primary keys:

SELECT
  nspname AS schema,
  relname AS table
FROM pg_class
  LEFT JOIN pg_constraint ON
    pg_constraint.contype = 'p' AND
    conrelid = pg_class.oid
  JOIN pg_namespace ON
    pg_namespace.oid = pg_class.relnamespace
WHERE
  relkind = 'r' AND contype IS NULL;
internalskeysmetadatapostgresqlprimarysql

Given a table MYTABLE in namespace MYNAMESPACE, you can use this SQL to retrieve the primary key column name(s) for the table:

SELECT
  attname::text
FROM
  pg_attribute
JOIN
  pg_class ON pg_attribute.attrelid = pg_class.oid
JOIN
  pg_namespace ON pg_namespace.oid = pg_class.relnamespace
LEFT JOIN
  pg_constraint ON conrelid = pg_class.oid AND pg_constraint.contype = 'p'
WHERE
  pg_namespace.nspname = 'MYNAMESPACE' AND
  pg_class.relname = 'MYTABLE' AND
  pg_attribute.attnum = ANY (pg_constraint.conkey)
ORDER BY
  pg_attribute.attnum;
columnsinternalskeymetadatapostgresqlprimarysql
RSS