Skip to content

Instantly share code, notes, and snippets.

@le0pard
Created April 6, 2023 16:14
Show Gist options
  • Save le0pard/d41d92a1d174489aea1aae6d1bc2d2ca to your computer and use it in GitHub Desktop.
Save le0pard/d41d92a1d174489aea1aae6d1bc2d2ca to your computer and use it in GitHub Desktop.
Filtered Table Estimates
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;
SELECT count_estimate('SELECT 1 FROM items WHERE n < 1000');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment