Skip to content

Instantly share code, notes, and snippets.

@frutik
Last active October 22, 2024 20:48
Show Gist options
  • Save frutik/3c8b562b7496c40e61e9b65421be85b5 to your computer and use it in GitHub Desktop.
Save frutik/3c8b562b7496c40e61e9b65421be85b5 to your computer and use it in GitHub Desktop.
useful postgresql queries - when your postgres went crazy
SELECT
c.relname AS index_name,
pg_size_pretty(pg_relation_size(c.oid)) AS index_size,
pg_size_pretty(pg_total_relation_size(c.oid) - pg_relation_size(c.oid)) AS index_bloat_size,
ROUND((pg_total_relation_size(c.oid) - pg_relation_size(c.oid)) / pg_relation_size(c.oid)::numeric * 100, 2) AS bloat_percentage
FROM
pg_class c
JOIN
pg_namespace n ON c.relnamespace = n.oid
WHERE
c.relkind = 'i' -- Only indexes
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
bloat_percentage DESC;
SELECT
indexrelid::regclass AS index_name,
indrelid::regclass AS table_name,
indisvalid
FROM
pg_index
WHERE
NOT indisvalid;
REINDEX INDEX index_name;
VACUUM FULL my_table_name;
SELECT
relname AS table_name,
n_dead_tup AS dead_tuples,
n_live_tup AS live_tuples,
pg_size_pretty(pg_total_relation_size(relid)) AS total_table_size
FROM
pg_stat_user_tables
ORDER BY
n_dead_tup DESC;
tradetracker=> SELECT
relname AS table_name,
n_dead_tup AS dead_tuples,
n_live_tup AS live_tuples,
pg_size_pretty(pg_total_relation_size(relid)) AS total_table_size
FROM
pg_stat_user_tables
ORDER BY
n_dead_tup DESC;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment