Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get query plan information from Postgres into JDBC

I want to capture the cost numbers from the query plan you get when you 'Explain' a query. Is there any way to get at this data inside of a Java ResultSet(or similar object)?

like image 709
user742626 Avatar asked Dec 02 '11 12:12

user742626


2 Answers

Sure, just run it as a regular statement:

Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("explain analyze select * from foo");
while (rs.next())
{
   System.out.println(rs.getString(1));
}
like image 185
a_horse_with_no_name Avatar answered Nov 05 '22 06:11

a_horse_with_no_name


In addition to the answer supplied above, I would suggest that you make use of the ability to format EXPLAIN plans as XML in PostgreSQL 9.0 and later.

EXPLAIN ( analyze on, format xml ) SELECT ...

This will give you explain output you can more easily work with in Java by manipulating it as XML.

like image 34
Josh Berkus Avatar answered Nov 05 '22 06:11

Josh Berkus