Search code examples
javaoraclejdbcsql-execution-planexplain

JDBC Oracle - Fetch explain plan for query


Im wondering how I can fetch the explain plan using Java. Reason I need this is because we have a framework where special users can craft reports. These reports sometimes build huge queries in which we want to explain on the fly and store the cost of. This way we can analyse the high cost queries later on and optimize.

Example code which gives me illegal column exception:

ResultSet rs = null;
   try {
        oracle = ConnectionManager.getConnection(ConnectionManager.Test);
        pstmt = oracle.prepareStatement("begin execute immediate 
        'explain plan for SELECT   1 from Dual'; end;");
        rs = pstmt.executeQuery();
        while (rs.next()) {
            System.out.println(rs.getString(1));
        }

Solution

  • Use this:

    oracle = ConnectionManager.getConnection(ConnectionManager.Test);
    stmt = oracle.createStatement()
    stmt.execute("explain plan for SELECT   1 from Dual");
    rs = stmt.executeQuery("select plan_table_output from table(dbms_xplan.display())");
    while (rs.next()) 
    {
      System.out.println(rs.getString(1));
    }