Last active
May 20, 2023 19:04
-
-
Save rponte/737c1e6a44ed425c2def to your computer and use it in GitHub Desktop.
Finding all tables without PK (Primary Key) or indexes on PostgreSQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
More information,
http://www.postgresonline.com/journal/archives/65-How-to-determine-which-tables-are-missing-indexes.html