Created
April 9, 2020 18:01
-
-
Save arthuralvim/a5734a2e3947ba4c833b2b9ea813a247 to your computer and use it in GitHub Desktop.
SQL to count rows in all PostgreSQL tables.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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