Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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