Created
April 8, 2011 20:57
-
-
Save le0pard/910728 to your computer and use it in GitHub Desktop.
Count estimate
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 LANGUAGE plpgsql; | |
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; | |
Тестируем: | |
CREATE TABLE foo (r double precision); | |
INSERT INTO foo SELECT random() FROM generate_series(1, 1000); | |
ANALYZE foo; | |
# SELECT count(*) FROM foo WHERE r < 0.1; | |
count | |
------- | |
92 | |
(1 row) | |
# SELECT count_estimate('SELECT * FROM foo WHERE r < 0.1'); | |
count_estimate | |
---------------- | |
94 | |
(1 row) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment