CREATE OR REPLACE FUNCTION table_rows(tables text[])
RETURNS TABLE (table_name text, count bigint) AS $$
DECLARE
query text := '';
BEGIN
FOR i IN 1..array_length(tables, 1) LOOP
query := query || format('SELECT %L as table_name, count(*) from %s', tables[i], tables[i]);
IF i < array_length(tables, 1) THEN
query := query || ' union all ';
END IF;
END LOOP;
RETURN QUERY EXECUTE query;
END $$ LANGUAGE plpgsql;
-- Output
--
-- table_name | count
----------------------+----------
-- public.tags | 35100
-- public.diagnostics | 15833383
-- public.readings | 15830114
-- (3 rows)
--
Created
August 29, 2023 06:03
-
-
Save Harkishen-Singh/41a20d15996825e81832acdb6351331d to your computer and use it in GitHub Desktop.
PLPGSQL function that returns the number of rows of a given array of tables in a 'table_name', 'count' format
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment