Skip to content

Instantly share code, notes, and snippets.

@aspyct
Last active February 25, 2020 12:54
Show Gist options
  • Save aspyct/c9c020e28b34342d6163d3752c636bcc to your computer and use it in GitHub Desktop.
Save aspyct/c9c020e28b34342d6163d3752c636bcc to your computer and use it in GitHub Desktop.
Postgres database inspection queries
-- List big tables, materialized views and indices
SELECT relname AS objectname
, relkind AS objecttype
, reltuples AS entries
, pg_size_pretty(pg_table_size(oid)) AS size
FROM pg_class
WHERE relkind IN ('r', 'i', 'm')
ORDER BY pg_table_size(oid) DESC
LIMIT 10;
-- List tables and how often seqscans and indexscans are done
SELECT
relname AS TableName,
to_char(seq_scan, '999,999,999,999') AS TotalSeqScan,
to_char(idx_scan, '999,999,999,999') AS TotalIndexScan,
to_char(n_live_tup, '999,999,999,999') AS TableRows,
pg_size_pretty(pg_relation_size(relname :: regclass)) AS TableSize
FROM pg_stat_all_tables
WHERE schemaname = 'public'
AND 50 * seq_scan > idx_scan -- more than 2%
AND n_live_tup > 10000
AND pg_relation_size(relname :: regclass) > 5000000
ORDER BY relname ASC;
-- List grants per user
SELECT grantee
,table_catalog
,table_schema
,table_name
,string_agg(privilege_type, ', ' ORDER BY privilege_type) AS privileges
FROM information_schema.role_table_grants
WHERE grantee != 'postgres'
GROUP BY grantee, table_catalog, table_schema, table_name;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment