Skip to content

Instantly share code, notes, and snippets.

@alasarr
Last active August 31, 2017 14:42
Show Gist options
  • Save alasarr/2e93eac09cf69654bfa03901c9fb0c4d to your computer and use it in GitHub Desktop.
Save alasarr/2e93eac09cf69654bfa03901c9fb0c4d to your computer and use it in GitHub Desktop.
Useful commands PostgreSQL

PostgreSQL

Useful commands for PostgreSQL

Size

SELECT *, pg_size_pretty(total_bytes) AS total
    , pg_size_pretty(index_bytes) AS INDEX
    , pg_size_pretty(toast_bytes) AS toast
    , pg_size_pretty(table_bytes) AS TABLE
  FROM (
  SELECT *, total_bytes-index_bytes-COALESCE(toast_bytes,0) AS table_bytes FROM (
      SELECT c.oid,nspname AS table_schema, relname AS TABLE_NAME
              , c.reltuples AS row_estimate
              , pg_total_relation_size(c.oid) AS total_bytes
              , pg_indexes_size(c.oid) AS index_bytes
              , pg_total_relation_size(reltoastrelid) AS toast_bytes
          FROM pg_class c
          LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
          WHERE relkind = 'r'
  ) a
) a;

Indexes

select
    t.relname as table_name,
    i.relname as index_name,
    a.attname as column_name
from
    pg_class t,
    pg_class i,
    pg_index ix,
    pg_attribute a
where
    t.oid = ix.indrelid
    and i.oid = ix.indexrelid
    and a.attrelid = t.oid
    and a.attnum = ANY(ix.indkey)
    and t.relkind = 'r'
    and t.relname like 'test%'
order by
    t.relname,
    i.relname;
    

              , pg_total_relation_size(reltoastrelid) AS toast_bytes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment