Skip to content

Instantly share code, notes, and snippets.

@sfcgeorge
Created September 14, 2018 09:02
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 sfcgeorge/98d06f88422f00a3ea8b83af73e48cd2 to your computer and use it in GitHub Desktop.
Save sfcgeorge/98d06f88422f00a3ea8b83af73e48cd2 to your computer and use it in GitHub Desktop.
Faster PostgreSQL COUNT function for large result sets by using query planner estimates.
CREATE FUNCTION count_estimate(query text) RETURNS integer AS $$
DECLARE
rec record;
rows integer;
row integer;
BEGIN
rows := 1;
FOR rec IN EXECUTE 'EXPLAIN ' || query LOOP
row := substring(rec."QUERY PLAN" FROM ' rows=([[:digit:]]+)')::integer;
IF (row != 0) THEN rows := rows * row; END IF;
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