Skip to content

Instantly share code, notes, and snippets.

@dronezzzko
Created November 1, 2022 10:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dronezzzko/76d76a5d59f2a876a7b8a665f12fce9a to your computer and use it in GitHub Desktop.
Save dronezzzko/76d76a5d59f2a876a7b8a665f12fce9a to your computer and use it in GitHub Desktop.
PostgreSQL Snippets

Usefull PostgreSQL Snippets.

Display the size of all tables

SELECT schemaname,
       C.relname AS "relation",
       pg_size_pretty (pg_relation_size(C.oid)) as table,
       pg_size_pretty (pg_total_relation_size (C.oid)-pg_relation_size(C.oid)) as index,
       pg_size_pretty (pg_total_relation_size (C.oid)) as table_index,
       n_live_tup
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C .relnamespace)
LEFT JOIN pg_stat_user_tables A ON C.relname = A.relname
WHERE nspname NOT IN ('pg_catalog', 'information_schema')
AND C.relkind <> 'i'
AND nspname !~ '^pg_toast'
ORDER BY pg_total_relation_size (C.oid) DESC

It will display detailed information about each table including its schema, size without indexes, size of indexes, total size of a table and indexes, as well as the number of rows in a table.

Indexes usage

SELECT relname,   
       100 * idx_scan / (seq_scan + idx_scan) percent_of_times_index_used,   
       n_live_tup rows_in_table 
FROM pg_stat_user_tables 
WHERE seq_scan + idx_scan > 0 
ORDER BY n_live_tup DESC;

It makes sense to add indexes if a table contains more than 10000 rows and has the low index usage.

Display inused indexes

SELECT schemaname, relname, indexrelname
FROM pg_stat_all_indexes
WHERE idx_scan = 0 and schemaname <> 'pg_toast' and  schemaname <> 'pg_catalog'

Running queries

SELECT pid, age(clock_timestamp(), query_start), usename, query, state
FROM pg_stat_activity
WHERE state != 'idle' AND query NOT ILIKE '%pg_stat_activity%'
ORDER BY query_start desc;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment