Skip to content

Instantly share code, notes, and snippets.

@dncpax
Last active August 29, 2015 14:07
Show Gist options
  • Save dncpax/aa9445b79c8f8ea06150 to your computer and use it in GitHub Desktop.
Save dncpax/aa9445b79c8f8ea06150 to your computer and use it in GitHub Desktop.
#postgresql get accurate row count from all tables
-- Function to execute some sql text and return a scalar (eg number);
-- original from stackoverflow: https://stackoverflow.com/questions/2596670/how-do-you-find-the-row-count-for-all-your-tables-in-postgres
CREATE OR REPLACE FUNCTION dsql2(i_text text)
RETURNS integer AS
$BODY$
Declare
v_val int;
BEGIN
execute i_text into v_val;
return v_val;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION dsql2(text)
OWNER TO postgres;
COMMENT ON FUNCTION dsql2(text) IS 'Função para executar uma string sql e devolver um resultado escalar (eg número)';
-- sql command using function above; improved schema support that was not working
-- you can include and exclude schemas at will
SELECT table_schema,table_name, dsql2('select count(*) from "'||table_schema||'"."'||table_name||'"') as rownum
FROM information_schema.tables
WHERE table_type='BASE TABLE'
AND table_schema not in ('pg_catalog','information_schema')
ORDER BY table_schema,table_name;
@dncpax
Copy link
Author

dncpax commented Oct 14, 2014

Added support for upper case named tables

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment