Skip to content

Instantly share code, notes, and snippets.

@pallymore
Created August 9, 2015 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pallymore/06d1d1941593f219e825 to your computer and use it in GitHub Desktop.
Save pallymore/06d1d1941593f219e825 to your computer and use it in GitHub Desktop.
count rows for all tables in database
create or replace function
count_rows(schema text, tablename text) returns integer
as
$body$
declare
result integer;
query varchar;
begin
query := 'SELECT count(1) FROM ' || schema || '.' || tablename;
execute query into result;
return result;
end;
$body$
language plpgsql;
/*
We can invoke this function like any other postgres function with count_rows('users'). Adding our count_rows function to the original query will get us row counts for each table:
*/
select
table_schema,
table_name,
count_rows(table_schema, table_name)
from information_schema.tables
where
table_schema not in ('pg_catalog', 'information_schema')
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