Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save arckid/2f708ad1119252c7e9a2b8b73272012a to your computer and use it in GitHub Desktop.
Save arckid/2f708ad1119252c7e9a2b8b73272012a to your computer and use it in GitHub Desktop.
Finding all tables without PK (Primary Key) or indexes on PostgreSQL
SELECT
c.table_schema,
c.table_name,
c.table_type
FROM
information_schema.tables c
WHERE
c.table_schema NOT IN('information_schema', 'pg_catalog') AND c.table_type = 'BASE TABLE'
AND NOT EXISTS(SELECT i.tablename
FROM pg_catalog.pg_indexes i
WHERE i.schemaname = c.table_schema
AND i.tablename = c.table_name AND indexdef LIKE '%UNIQUE%')
AND
NOT EXISTS (SELECT cu.table_name
FROM information_schema.key_column_usage cu
WHERE cu.table_schema = c.table_schema AND
cu.table_name = c.table_name)
ORDER BY
c.table_schema, c.table_name;
SELECT
n.nspname AS "Schema",
c.relname AS "Table Name",
c.relhaspkey AS "Has PK"
FROM
pg_catalog.pg_class c
JOIN
pg_namespace n
ON (
c.relnamespace = n.oid
AND n.nspname NOT IN ('information_schema', 'pg_catalog')
AND c.relkind='r'
)
WHERE
c.relhaspkey = false
ORDER BY
c.relhaspkey, c.relname
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment