Created
September 14, 2018 09:02
-
-
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.
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
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