Skip to content

Instantly share code, notes, and snippets.

@jitscar
Last active March 5, 2019 15:31
Show Gist options
  • Save jitscar/3524e3ece5a71b628007dba643ff1959 to your computer and use it in GitHub Desktop.
Save jitscar/3524e3ece5a71b628007dba643ff1959 to your computer and use it in GitHub Desktop.
Fast count of table rows in PostgreSql
create or replace function
count_rows(schema text, tablename text) returns integer
as
$body$
declare
result integer;
query varchar;
begin
query := 'SELECT reltuples::bigint AS estimate FROM pg_class WHERE oid = to_regclass(''' || schema || '.' || tablename || ''')';
execute query into result;
return result;
end;
$body$
language plpgsql;
select
table_schema,
table_name,
count_rows(table_schema, table_name)
from information_schema.tables
where
table_schema not in ('pg_catalog', 'information_schema', 'partman')
and table_type='BASE TABLE'
order by 3 desc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment