snippetsqlMinor
How to get row_count diagnostic after EXPLAIN ANALYZE in Postgres?
Viewed 0 times
row_countdiagnosticafteranalyzepostgresgethowexplain
Problem
I normally retrieve the
But if I want to run
Is there any built in way to do this other than parsing the string?
row_count of a query by doing GET DIAGNOSTICS row_count (normally within a function). But if I want to run
EXPLAIN ANALYZE on a query AND get row_count, I can't see any easy way to do that other than parsing the string output, because then GET DIAGNOSTICS row_count would return the number of rows in the EXPLAIN output. Is there any built in way to do this other than parsing the string?
Solution
Having come to this conclusion that there isn't an easy built-in way, here is my quick solution for this:
Create this function to capture the explain analyze plan result:
Run this to get the row count (only tested for select/create temp table statements - regex to the 2nd rows= number):
Create this function to capture the explain analyze plan result:
CREATE OR REPLACE FUNCTION get_explain_analyze(p_sql text)
RETURNS TABLE("QUERY PLAN" text)
AS
$BODY$
BEGIN
RETURN QUERY EXECUTE 'EXPLAIN ANALYZE '||p_sql;
END;
$BODY$
LANGUAGE plpgsql;Run this to get the row count (only tested for select/create temp table statements - regex to the 2nd rows= number):
SELECT substring("QUERY PLAN" from 'rows=.+rows=(\d+)') AS row_count
FROM get_explain_analyze('SELECT 1') -- query here
LIMIT 1;Code Snippets
CREATE OR REPLACE FUNCTION get_explain_analyze(p_sql text)
RETURNS TABLE("QUERY PLAN" text)
AS
$BODY$
BEGIN
RETURN QUERY EXECUTE 'EXPLAIN ANALYZE '||p_sql;
END;
$BODY$
LANGUAGE plpgsql;SELECT substring("QUERY PLAN" from 'rows=.+rows=(\d+)') AS row_count
FROM get_explain_analyze('SELECT 1') -- query here
LIMIT 1;Context
StackExchange Database Administrators Q#116834, answer score: 3
Revisions (0)
No revisions yet.