Skip to content

Instantly share code, notes, and snippets.

@arthuralvim
Created April 9, 2020 18: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 arthuralvim/a5734a2e3947ba4c833b2b9ea813a247 to your computer and use it in GitHub Desktop.
Save arthuralvim/a5734a2e3947ba4c833b2b9ea813a247 to your computer and use it in GitHub Desktop.
SQL to count rows in all PostgreSQL tables.
# credits for -> https://www.sisense.com/blog/exact-row-counts-for-every-database-table/
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;
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