Skip to content

Instantly share code, notes, and snippets.

@Jeetah
Last active November 21, 2023 10:25
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 Jeetah/d39da0d224111112e9a1f5afdaf62584 to your computer and use it in GitHub Desktop.
Save Jeetah/d39da0d224111112e9a1f5afdaf62584 to your computer and use it in GitHub Desktop.
Function for quick row count of arbitrary queries
CREATE FUNCTION count_estimate(query text) RETURNS integer AS $$
DECLARE
rec record;
rows integer;
BEGIN
FOR rec IN EXECUTE 'EXPLAIN ' || query LOOP
rows := substring(rec."QUERY PLAN" FROM ' rows=([[:digit:]]+)');
EXIT WHEN rows IS NOT NULL;
END LOOP;
RETURN rows;
END;
$$ LANGUAGE plpgsql VOLATILE STRICT;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment