You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@phoenix.apache.org by ap...@apache.org on 2026/07/24 00:23:35 UTC

(phoenix) 02/27: PHOENIX-7881 Refactor UTs and ITs to assert on ExplainPlanAttributes (#2503)

This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch PHOENIX-7876-feature
in repository https://gitbox.apache.org/repos/asf/phoenix.git

commit dc5ef00e7c0a60bb6cc77bdedeadb780c7d09cfc
Author: Andrew Purtell <ap...@apache.org>
AuthorDate: Mon Jun 8 23:24:58 2026 -0700

    PHOENIX-7881 Refactor UTs and ITs to assert on ExplainPlanAttributes (#2503)
    
    Co-authored-by: Claude Opus 4.8[1m] <no...@anthropic.com>
---
 .../org/apache/phoenix/compile/DeleteCompiler.java |   4 +-
 .../phoenix/compile/ExplainPlanAttributes.java     | 564 ++++++++++------
 .../apache/phoenix/compile/GroupByCompiler.java    |   6 +
 .../phoenix/execute/ClientAggregatePlan.java       |  77 ++-
 .../org/apache/phoenix/execute/ClientScanPlan.java |  30 +-
 .../org/apache/phoenix/execute/HashJoinPlan.java   |  82 ++-
 .../apache/phoenix/execute/SortMergeJoinPlan.java  |  19 +-
 .../phoenix/execute/TupleProjectionPlan.java       |   4 +-
 .../phoenix/iterate/CursorResultIterator.java      |   4 +-
 .../iterate/DistinctAggregatingResultIterator.java |   4 +-
 .../org/apache/phoenix/iterate/ExplainTable.java   |  60 +-
 .../iterate/FilterAggregatingResultIterator.java   |   4 +-
 .../phoenix/iterate/FilterResultIterator.java      |   4 +-
 .../phoenix/iterate/LimitingResultIterator.java    |   4 +-
 .../iterate/MergeSortRowKeyResultIterator.java     |   1 +
 .../iterate/MergeSortTopNResultIterator.java       |   9 +-
 .../phoenix/iterate/OffsetResultIterator.java      |   4 +-
 .../phoenix/iterate/OrderedResultIterator.java     |   6 +-
 .../phoenix/iterate/SegmentResultIterator.java     |   1 +
 .../phoenix/iterate/SequenceResultIterator.java    |   6 +-
 .../org/apache/phoenix/end2end/AlterSessionIT.java |  17 +-
 .../apache/phoenix/end2end/BaseAggregateIT.java    |  76 +--
 .../end2end/BaseAggregateWithRegionMoves2IT.java   |  76 +--
 .../end2end/BaseAggregateWithRegionMovesIT.java    |  28 +-
 .../org/apache/phoenix/end2end/BaseOrderByIT.java  |  21 +-
 .../end2end/BaseOrderByWithRegionMovesIT.java      |  21 +-
 .../apache/phoenix/end2end/BasePermissionsIT.java  |  13 +-
 .../end2end/BaseTenantSpecificViewIndexIT.java     |  63 +-
 .../org/apache/phoenix/end2end/BaseViewIT.java     |  29 +-
 .../java/org/apache/phoenix/end2end/Bson4IT.java   |  16 +-
 .../java/org/apache/phoenix/end2end/Bson5IT.java   |  13 +-
 .../org/apache/phoenix/end2end/CDCQueryIT.java     |  15 +-
 .../apache/phoenix/end2end/CastAndCoerceIT.java    |  19 +-
 .../phoenix/end2end/ClientHashAggregateIT.java     |  21 +-
 .../phoenix/end2end/CostBasedDecisionIT.java       | 294 ++++----
 .../CountDistinctApproximateHyperLogLogIT.java     |  15 +-
 .../org/apache/phoenix/end2end/CreateTableIT.java  |  14 +-
 .../apache/phoenix/end2end/CsvBulkLoadToolIT.java  |   8 +-
 .../java/org/apache/phoenix/end2end/DeleteIT.java  |  64 +-
 .../org/apache/phoenix/end2end/DerivedTableIT.java |  96 +--
 .../phoenix/end2end/DistinctPrefixFilterIT.java    |  13 +-
 .../org/apache/phoenix/end2end/EmptyColumnIT.java  |  14 +-
 .../end2end/ExplainPlanWithStatsDisabledIT.java    | 110 +--
 .../phoenix/end2end/FlappingLocalIndexIT.java      |  83 +--
 .../java/org/apache/phoenix/end2end/InListIT.java  | 136 +---
 .../phoenix/end2end/IndexBuildTimestampIT.java     |  15 +-
 .../apache/phoenix/end2end/IndexExtendedIT.java    |  29 +-
 .../end2end/IndexToolForPartialBuildIT.java        |  25 +-
 .../org/apache/phoenix/end2end/IndexToolIT.java    | 110 +--
 .../java/org/apache/phoenix/end2end/KeyOnlyIT.java |  15 +-
 .../phoenix/end2end/LocalIndexSplitMergeIT.java    |  64 +-
 .../end2end/LogicalTableNameExtendedIT.java        |  16 +-
 .../apache/phoenix/end2end/LogicalTableNameIT.java |  15 +-
 .../phoenix/end2end/MaxLookbackExtendedIT.java     |   8 +-
 .../org/apache/phoenix/end2end/MaxLookbackIT.java  |  10 +-
 .../apache/phoenix/end2end/MultiCfQueryExecIT.java |   7 +-
 .../apache/phoenix/end2end/OnDuplicateKey2IT.java  |  11 +-
 .../apache/phoenix/end2end/OnDuplicateKeyIT.java   |  14 +-
 .../phoenix/end2end/ParallelStatsDisabledIT.java   |  12 -
 .../ParallelStatsDisabledWithRegionMovesIT.java    |  11 -
 .../end2end/ProjectArrayElemAfterHashJoinIT.java   |  20 +-
 .../org/apache/phoenix/end2end/QueryLoggerIT.java  |   4 +
 .../apache/phoenix/end2end/QueryWithLimitIT.java   |  15 +-
 .../apache/phoenix/end2end/QueryWithOffsetIT.java  |  36 +-
 .../phoenix/end2end/QueryWithTableSampleIT.java    |  55 +-
 .../apache/phoenix/end2end/RTrimFunctionIT.java    |   6 +-
 .../org/apache/phoenix/end2end/ReverseScanIT.java  |  30 +-
 .../phoenix/end2end/RowValueConstructorIT.java     |  14 +-
 .../end2end/RowValueConstructorOffsetIT.java       |  22 +-
 .../phoenix/end2end/SequenceBulkAllocationIT.java  |  14 +-
 .../org/apache/phoenix/end2end/SequenceIT.java     |  24 +-
 .../org/apache/phoenix/end2end/ServerPagingIT.java |  22 +-
 .../phoenix/end2end/SortMergeJoinMoreIT.java       |  70 +-
 .../apache/phoenix/end2end/SpillableGroupByIT.java |  13 +-
 .../phoenix/end2end/SubBinaryFunctionIT.java       |  12 +-
 .../org/apache/phoenix/end2end/TableTTLIT.java     |  14 +-
 .../phoenix/end2end/TenantSpecificTablesDDLIT.java |  15 +-
 .../phoenix/end2end/TenantSpecificTablesDMLIT.java |  11 +-
 .../phoenix/end2end/TenantSpecificViewIndexIT.java |  34 +-
 .../phoenix/end2end/UCFWithDisabledIndexIT.java    |   9 +-
 .../org/apache/phoenix/end2end/UnionAllIT.java     |  39 +-
 .../org/apache/phoenix/end2end/UpsertSelectIT.java |  11 +-
 .../end2end/UpsertSelectWithRegionMovesIT.java     |  11 +-
 .../phoenix/end2end/UserDefinedFunctionsIT.java    |  25 +-
 .../phoenix/end2end/VarBinaryEncoded2IT.java       |  11 +-
 .../it/java/org/apache/phoenix/end2end/ViewIT.java | 119 ++--
 .../org/apache/phoenix/end2end/ViewMetadataIT.java |  29 +-
 .../end2end/WhereOptimizerForArrayAnyIT.java       |   8 +-
 .../end2end/WhereOptimizerForArrayAnyITBase.java   |  29 +-
 .../WhereOptimizerForArrayAnyNullablePKIT.java     |  12 +-
 .../end2end/index/BaseImmutableIndexIT.java        |   9 +-
 .../apache/phoenix/end2end/index/BaseIndexIT.java  | 217 ++----
 .../end2end/index/BaseIndexWithRegionMovesIT.java  | 200 ++----
 .../index/ChildViewsUseParentViewIndexIT.java      |  46 +-
 .../end2end/index/GlobalIndexCheckerIT.java        | 119 ++--
 .../index/GlobalIndexCheckerWithRegionMovesIT.java |  74 +-
 .../end2end/index/GlobalIndexOptimizationIT.java   | 155 ++---
 .../end2end/index/ImmutableIndexWithStatsIT.java   |  12 +-
 .../phoenix/end2end/index/IndexMaintenanceIT.java  |  39 +-
 .../apache/phoenix/end2end/index/IndexUsageIT.java | 249 +++----
 .../apache/phoenix/end2end/index/LocalIndexIT.java | 282 +++-----
 .../end2end/index/MutableIndexFailureIT.java       |  58 +-
 .../phoenix/end2end/index/MutableIndexIT.java      |  86 +--
 .../phoenix/end2end/index/PartialIndexIT.java      |  83 +--
 .../end2end/index/PartialSystemCatalogIndexIT.java |  50 +-
 .../phoenix/end2end/index/SaltedIndexIT.java       |  89 +--
 .../phoenix/end2end/index/SingleCellIndexIT.java   |  36 +-
 .../UncoveredGlobalIndexRegionScanner2IT.java      |  11 +-
 .../index/UncoveredGlobalIndexRegionScannerIT.java |  25 +-
 .../apache/phoenix/end2end/index/ViewIndexIT.java  |  26 +-
 .../end2end/index/txn/TxWriteFailureIT.java        |  15 +-
 .../apache/phoenix/end2end/join/BaseJoinIT.java    |  36 +-
 .../end2end/join/HashJoinGlobalIndexIT.java        | 574 ++++++++--------
 .../apache/phoenix/end2end/join/HashJoinIT.java    | 391 +++++++++--
 .../phoenix/end2end/join/HashJoinLocalIndexIT.java | 747 +++++++++++----------
 .../phoenix/end2end/join/HashJoinMoreIT.java       | 117 ++--
 .../phoenix/end2end/join/HashJoinNoIndexIT.java    | 564 ++++++++--------
 .../end2end/join/SortMergeJoinGlobalIndexIT.java   |  86 ++-
 .../phoenix/end2end/join/SortMergeJoinIT.java      |  63 +-
 .../end2end/join/SortMergeJoinLocalIndexIT.java    | 106 ++-
 .../end2end/join/SortMergeJoinNoIndexIT.java       |  68 +-
 .../end2end/join/SortMergeJoinNoSpoolingIT.java    |   4 +-
 .../apache/phoenix/end2end/join/SubqueryIT.java    | 251 ++-----
 .../end2end/join/SubqueryUsingSortMergeJoinIT.java | 198 +-----
 .../phoenix/end2end/json/JsonFunctionsIT.java      |  18 +-
 .../phoenix/end2end/salted/BaseSaltedTableIT.java  |   8 +-
 .../phoenix/end2end/salted/SaltedTableIT.java      |  12 +-
 .../phoenix/monitoring/HBaseScanMetricsIT.java     |  17 +-
 .../org/apache/phoenix/rpc/PhoenixClientRpcIT.java |  10 +-
 .../org/apache/phoenix/rpc/PhoenixServerRpcIT.java |  10 +-
 .../phoenix/schema/ConditionalTTLExpressionIT.java |  11 +-
 .../phoenix/schema/stats/BaseStatsCollectorIT.java | 103 +--
 .../phoenix/compile/JoinQueryCompilerTest.java     |  25 +-
 .../apache/phoenix/compile/QueryCompilerTest.java  | 177 ++---
 .../apache/phoenix/compile/QueryOptimizerTest.java |  11 +-
 .../compile/StatementHintsCompilationTest.java     |  28 +-
 .../TenantSpecificViewIndexCompileTest.java        | 127 ++--
 .../apache/phoenix/query/ExplainPlanTextTest.java  |  67 --
 .../org/apache/phoenix/query/QueryPlanTest.java    | 238 ++-----
 .../query/explain/ExplainJsonNormalizer.java       |  21 +-
 ...CompatibilityTest.java => ExplainPlanTest.java} | 342 ++++++++--
 .../phoenix/query/explain/ExplainPlanTestUtil.java | 475 +++++++++++++
 .../query/explain/ExplainTextNormalizer.java       |  10 +-
 143 files changed, 4819 insertions(+), 5241 deletions(-)

diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java b/phoenix-core-client/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java
index 3d1e9ffdcd..05316748b9 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java
@@ -793,7 +793,9 @@ public class DeleteCompiler {
 
     @Override
     public ExplainPlan getExplainPlan() throws SQLException {
-      return new ExplainPlan(Collections.singletonList("DELETE SINGLE ROW"));
+      ExplainPlanAttributes attributes =
+        new ExplainPlanAttributesBuilder().setAbstractExplainPlan("DELETE SINGLE ROW").build();
+      return new ExplainPlan(Collections.singletonList("DELETE SINGLE ROW"), attributes);
     }
 
     @Override
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/compile/ExplainPlanAttributes.java b/phoenix-core-client/src/main/java/org/apache/phoenix/compile/ExplainPlanAttributes.java
index f4ed63f245..74cd983332 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/compile/ExplainPlanAttributes.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/compile/ExplainPlanAttributes.java
@@ -19,6 +19,8 @@ package org.apache.phoenix.compile;
 
 import com.fasterxml.jackson.annotation.JsonPropertyOrder;
 import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
 import java.util.Set;
 import org.apache.hadoop.hbase.HRegionLocation;
@@ -32,149 +34,187 @@ import org.apache.phoenix.schema.PColumn;
  * against. This also makes attribute retrieval easier as an API rather than retrieving list of
  * Strings containing entire plan.
  */
-@JsonPropertyOrder({ "abstractExplainPlan", "splitsChunk", "estimatedRows", "estimatedSizeInBytes",
-  "iteratorTypeAndScanSize", "samplingRate", "useRoundRobinIterator", "hexStringRVCOffset",
-  "consistency", "hint", "serverSortedBy", "explainScanType", "tableName", "keyRanges",
-  "scanTimeRangeMin", "scanTimeRangeMax", "serverWhereFilter", "serverDistinctFilter",
-  "serverOffset", "serverRowLimit", "serverArrayElementProjection", "serverAggregate",
-  "clientFilterBy", "clientAggregate", "clientSortedBy", "clientAfterAggregate",
-  "clientDistinctFilter", "clientOffset", "clientRowLimit", "clientSequenceCount",
-  "clientCursorName", "clientSortAlgo", "rhsJoinQueryExplainPlan", "serverMergeColumns",
-  "regionLocations", "numRegionLocationLookups" })
+@JsonPropertyOrder({ "abstractExplainPlan", "hint", "explainScanType", "consistency", "tableName",
+  "keyRanges", "scanTimeRangeMin", "scanTimeRangeMax", "splitsChunk", "useRoundRobinIterator",
+  "samplingRate", "hexStringRVCOffset", "iteratorTypeAndScanSize", "estimatedRows",
+  "estimatedSizeInBytes", "serverWhereFilter", "serverDistinctFilter", "serverMergeColumns",
+  "serverArrayElementProjection", "serverAggregate", "serverGroupByLimit", "serverSortedBy",
+  "serverOffset", "serverRowLimit", "clientFilterBy", "clientAggregate", "clientDistinctFilter",
+  "clientAfterAggregate", "clientSortAlgo", "clientSortedBy", "clientOffset", "clientRowLimit",
+  "clientSequenceCount", "clientCursorName", "clientSteps", "lhsJoinQueryExplainPlan",
+  "rhsJoinQueryExplainPlan", "subPlans", "dynamicServerFilter", "afterJoinFilter",
+  "joinScannerLimit", "sortMergeSkipMerge", "regionLocations", "regionLocationsTotalSize",
+  "numRegionLocationLookups" })
 public class ExplainPlanAttributes {
 
+  // Plan identity and scan-level metadata
   private final String abstractExplainPlan;
-  private final Integer splitsChunk;
-  private final Long estimatedRows;
-  private final Long estimatedSizeInBytes;
-  private final String iteratorTypeAndScanSize;
-  private final Double samplingRate;
-  private final boolean useRoundRobinIterator;
-  private final String hexStringRVCOffset;
-  private final Consistency consistency;
   private final Hint hint;
-  private final String serverSortedBy;
   private final String explainScanType;
+  private final Consistency consistency;
   private final String tableName;
   private final String keyRanges;
   private final Long scanTimeRangeMin;
   private final Long scanTimeRangeMax;
+  private final Integer splitsChunk;
+  private final boolean useRoundRobinIterator;
+  private final Double samplingRate;
+  private final String hexStringRVCOffset;
+  private final String iteratorTypeAndScanSize;
+  private final Long estimatedRows;
+  private final Long estimatedSizeInBytes;
+
+  // Server-side operations
   private final String serverWhereFilter;
   private final String serverDistinctFilter;
-  private final Integer serverOffset;
-  private final Long serverRowLimit;
+  private final Set<PColumn> serverMergeColumns;
   private final boolean serverArrayElementProjection;
   private final String serverAggregate;
+  private final Integer serverGroupByLimit;
+  private final String serverSortedBy;
+  private final Integer serverOffset;
+  private final Long serverRowLimit;
+
+  // Client-side operations
   private final String clientFilterBy;
   private final String clientAggregate;
-  private final String clientSortedBy;
-  private final String clientAfterAggregate;
   private final String clientDistinctFilter;
+  private final String clientAfterAggregate;
+  private final String clientSortAlgo;
+  private final String clientSortedBy;
   private final Integer clientOffset;
   private final Integer clientRowLimit;
   private final Integer clientSequenceCount;
   private final String clientCursorName;
-  private final String clientSortAlgo;
-  // This object represents PlanAttributes object for rhs query
-  // to be used only by Join queries. In case of Join query, lhs plan is
-  // represented by 'this' object and rhs plan is represented by
-  // 'rhsJoinQueryExplainPlan' object (which in turn should
-  // have null rhsJoinQueryExplainPlan)
-  // For non-Join queries related Plans, rhsJoinQueryExplainPlan will always
-  // be null
+  // Ordered client-side pipeline (CLIENT* lines in emission order).
+  private final List<String> clientSteps;
+
+  // Join / sub-plan
+  private final ExplainPlanAttributes lhsJoinQueryExplainPlan;
   private final ExplainPlanAttributes rhsJoinQueryExplainPlan;
-  private final Set<PColumn> serverMergeColumns;
+  private final List<ExplainPlanAttributes> subPlans;
+  private final String dynamicServerFilter;
+  private final String afterJoinFilter;
+  private final Long joinScannerLimit;
+  private final boolean sortMergeSkipMerge;
+
+  // Region-location metadata
   private final List<HRegionLocation> regionLocations;
+  // Total number of distinct region locations before any trimming. Null when not populated.
+  private final Integer regionLocationsTotalSize;
   private final int numRegionLocationLookups;
 
   private static final ExplainPlanAttributes EXPLAIN_PLAN_INSTANCE = new ExplainPlanAttributes();
 
   private ExplainPlanAttributes() {
     this.abstractExplainPlan = null;
-    this.splitsChunk = null;
-    this.estimatedRows = null;
-    this.estimatedSizeInBytes = null;
-    this.iteratorTypeAndScanSize = null;
-    this.samplingRate = null;
-    this.useRoundRobinIterator = false;
-    this.hexStringRVCOffset = null;
-    this.consistency = null;
     this.hint = null;
-    this.serverSortedBy = null;
     this.explainScanType = null;
+    this.consistency = null;
     this.tableName = null;
     this.keyRanges = null;
     this.scanTimeRangeMin = null;
     this.scanTimeRangeMax = null;
+    this.splitsChunk = null;
+    this.useRoundRobinIterator = false;
+    this.samplingRate = null;
+    this.hexStringRVCOffset = null;
+    this.iteratorTypeAndScanSize = null;
+    this.estimatedRows = null;
+    this.estimatedSizeInBytes = null;
     this.serverWhereFilter = null;
     this.serverDistinctFilter = null;
-    this.serverOffset = null;
-    this.serverRowLimit = null;
+    this.serverMergeColumns = null;
     this.serverArrayElementProjection = false;
     this.serverAggregate = null;
+    this.serverGroupByLimit = null;
+    this.serverSortedBy = null;
+    this.serverOffset = null;
+    this.serverRowLimit = null;
     this.clientFilterBy = null;
     this.clientAggregate = null;
-    this.clientSortedBy = null;
-    this.clientAfterAggregate = null;
     this.clientDistinctFilter = null;
+    this.clientAfterAggregate = null;
+    this.clientSortAlgo = null;
+    this.clientSortedBy = null;
     this.clientOffset = null;
     this.clientRowLimit = null;
     this.clientSequenceCount = null;
     this.clientCursorName = null;
-    this.clientSortAlgo = null;
+    this.clientSteps = null;
+    this.lhsJoinQueryExplainPlan = null;
     this.rhsJoinQueryExplainPlan = null;
-    this.serverMergeColumns = null;
+    this.subPlans = null;
+    this.dynamicServerFilter = null;
+    this.afterJoinFilter = null;
+    this.joinScannerLimit = null;
+    this.sortMergeSkipMerge = false;
     this.regionLocations = null;
+    this.regionLocationsTotalSize = null;
     this.numRegionLocationLookups = 0;
   }
 
-  public ExplainPlanAttributes(String abstractExplainPlan, Integer splitsChunk, Long estimatedRows,
-    Long estimatedSizeInBytes, String iteratorTypeAndScanSize, Double samplingRate,
-    boolean useRoundRobinIterator, String hexStringRVCOffset, Consistency consistency, Hint hint,
-    String serverSortedBy, String explainScanType, String tableName, String keyRanges,
-    Long scanTimeRangeMin, Long scanTimeRangeMax, String serverWhereFilter,
-    String serverDistinctFilter, Integer serverOffset, Long serverRowLimit,
-    boolean serverArrayElementProjection, String serverAggregate, String clientFilterBy,
-    String clientAggregate, String clientSortedBy, String clientAfterAggregate,
-    String clientDistinctFilter, Integer clientOffset, Integer clientRowLimit,
-    Integer clientSequenceCount, String clientCursorName, String clientSortAlgo,
-    ExplainPlanAttributes rhsJoinQueryExplainPlan, Set<PColumn> serverMergeColumns,
-    List<HRegionLocation> regionLocations, int numRegionLocationLookups) {
+  public ExplainPlanAttributes(String abstractExplainPlan, Hint hint, String explainScanType,
+    Consistency consistency, String tableName, String keyRanges, Long scanTimeRangeMin,
+    Long scanTimeRangeMax, Integer splitsChunk, boolean useRoundRobinIterator, Double samplingRate,
+    String hexStringRVCOffset, String iteratorTypeAndScanSize, Long estimatedRows,
+    Long estimatedSizeInBytes, String serverWhereFilter, String serverDistinctFilter,
+    Set<PColumn> serverMergeColumns, boolean serverArrayElementProjection, String serverAggregate,
+    Integer serverGroupByLimit, String serverSortedBy, Integer serverOffset, Long serverRowLimit,
+    String clientFilterBy, String clientAggregate, String clientDistinctFilter,
+    String clientAfterAggregate, String clientSortAlgo, String clientSortedBy, Integer clientOffset,
+    Integer clientRowLimit, Integer clientSequenceCount, String clientCursorName,
+    List<String> clientSteps, ExplainPlanAttributes lhsJoinQueryExplainPlan,
+    ExplainPlanAttributes rhsJoinQueryExplainPlan, List<ExplainPlanAttributes> subPlans,
+    String dynamicServerFilter, String afterJoinFilter, Long joinScannerLimit,
+    boolean sortMergeSkipMerge, List<HRegionLocation> regionLocations,
+    Integer regionLocationsTotalSize, int numRegionLocationLookups) {
     this.abstractExplainPlan = abstractExplainPlan;
-    this.splitsChunk = splitsChunk;
-    this.estimatedRows = estimatedRows;
-    this.estimatedSizeInBytes = estimatedSizeInBytes;
-    this.iteratorTypeAndScanSize = iteratorTypeAndScanSize;
-    this.samplingRate = samplingRate;
-    this.useRoundRobinIterator = useRoundRobinIterator;
-    this.hexStringRVCOffset = hexStringRVCOffset;
-    this.consistency = consistency;
     this.hint = hint;
-    this.serverSortedBy = serverSortedBy;
     this.explainScanType = explainScanType;
+    this.consistency = consistency;
     this.tableName = tableName;
     this.keyRanges = keyRanges;
     this.scanTimeRangeMin = scanTimeRangeMin;
     this.scanTimeRangeMax = scanTimeRangeMax;
+    this.splitsChunk = splitsChunk;
+    this.useRoundRobinIterator = useRoundRobinIterator;
+    this.samplingRate = samplingRate;
+    this.hexStringRVCOffset = hexStringRVCOffset;
+    this.iteratorTypeAndScanSize = iteratorTypeAndScanSize;
+    this.estimatedRows = estimatedRows;
+    this.estimatedSizeInBytes = estimatedSizeInBytes;
     this.serverWhereFilter = serverWhereFilter;
     this.serverDistinctFilter = serverDistinctFilter;
-    this.serverOffset = serverOffset;
-    this.serverRowLimit = serverRowLimit;
+    this.serverMergeColumns = serverMergeColumns;
     this.serverArrayElementProjection = serverArrayElementProjection;
     this.serverAggregate = serverAggregate;
+    this.serverGroupByLimit = serverGroupByLimit;
+    this.serverSortedBy = serverSortedBy;
+    this.serverOffset = serverOffset;
+    this.serverRowLimit = serverRowLimit;
     this.clientFilterBy = clientFilterBy;
     this.clientAggregate = clientAggregate;
-    this.clientSortedBy = clientSortedBy;
-    this.clientAfterAggregate = clientAfterAggregate;
     this.clientDistinctFilter = clientDistinctFilter;
+    this.clientAfterAggregate = clientAfterAggregate;
+    this.clientSortAlgo = clientSortAlgo;
+    this.clientSortedBy = clientSortedBy;
     this.clientOffset = clientOffset;
     this.clientRowLimit = clientRowLimit;
     this.clientSequenceCount = clientSequenceCount;
     this.clientCursorName = clientCursorName;
-    this.clientSortAlgo = clientSortAlgo;
+    this.clientSteps = (clientSteps == null || clientSteps.isEmpty())
+      ? null
+      : Collections.unmodifiableList(new ArrayList<>(clientSteps));
+    this.lhsJoinQueryExplainPlan = lhsJoinQueryExplainPlan;
     this.rhsJoinQueryExplainPlan = rhsJoinQueryExplainPlan;
-    this.serverMergeColumns = serverMergeColumns;
+    this.subPlans = subPlans;
+    this.dynamicServerFilter = dynamicServerFilter;
+    this.afterJoinFilter = afterJoinFilter;
+    this.joinScannerLimit = joinScannerLimit;
+    this.sortMergeSkipMerge = sortMergeSkipMerge;
     this.regionLocations = regionLocations;
+    this.regionLocationsTotalSize = regionLocationsTotalSize;
     this.numRegionLocationLookups = numRegionLocationLookups;
   }
 
@@ -182,64 +222,60 @@ public class ExplainPlanAttributes {
     return abstractExplainPlan;
   }
 
-  public Integer getSplitsChunk() {
-    return splitsChunk;
-  }
-
-  public Long getEstimatedRows() {
-    return estimatedRows;
+  public Hint getHint() {
+    return hint;
   }
 
-  public Long getEstimatedSizeInBytes() {
-    return estimatedSizeInBytes;
+  public String getExplainScanType() {
+    return explainScanType;
   }
 
-  public String getIteratorTypeAndScanSize() {
-    return iteratorTypeAndScanSize;
+  public Consistency getConsistency() {
+    return consistency;
   }
 
-  public Double getSamplingRate() {
-    return samplingRate;
+  public String getTableName() {
+    return tableName;
   }
 
-  public boolean isUseRoundRobinIterator() {
-    return useRoundRobinIterator;
+  public String getKeyRanges() {
+    return keyRanges;
   }
 
-  public String getHexStringRVCOffset() {
-    return hexStringRVCOffset;
+  public Long getScanTimeRangeMin() {
+    return scanTimeRangeMin;
   }
 
-  public Consistency getConsistency() {
-    return consistency;
+  public Long getScanTimeRangeMax() {
+    return scanTimeRangeMax;
   }
 
-  public Hint getHint() {
-    return hint;
+  public Integer getSplitsChunk() {
+    return splitsChunk;
   }
 
-  public String getServerSortedBy() {
-    return serverSortedBy;
+  public boolean isUseRoundRobinIterator() {
+    return useRoundRobinIterator;
   }
 
-  public String getExplainScanType() {
-    return explainScanType;
+  public Double getSamplingRate() {
+    return samplingRate;
   }
 
-  public String getTableName() {
-    return tableName;
+  public String getHexStringRVCOffset() {
+    return hexStringRVCOffset;
   }
 
-  public String getKeyRanges() {
-    return keyRanges;
+  public String getIteratorTypeAndScanSize() {
+    return iteratorTypeAndScanSize;
   }
 
-  public Long getScanTimeRangeMin() {
-    return scanTimeRangeMin;
+  public Long getEstimatedRows() {
+    return estimatedRows;
   }
 
-  public Long getScanTimeRangeMax() {
-    return scanTimeRangeMax;
+  public Long getEstimatedSizeInBytes() {
+    return estimatedSizeInBytes;
   }
 
   public String getServerWhereFilter() {
@@ -250,12 +286,9 @@ public class ExplainPlanAttributes {
     return serverDistinctFilter;
   }
 
-  public Integer getServerOffset() {
-    return serverOffset;
-  }
-
-  public Long getServerRowLimit() {
-    return serverRowLimit;
+  @JsonSerialize(using = ServerMergeColumnsSerializer.class)
+  public Set<PColumn> getServerMergeColumns() {
+    return serverMergeColumns;
   }
 
   public boolean isServerArrayElementProjection() {
@@ -266,6 +299,22 @@ public class ExplainPlanAttributes {
     return serverAggregate;
   }
 
+  public Integer getServerGroupByLimit() {
+    return serverGroupByLimit;
+  }
+
+  public String getServerSortedBy() {
+    return serverSortedBy;
+  }
+
+  public Integer getServerOffset() {
+    return serverOffset;
+  }
+
+  public Long getServerRowLimit() {
+    return serverRowLimit;
+  }
+
   public String getClientFilterBy() {
     return clientFilterBy;
   }
@@ -274,16 +323,20 @@ public class ExplainPlanAttributes {
     return clientAggregate;
   }
 
-  public String getClientSortedBy() {
-    return clientSortedBy;
+  public String getClientDistinctFilter() {
+    return clientDistinctFilter;
   }
 
   public String getClientAfterAggregate() {
     return clientAfterAggregate;
   }
 
-  public String getClientDistinctFilter() {
-    return clientDistinctFilter;
+  public String getClientSortAlgo() {
+    return clientSortAlgo;
+  }
+
+  public String getClientSortedBy() {
+    return clientSortedBy;
   }
 
   public Integer getClientOffset() {
@@ -302,17 +355,36 @@ public class ExplainPlanAttributes {
     return clientCursorName;
   }
 
-  public String getClientSortAlgo() {
-    return clientSortAlgo;
+  public List<String> getClientSteps() {
+    return clientSteps;
+  }
+
+  public ExplainPlanAttributes getLhsJoinQueryExplainPlan() {
+    return lhsJoinQueryExplainPlan;
   }
 
   public ExplainPlanAttributes getRhsJoinQueryExplainPlan() {
     return rhsJoinQueryExplainPlan;
   }
 
-  @JsonSerialize(using = ServerMergeColumnsSerializer.class)
-  public Set<PColumn> getServerMergeColumns() {
-    return serverMergeColumns;
+  public List<ExplainPlanAttributes> getSubPlans() {
+    return subPlans;
+  }
+
+  public String getDynamicServerFilter() {
+    return dynamicServerFilter;
+  }
+
+  public String getAfterJoinFilter() {
+    return afterJoinFilter;
+  }
+
+  public Long getJoinScannerLimit() {
+    return joinScannerLimit;
+  }
+
+  public boolean isSortMergeSkipMerge() {
+    return sortMergeSkipMerge;
   }
 
   @JsonSerialize(using = RegionLocationsListSerializer.class)
@@ -320,6 +392,10 @@ public class ExplainPlanAttributes {
     return regionLocations;
   }
 
+  public Integer getRegionLocationsTotalSize() {
+    return regionLocationsTotalSize;
+  }
+
   public int getNumRegionLocationLookups() {
     return numRegionLocationLookups;
   }
@@ -330,40 +406,49 @@ public class ExplainPlanAttributes {
 
   public static class ExplainPlanAttributesBuilder {
     private String abstractExplainPlan;
-    private Integer splitsChunk;
-    private Long estimatedRows;
-    private Long estimatedSizeInBytes;
-    private String iteratorTypeAndScanSize;
-    private Double samplingRate;
-    private boolean useRoundRobinIterator;
-    private String hexStringRVCOffset;
-    private Consistency consistency;
     private HintNode.Hint hint;
-    private String serverSortedBy;
     private String explainScanType;
+    private Consistency consistency;
     private String tableName;
     private String keyRanges;
     private Long scanTimeRangeMin;
     private Long scanTimeRangeMax;
+    private Integer splitsChunk;
+    private boolean useRoundRobinIterator;
+    private Double samplingRate;
+    private String hexStringRVCOffset;
+    private String iteratorTypeAndScanSize;
+    private Long estimatedRows;
+    private Long estimatedSizeInBytes;
     private String serverWhereFilter;
     private String serverDistinctFilter;
-    private Integer serverOffset;
-    private Long serverRowLimit;
+    private Set<PColumn> serverMergeColumns;
     private boolean serverArrayElementProjection;
     private String serverAggregate;
+    private Integer serverGroupByLimit;
+    private String serverSortedBy;
+    private Integer serverOffset;
+    private Long serverRowLimit;
     private String clientFilterBy;
     private String clientAggregate;
-    private String clientSortedBy;
-    private String clientAfterAggregate;
     private String clientDistinctFilter;
+    private String clientAfterAggregate;
+    private String clientSortAlgo;
+    private String clientSortedBy;
     private Integer clientOffset;
     private Integer clientRowLimit;
     private Integer clientSequenceCount;
     private String clientCursorName;
-    private String clientSortAlgo;
+    private List<String> clientSteps;
+    private ExplainPlanAttributes lhsJoinQueryExplainPlan;
     private ExplainPlanAttributes rhsJoinQueryExplainPlan;
-    private Set<PColumn> serverMergeColumns;
+    private List<ExplainPlanAttributes> subPlans;
+    private String dynamicServerFilter;
+    private String afterJoinFilter;
+    private Long joinScannerLimit;
+    private boolean sortMergeSkipMerge;
     private List<HRegionLocation> regionLocations;
+    private Integer regionLocationsTotalSize;
     private int numRegionLocationLookups;
 
     public ExplainPlanAttributesBuilder() {
@@ -372,40 +457,50 @@ public class ExplainPlanAttributes {
 
     public ExplainPlanAttributesBuilder(ExplainPlanAttributes explainPlanAttributes) {
       this.abstractExplainPlan = explainPlanAttributes.getAbstractExplainPlan();
-      this.splitsChunk = explainPlanAttributes.getSplitsChunk();
-      this.estimatedRows = explainPlanAttributes.getEstimatedRows();
-      this.estimatedSizeInBytes = explainPlanAttributes.getEstimatedSizeInBytes();
-      this.iteratorTypeAndScanSize = explainPlanAttributes.getIteratorTypeAndScanSize();
-      this.samplingRate = explainPlanAttributes.getSamplingRate();
-      this.useRoundRobinIterator = explainPlanAttributes.isUseRoundRobinIterator();
-      this.hexStringRVCOffset = explainPlanAttributes.getHexStringRVCOffset();
-      this.consistency = explainPlanAttributes.getConsistency();
       this.hint = explainPlanAttributes.getHint();
-      this.serverSortedBy = explainPlanAttributes.getServerSortedBy();
       this.explainScanType = explainPlanAttributes.getExplainScanType();
+      this.consistency = explainPlanAttributes.getConsistency();
       this.tableName = explainPlanAttributes.getTableName();
       this.keyRanges = explainPlanAttributes.getKeyRanges();
       this.scanTimeRangeMin = explainPlanAttributes.getScanTimeRangeMin();
       this.scanTimeRangeMax = explainPlanAttributes.getScanTimeRangeMax();
+      this.splitsChunk = explainPlanAttributes.getSplitsChunk();
+      this.useRoundRobinIterator = explainPlanAttributes.isUseRoundRobinIterator();
+      this.samplingRate = explainPlanAttributes.getSamplingRate();
+      this.hexStringRVCOffset = explainPlanAttributes.getHexStringRVCOffset();
+      this.iteratorTypeAndScanSize = explainPlanAttributes.getIteratorTypeAndScanSize();
+      this.estimatedRows = explainPlanAttributes.getEstimatedRows();
+      this.estimatedSizeInBytes = explainPlanAttributes.getEstimatedSizeInBytes();
       this.serverWhereFilter = explainPlanAttributes.getServerWhereFilter();
       this.serverDistinctFilter = explainPlanAttributes.getServerDistinctFilter();
-      this.serverOffset = explainPlanAttributes.getServerOffset();
-      this.serverRowLimit = explainPlanAttributes.getServerRowLimit();
+      this.serverMergeColumns = explainPlanAttributes.getServerMergeColumns();
       this.serverArrayElementProjection = explainPlanAttributes.isServerArrayElementProjection();
       this.serverAggregate = explainPlanAttributes.getServerAggregate();
+      this.serverGroupByLimit = explainPlanAttributes.getServerGroupByLimit();
+      this.serverSortedBy = explainPlanAttributes.getServerSortedBy();
+      this.serverOffset = explainPlanAttributes.getServerOffset();
+      this.serverRowLimit = explainPlanAttributes.getServerRowLimit();
       this.clientFilterBy = explainPlanAttributes.getClientFilterBy();
       this.clientAggregate = explainPlanAttributes.getClientAggregate();
-      this.clientSortedBy = explainPlanAttributes.getClientSortedBy();
-      this.clientAfterAggregate = explainPlanAttributes.getClientAfterAggregate();
       this.clientDistinctFilter = explainPlanAttributes.getClientDistinctFilter();
+      this.clientAfterAggregate = explainPlanAttributes.getClientAfterAggregate();
+      this.clientSortAlgo = explainPlanAttributes.getClientSortAlgo();
+      this.clientSortedBy = explainPlanAttributes.getClientSortedBy();
       this.clientOffset = explainPlanAttributes.getClientOffset();
       this.clientRowLimit = explainPlanAttributes.getClientRowLimit();
       this.clientSequenceCount = explainPlanAttributes.getClientSequenceCount();
       this.clientCursorName = explainPlanAttributes.getClientCursorName();
-      this.clientSortAlgo = explainPlanAttributes.getClientSortAlgo();
+      List<String> srcClientSteps = explainPlanAttributes.getClientSteps();
+      this.clientSteps = srcClientSteps == null ? null : new ArrayList<>(srcClientSteps);
+      this.lhsJoinQueryExplainPlan = explainPlanAttributes.getLhsJoinQueryExplainPlan();
       this.rhsJoinQueryExplainPlan = explainPlanAttributes.getRhsJoinQueryExplainPlan();
-      this.serverMergeColumns = explainPlanAttributes.getServerMergeColumns();
+      this.subPlans = explainPlanAttributes.getSubPlans();
+      this.dynamicServerFilter = explainPlanAttributes.getDynamicServerFilter();
+      this.afterJoinFilter = explainPlanAttributes.getAfterJoinFilter();
+      this.joinScannerLimit = explainPlanAttributes.getJoinScannerLimit();
+      this.sortMergeSkipMerge = explainPlanAttributes.isSortMergeSkipMerge();
       this.regionLocations = explainPlanAttributes.getRegionLocations();
+      this.regionLocationsTotalSize = explainPlanAttributes.getRegionLocationsTotalSize();
       this.numRegionLocationLookups = explainPlanAttributes.getNumRegionLocationLookups();
     }
 
@@ -414,78 +509,73 @@ public class ExplainPlanAttributes {
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setSplitsChunk(Integer splitsChunk) {
-      this.splitsChunk = splitsChunk;
-      return this;
-    }
-
-    public ExplainPlanAttributesBuilder setEstimatedRows(Long estimatedRows) {
-      this.estimatedRows = estimatedRows;
+    public ExplainPlanAttributesBuilder setHint(HintNode.Hint hint) {
+      this.hint = hint;
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setEstimatedSizeInBytes(Long estimatedSizeInBytes) {
-      this.estimatedSizeInBytes = estimatedSizeInBytes;
+    public ExplainPlanAttributesBuilder setExplainScanType(String explainScanType) {
+      this.explainScanType = explainScanType;
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setIteratorTypeAndScanSize(String iteratorTypeAndScanSize) {
-      this.iteratorTypeAndScanSize = iteratorTypeAndScanSize;
+    public ExplainPlanAttributesBuilder setConsistency(Consistency consistency) {
+      this.consistency = consistency;
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setSamplingRate(Double samplingRate) {
-      this.samplingRate = samplingRate;
+    public ExplainPlanAttributesBuilder setTableName(String tableName) {
+      this.tableName = tableName;
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setUseRoundRobinIterator(boolean useRoundRobinIterator) {
-      this.useRoundRobinIterator = useRoundRobinIterator;
+    public ExplainPlanAttributesBuilder setKeyRanges(String keyRanges) {
+      this.keyRanges = keyRanges;
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setHexStringRVCOffset(String hexStringRVCOffset) {
-      this.hexStringRVCOffset = hexStringRVCOffset;
+    public ExplainPlanAttributesBuilder setScanTimeRangeMin(Long scanTimeRangeMin) {
+      this.scanTimeRangeMin = scanTimeRangeMin;
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setConsistency(Consistency consistency) {
-      this.consistency = consistency;
+    public ExplainPlanAttributesBuilder setScanTimeRangeMax(Long scanTimeRangeMax) {
+      this.scanTimeRangeMax = scanTimeRangeMax;
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setHint(HintNode.Hint hint) {
-      this.hint = hint;
+    public ExplainPlanAttributesBuilder setSplitsChunk(Integer splitsChunk) {
+      this.splitsChunk = splitsChunk;
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setServerSortedBy(String serverSortedBy) {
-      this.serverSortedBy = serverSortedBy;
+    public ExplainPlanAttributesBuilder setUseRoundRobinIterator(boolean useRoundRobinIterator) {
+      this.useRoundRobinIterator = useRoundRobinIterator;
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setExplainScanType(String explainScanType) {
-      this.explainScanType = explainScanType;
+    public ExplainPlanAttributesBuilder setSamplingRate(Double samplingRate) {
+      this.samplingRate = samplingRate;
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setTableName(String tableName) {
-      this.tableName = tableName;
+    public ExplainPlanAttributesBuilder setHexStringRVCOffset(String hexStringRVCOffset) {
+      this.hexStringRVCOffset = hexStringRVCOffset;
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setKeyRanges(String keyRanges) {
-      this.keyRanges = keyRanges;
+    public ExplainPlanAttributesBuilder setIteratorTypeAndScanSize(String iteratorTypeAndScanSize) {
+      this.iteratorTypeAndScanSize = iteratorTypeAndScanSize;
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setScanTimeRangeMin(Long scanTimeRangeMin) {
-      this.scanTimeRangeMin = scanTimeRangeMin;
+    public ExplainPlanAttributesBuilder setEstimatedRows(Long estimatedRows) {
+      this.estimatedRows = estimatedRows;
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setScanTimeRangeMax(Long scanTimeRangeMax) {
-      this.scanTimeRangeMax = scanTimeRangeMax;
+    public ExplainPlanAttributesBuilder setEstimatedSizeInBytes(Long estimatedSizeInBytes) {
+      this.estimatedSizeInBytes = estimatedSizeInBytes;
       return this;
     }
 
@@ -499,13 +589,8 @@ public class ExplainPlanAttributes {
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setServerOffset(Integer serverOffset) {
-      this.serverOffset = serverOffset;
-      return this;
-    }
-
-    public ExplainPlanAttributesBuilder setServerRowLimit(Long serverRowLimit) {
-      this.serverRowLimit = serverRowLimit;
+    public ExplainPlanAttributesBuilder setServerMergeColumns(Set<PColumn> columns) {
+      this.serverMergeColumns = columns;
       return this;
     }
 
@@ -520,6 +605,26 @@ public class ExplainPlanAttributes {
       return this;
     }
 
+    public ExplainPlanAttributesBuilder setServerGroupByLimit(Integer serverGroupByLimit) {
+      this.serverGroupByLimit = serverGroupByLimit;
+      return this;
+    }
+
+    public ExplainPlanAttributesBuilder setServerSortedBy(String serverSortedBy) {
+      this.serverSortedBy = serverSortedBy;
+      return this;
+    }
+
+    public ExplainPlanAttributesBuilder setServerOffset(Integer serverOffset) {
+      this.serverOffset = serverOffset;
+      return this;
+    }
+
+    public ExplainPlanAttributesBuilder setServerRowLimit(Long serverRowLimit) {
+      this.serverRowLimit = serverRowLimit;
+      return this;
+    }
+
     public ExplainPlanAttributesBuilder setClientFilterBy(String clientFilterBy) {
       this.clientFilterBy = clientFilterBy;
       return this;
@@ -530,8 +635,8 @@ public class ExplainPlanAttributes {
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setClientSortedBy(String clientSortedBy) {
-      this.clientSortedBy = clientSortedBy;
+    public ExplainPlanAttributesBuilder setClientDistinctFilter(String clientDistinctFilter) {
+      this.clientDistinctFilter = clientDistinctFilter;
       return this;
     }
 
@@ -540,8 +645,13 @@ public class ExplainPlanAttributes {
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setClientDistinctFilter(String clientDistinctFilter) {
-      this.clientDistinctFilter = clientDistinctFilter;
+    public ExplainPlanAttributesBuilder setClientSortAlgo(String clientSortAlgo) {
+      this.clientSortAlgo = clientSortAlgo;
+      return this;
+    }
+
+    public ExplainPlanAttributesBuilder setClientSortedBy(String clientSortedBy) {
+      this.clientSortedBy = clientSortedBy;
       return this;
     }
 
@@ -565,8 +675,22 @@ public class ExplainPlanAttributes {
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setClientSortAlgo(String clientSortAlgo) {
-      this.clientSortAlgo = clientSortAlgo;
+    public ExplainPlanAttributesBuilder setClientSteps(List<String> clientSteps) {
+      this.clientSteps = clientSteps == null ? null : new ArrayList<>(clientSteps);
+      return this;
+    }
+
+    public ExplainPlanAttributesBuilder addClientStep(String step) {
+      if (this.clientSteps == null) {
+        this.clientSteps = new ArrayList<>();
+      }
+      this.clientSteps.add(step);
+      return this;
+    }
+
+    public ExplainPlanAttributesBuilder
+      setLhsJoinQueryExplainPlan(ExplainPlanAttributes lhsJoinQueryExplainPlan) {
+      this.lhsJoinQueryExplainPlan = lhsJoinQueryExplainPlan;
       return this;
     }
 
@@ -576,8 +700,28 @@ public class ExplainPlanAttributes {
       return this;
     }
 
-    public ExplainPlanAttributesBuilder setServerMergeColumns(Set<PColumn> columns) {
-      this.serverMergeColumns = columns;
+    public ExplainPlanAttributesBuilder setSubPlans(List<ExplainPlanAttributes> subPlans) {
+      this.subPlans = subPlans;
+      return this;
+    }
+
+    public ExplainPlanAttributesBuilder setDynamicServerFilter(String dynamicServerFilter) {
+      this.dynamicServerFilter = dynamicServerFilter;
+      return this;
+    }
+
+    public ExplainPlanAttributesBuilder setAfterJoinFilter(String afterJoinFilter) {
+      this.afterJoinFilter = afterJoinFilter;
+      return this;
+    }
+
+    public ExplainPlanAttributesBuilder setJoinScannerLimit(Long joinScannerLimit) {
+      this.joinScannerLimit = joinScannerLimit;
+      return this;
+    }
+
+    public ExplainPlanAttributesBuilder setSortMergeSkipMerge(boolean sortMergeSkipMerge) {
+      this.sortMergeSkipMerge = sortMergeSkipMerge;
       return this;
     }
 
@@ -586,20 +730,28 @@ public class ExplainPlanAttributes {
       return this;
     }
 
+    public ExplainPlanAttributesBuilder
+      setRegionLocationsTotalSize(Integer regionLocationsTotalSize) {
+      this.regionLocationsTotalSize = regionLocationsTotalSize;
+      return this;
+    }
+
     public ExplainPlanAttributesBuilder setNumRegionLocationLookups(int numRegionLocationLookups) {
       this.numRegionLocationLookups = numRegionLocationLookups;
       return this;
     }
 
     public ExplainPlanAttributes build() {
-      return new ExplainPlanAttributes(abstractExplainPlan, splitsChunk, estimatedRows,
-        estimatedSizeInBytes, iteratorTypeAndScanSize, samplingRate, useRoundRobinIterator,
-        hexStringRVCOffset, consistency, hint, serverSortedBy, explainScanType, tableName,
-        keyRanges, scanTimeRangeMin, scanTimeRangeMax, serverWhereFilter, serverDistinctFilter,
-        serverOffset, serverRowLimit, serverArrayElementProjection, serverAggregate, clientFilterBy,
-        clientAggregate, clientSortedBy, clientAfterAggregate, clientDistinctFilter, clientOffset,
-        clientRowLimit, clientSequenceCount, clientCursorName, clientSortAlgo,
-        rhsJoinQueryExplainPlan, serverMergeColumns, regionLocations, numRegionLocationLookups);
+      return new ExplainPlanAttributes(abstractExplainPlan, hint, explainScanType, consistency,
+        tableName, keyRanges, scanTimeRangeMin, scanTimeRangeMax, splitsChunk,
+        useRoundRobinIterator, samplingRate, hexStringRVCOffset, iteratorTypeAndScanSize,
+        estimatedRows, estimatedSizeInBytes, serverWhereFilter, serverDistinctFilter,
+        serverMergeColumns, serverArrayElementProjection, serverAggregate, serverGroupByLimit,
+        serverSortedBy, serverOffset, serverRowLimit, clientFilterBy, clientAggregate,
+        clientDistinctFilter, clientAfterAggregate, clientSortAlgo, clientSortedBy, clientOffset,
+        clientRowLimit, clientSequenceCount, clientCursorName, clientSteps, lhsJoinQueryExplainPlan,
+        rhsJoinQueryExplainPlan, subPlans, dynamicServerFilter, afterJoinFilter, joinScannerLimit,
+        sortMergeSkipMerge, regionLocations, regionLocationsTotalSize, numRegionLocationLookups);
     }
   }
 }
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/compile/GroupByCompiler.java b/phoenix-core-client/src/main/java/org/apache/phoenix/compile/GroupByCompiler.java
index 7b090467b3..06db058418 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/compile/GroupByCompiler.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/compile/GroupByCompiler.java
@@ -164,6 +164,7 @@ public class GroupByCompiler {
       return orderPreservingTrackInfos;
     }
 
+    @SuppressWarnings("rawtypes")
     public GroupBy compile(StatementContext context, QueryPlan innerQueryPlan,
       Expression whereExpression) throws SQLException {
       boolean isOrderPreserving = this.isOrderPreserving;
@@ -365,6 +366,9 @@ public class GroupByCompiler {
       planSteps.add("    " + serverAggregate);
       if (explainPlanAttributesBuilder != null) {
         explainPlanAttributesBuilder.setServerAggregate(serverAggregate);
+        if (!isUngroupedAggregate && limit != null) {
+          explainPlanAttributesBuilder.setServerGroupByLimit(limit);
+        }
       }
     }
 
@@ -448,6 +452,7 @@ public class GroupByCompiler {
     return groupBy;
   }
 
+  @SuppressWarnings("rawtypes")
   private static boolean onlyAtEndType(Expression expression) {
     // Due to the encoding schema of these types, they may only be
     // used once in a group by and are located at the end of the
@@ -456,6 +461,7 @@ public class GroupByCompiler {
     return type.isArrayType() || type == PVarbinary.INSTANCE;
   }
 
+  @SuppressWarnings("rawtypes")
   private static PDataType getGroupByDataType(Expression expression) {
     return IndexUtil.getIndexColumnDataType(expression.isNullable(), expression.getDataType());
   }
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/execute/ClientAggregatePlan.java b/phoenix-core-client/src/main/java/org/apache/phoenix/execute/ClientAggregatePlan.java
index e89bf515cc..4a3d1b5d28 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/execute/ClientAggregatePlan.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/execute/ClientAggregatePlan.java
@@ -226,63 +226,86 @@ public class ClientAggregatePlan extends ClientProcessingPlan {
     ExplainPlanAttributesBuilder newBuilder =
       new ExplainPlanAttributesBuilder(explainPlanAttributes);
     if (where != null) {
-      planSteps.add("CLIENT FILTER BY " + where.toString());
+      String step = "CLIENT FILTER BY " + where.toString();
+      planSteps.add(step);
       newBuilder.setClientFilterBy(where.toString());
+      newBuilder.addClientStep(step);
     }
     if (groupBy.isEmpty()) {
-      planSteps.add("CLIENT AGGREGATE INTO SINGLE ROW");
-      newBuilder.setClientAggregate("CLIENT AGGREGATE INTO SINGLE ROW");
+      String step = "CLIENT AGGREGATE INTO SINGLE ROW";
+      planSteps.add(step);
+      newBuilder.setClientAggregate(step);
+      newBuilder.addClientStep(step);
     } else if (groupBy.isOrderPreserving()) {
-      planSteps.add(
-        "CLIENT AGGREGATE INTO ORDERED DISTINCT ROWS BY " + groupBy.getExpressions().toString());
-      newBuilder.setClientAggregate(
-        "CLIENT AGGREGATE INTO ORDERED DISTINCT ROWS BY " + groupBy.getExpressions().toString());
+      String step =
+        "CLIENT AGGREGATE INTO ORDERED DISTINCT ROWS BY " + groupBy.getExpressions().toString();
+      planSteps.add(step);
+      newBuilder.setClientAggregate(step);
+      newBuilder.addClientStep(step);
     } else if (useHashAgg) {
-      planSteps
-        .add("CLIENT HASH AGGREGATE INTO DISTINCT ROWS BY " + groupBy.getExpressions().toString());
-      newBuilder.setClientAggregate(
-        "CLIENT HASH AGGREGATE INTO DISTINCT ROWS BY " + groupBy.getExpressions().toString());
+      String step =
+        "CLIENT HASH AGGREGATE INTO DISTINCT ROWS BY " + groupBy.getExpressions().toString();
+      planSteps.add(step);
+      newBuilder.setClientAggregate(step);
+      newBuilder.addClientStep(step);
       if (orderBy == OrderBy.FWD_ROW_KEY_ORDER_BY || orderBy == OrderBy.REV_ROW_KEY_ORDER_BY) {
-        planSteps.add("CLIENT SORTED BY " + groupBy.getKeyExpressions().toString());
+        String sortStep = "CLIENT SORTED BY " + groupBy.getKeyExpressions().toString();
+        planSteps.add(sortStep);
         newBuilder.setClientSortedBy(groupBy.getKeyExpressions().toString());
+        newBuilder.addClientStep(sortStep);
       }
     } else {
-      planSteps.add("CLIENT SORTED BY " + groupBy.getKeyExpressions().toString());
-      planSteps
-        .add("CLIENT AGGREGATE INTO DISTINCT ROWS BY " + groupBy.getExpressions().toString());
+      String sortStep = "CLIENT SORTED BY " + groupBy.getKeyExpressions().toString();
+      String aggStep =
+        "CLIENT AGGREGATE INTO DISTINCT ROWS BY " + groupBy.getExpressions().toString();
+      planSteps.add(sortStep);
+      planSteps.add(aggStep);
       newBuilder.setClientSortedBy(groupBy.getKeyExpressions().toString());
-      newBuilder.setClientAggregate(
-        "CLIENT AGGREGATE INTO DISTINCT ROWS BY " + groupBy.getExpressions().toString());
+      newBuilder.setClientAggregate(aggStep);
+      newBuilder.addClientStep(sortStep);
+      newBuilder.addClientStep(aggStep);
     }
     if (having != null) {
-      planSteps.add("CLIENT AFTER-AGGREGATION FILTER BY " + having.toString());
-      newBuilder.setClientAfterAggregate("CLIENT AFTER-AGGREGATION FILTER BY " + having.toString());
+      String step = "CLIENT AFTER-AGGREGATION FILTER BY " + having.toString();
+      planSteps.add(step);
+      newBuilder.setClientAfterAggregate(step);
+      newBuilder.addClientStep(step);
     }
     if (statement.isDistinct() && statement.isAggregate()) {
-      planSteps.add("CLIENT DISTINCT ON " + projector.toString());
+      String step = "CLIENT DISTINCT ON " + projector.toString();
+      planSteps.add(step);
       newBuilder.setClientDistinctFilter(projector.toString());
+      newBuilder.addClientStep(step);
     }
     if (offset != null) {
-      planSteps.add("CLIENT OFFSET " + offset);
+      String step = "CLIENT OFFSET " + offset;
+      planSteps.add(step);
       newBuilder.setClientOffset(offset);
+      newBuilder.addClientStep(step);
     }
     if (orderBy.getOrderByExpressions().isEmpty()) {
       if (limit != null) {
-        planSteps.add("CLIENT " + limit + " ROW LIMIT");
+        String step = "CLIENT " + limit + " ROW LIMIT";
+        planSteps.add(step);
         newBuilder.setClientRowLimit(limit);
+        newBuilder.addClientStep(step);
       }
     } else {
-      planSteps
-        .add("CLIENT" + (limit == null ? "" : " TOP " + limit + " ROW" + (limit == 1 ? "" : "S"))
-          + " SORTED BY " + orderBy.getOrderByExpressions().toString());
+      String step =
+        "CLIENT" + (limit == null ? "" : " TOP " + limit + " ROW" + (limit == 1 ? "" : "S"))
+          + " SORTED BY " + orderBy.getOrderByExpressions().toString();
+      planSteps.add(step);
       newBuilder.setClientRowLimit(limit);
       newBuilder.setClientSortedBy(orderBy.getOrderByExpressions().toString());
+      newBuilder.addClientStep(step);
     }
     if (context.getSequenceManager().getSequenceCount() > 0) {
       int nSequences = context.getSequenceManager().getSequenceCount();
-      planSteps.add(
-        "CLIENT RESERVE VALUES FROM " + nSequences + " SEQUENCE" + (nSequences == 1 ? "" : "S"));
+      String step =
+        "CLIENT RESERVE VALUES FROM " + nSequences + " SEQUENCE" + (nSequences == 1 ? "" : "S");
+      planSteps.add(step);
       newBuilder.setClientSequenceCount(nSequences);
+      newBuilder.addClientStep(step);
     }
 
     return new ExplainPlan(planSteps, newBuilder.build());
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/execute/ClientScanPlan.java b/phoenix-core-client/src/main/java/org/apache/phoenix/execute/ClientScanPlan.java
index 8bc7198960..9807ba8ef9 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/execute/ClientScanPlan.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/execute/ClientScanPlan.java
@@ -123,34 +123,46 @@ public class ClientScanPlan extends ClientProcessingPlan {
     ExplainPlanAttributesBuilder newBuilder =
       new ExplainPlanAttributesBuilder(explainPlanAttributes);
     if (where != null) {
-      planSteps.add("CLIENT FILTER BY " + where.toString());
+      String step = "CLIENT FILTER BY " + where.toString();
+      planSteps.add(step);
       newBuilder.setClientFilterBy(where.toString());
+      newBuilder.addClientStep(step);
     }
     if (!orderBy.getOrderByExpressions().isEmpty()) {
       if (offset != null) {
-        planSteps.add("CLIENT OFFSET " + offset);
+        String step = "CLIENT OFFSET " + offset;
+        planSteps.add(step);
         newBuilder.setClientOffset(offset);
+        newBuilder.addClientStep(step);
       }
-      planSteps
-        .add("CLIENT" + (limit == null ? "" : " TOP " + limit + " ROW" + (limit == 1 ? "" : "S"))
-          + " SORTED BY " + orderBy.getOrderByExpressions().toString());
+      String step =
+        "CLIENT" + (limit == null ? "" : " TOP " + limit + " ROW" + (limit == 1 ? "" : "S"))
+          + " SORTED BY " + orderBy.getOrderByExpressions().toString();
+      planSteps.add(step);
       newBuilder.setClientRowLimit(limit);
       newBuilder.setClientSortedBy(orderBy.getOrderByExpressions().toString());
+      newBuilder.addClientStep(step);
     } else {
       if (offset != null) {
-        planSteps.add("CLIENT OFFSET " + offset);
+        String step = "CLIENT OFFSET " + offset;
+        planSteps.add(step);
         newBuilder.setClientOffset(offset);
+        newBuilder.addClientStep(step);
       }
       if (limit != null) {
-        planSteps.add("CLIENT " + limit + " ROW LIMIT");
+        String step = "CLIENT " + limit + " ROW LIMIT";
+        planSteps.add(step);
         newBuilder.setClientRowLimit(limit);
+        newBuilder.addClientStep(step);
       }
     }
     if (context.getSequenceManager().getSequenceCount() > 0) {
       int nSequences = context.getSequenceManager().getSequenceCount();
-      planSteps.add(
-        "CLIENT RESERVE VALUES FROM " + nSequences + " SEQUENCE" + (nSequences == 1 ? "" : "S"));
+      String step =
+        "CLIENT RESERVE VALUES FROM " + nSequences + " SEQUENCE" + (nSequences == 1 ? "" : "S");
+      planSteps.add(step);
       newBuilder.setClientSequenceCount(nSequences);
+      newBuilder.addClientStep(step);
     }
 
     return new ExplainPlan(planSteps, newBuilder.build());
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/execute/HashJoinPlan.java b/phoenix-core-client/src/main/java/org/apache/phoenix/execute/HashJoinPlan.java
index 81500776db..aa18e0e6cc 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/execute/HashJoinPlan.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/execute/HashJoinPlan.java
@@ -40,6 +40,8 @@ import org.apache.hadoop.hbase.util.Bytes;
 import org.apache.phoenix.cache.ServerCacheClient.ServerCache;
 import org.apache.phoenix.compile.ColumnProjector;
 import org.apache.phoenix.compile.ExplainPlan;
+import org.apache.phoenix.compile.ExplainPlanAttributes;
+import org.apache.phoenix.compile.ExplainPlanAttributes.ExplainPlanAttributesBuilder;
 import org.apache.phoenix.compile.FromCompiler;
 import org.apache.phoenix.compile.QueryPlan;
 import org.apache.phoenix.compile.RowProjector;
@@ -313,24 +315,62 @@ public class HashJoinPlan extends DelegateQueryPlan {
 
   @Override
   public ExplainPlan getExplainPlan() throws SQLException {
-    // TODO : Support ExplainPlanAttributes for HashJoinPlan
-    List<String> planSteps = Lists.newArrayList(delegate.getExplainPlan().getPlanSteps());
+    ExplainPlan delegateExplainPlan = delegate.getExplainPlan();
+    List<String> planSteps = Lists.newArrayList(delegateExplainPlan.getPlanSteps());
+    // Each hash/skip-scan sub-plan is recorded under subPlans.
+    ExplainPlanAttributes delegateAttributes = delegateExplainPlan.getPlanStepsAsAttributes();
+    if (delegateAttributes == null) {
+      delegateAttributes = ExplainPlanAttributes.getDefaultExplainPlan();
+    }
+    ExplainPlanAttributesBuilder builder = new ExplainPlanAttributesBuilder(delegateAttributes);
+    List<ExplainPlanAttributes> subPlanAttributes = Lists.newArrayList();
     int count = subPlans.length;
     for (int i = 0; i < count; i++) {
       planSteps.addAll(subPlans[i].getPreSteps(this));
+      ExplainPlanAttributes subPlanAttribute = subPlans[i].getPreStepsAsAttributes(this);
+      if (subPlanAttribute != null) {
+        subPlanAttributes.add(subPlanAttribute);
+      }
     }
     for (int i = 0; i < count; i++) {
-      planSteps.addAll(subPlans[i].getPostSteps(this));
+      List<String> postSteps = subPlans[i].getPostSteps(this);
+      planSteps.addAll(postSteps);
+      for (String step : postSteps) {
+        String trimmed = step.trim();
+        if (trimmed.startsWith("DYNAMIC SERVER FILTER BY")) {
+          builder.setDynamicServerFilter(trimmed);
+        }
+      }
     }
 
     if (joinInfo != null && joinInfo.getPostJoinFilterExpression() != null) {
-      planSteps.add(
-        "    AFTER-JOIN SERVER FILTER BY " + joinInfo.getPostJoinFilterExpression().toString());
+      String afterJoinFilter =
+        "AFTER-JOIN SERVER FILTER BY " + joinInfo.getPostJoinFilterExpression().toString();
+      planSteps.add("    " + afterJoinFilter);
+      builder.setAfterJoinFilter(afterJoinFilter);
     }
     if (joinInfo != null && joinInfo.getLimit() != null) {
       planSteps.add("    JOIN-SCANNER " + joinInfo.getLimit() + " ROW LIMIT");
+      builder.setJoinScannerLimit(joinInfo.getLimit().longValue());
     }
-    return new ExplainPlan(planSteps);
+    if (!subPlanAttributes.isEmpty()) {
+      builder.setSubPlans(subPlanAttributes);
+    }
+    return new ExplainPlan(planSteps, builder.build());
+  }
+
+  /**
+   * Builds the explain-plan attributes for a hash-join subplan by taking the inner plan's
+   * attributes (when available) and stamping the supplied join header onto abstractExplainPlan.
+   */
+  private static ExplainPlanAttributes subPlanAttributesWithHeader(QueryPlan plan, String header)
+    throws SQLException {
+    ExplainPlanAttributes innerAttributes = plan.getExplainPlan().getPlanStepsAsAttributes();
+    ExplainPlanAttributesBuilder builder =
+      (innerAttributes != null && innerAttributes != ExplainPlanAttributes.getDefaultExplainPlan())
+        ? new ExplainPlanAttributesBuilder(innerAttributes)
+        : new ExplainPlanAttributesBuilder();
+    return builder.setAbstractExplainPlan(header).build();
   }
 
   @Override
@@ -430,6 +470,14 @@ public class HashJoinPlan extends DelegateQueryPlan {
 
     public List<String> getPostSteps(HashJoinPlan parent) throws SQLException;
 
+    /**
+     * Returns the explain-plan attributes for this subplan, with its abstractExplainPlan. Returns
+     * null when no structured attributes are available for the inner plan.
+     */
+    default ExplainPlanAttributes getPreStepsAsAttributes(HashJoinPlan parent) throws SQLException {
+      return null;
+    }
+
     public QueryPlan getInnerPlan();
 
     public boolean hasKeyRangeExpression();
@@ -446,6 +494,7 @@ public class HashJoinPlan extends DelegateQueryPlan {
       this.expectSingleRow = expectSingleRow;
     }
 
+    @SuppressWarnings("rawtypes")
     @Override
     public ServerCache execute(HashJoinPlan parent) throws SQLException {
       List<Object> values = Lists.<Object> newArrayList();
@@ -508,6 +557,12 @@ public class HashJoinPlan extends DelegateQueryPlan {
       return steps;
     }
 
+    @Override
+    public ExplainPlanAttributes getPreStepsAsAttributes(HashJoinPlan parent) throws SQLException {
+      String header = "EXECUTE " + (expectSingleRow ? "SINGLE" : "MULTIPLE") + "-ROW SUBQUERY";
+      return subPlanAttributesWithHeader(plan, header);
+    }
+
     @Override
     public List<String> getPostSteps(HashJoinPlan parent) throws SQLException {
       return Collections.<String> emptyList();
@@ -646,6 +701,21 @@ public class HashJoinPlan extends DelegateQueryPlan {
       return steps;
     }
 
+    @Override
+    public ExplainPlanAttributes getPreStepsAsAttributes(HashJoinPlan parent) throws SQLException {
+      boolean earlyEvaluation = parent.joinInfo.earlyEvaluation()[index];
+      boolean skipMerge = parent.joinInfo.getSchemas()[index].getFieldCount() == 0;
+      String header;
+      if (hashExpressions != null) {
+        header = "PARALLEL " + parent.joinInfo.getJoinTypes()[index].toString().toUpperCase()
+          + "-JOIN TABLE " + index + (earlyEvaluation ? "" : "(DELAYED EVALUATION)")
+          + (skipMerge ? " (SKIP MERGE)" : "");
+      } else {
+        header = "SKIP-SCAN-JOIN TABLE " + index;
+      }
+      return subPlanAttributesWithHeader(plan, header);
+    }
+
     @Override
     public List<String> getPostSteps(HashJoinPlan parent) throws SQLException {
       if (keyRangeLhsExpression == null) return Collections.<String> emptyList();
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/execute/SortMergeJoinPlan.java b/phoenix-core-client/src/main/java/org/apache/phoenix/execute/SortMergeJoinPlan.java
index 0b85190221..9e1cd2290b 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/execute/SortMergeJoinPlan.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/execute/SortMergeJoinPlan.java
@@ -192,10 +192,6 @@ public class SortMergeJoinPlan implements QueryPlan {
     ExplainPlan lhsExplainPlan = lhsPlan.getExplainPlan();
     List<String> lhsPlanSteps = lhsExplainPlan.getPlanSteps();
     ExplainPlanAttributes lhsPlanAttributes = lhsExplainPlan.getPlanStepsAsAttributes();
-    ExplainPlanAttributesBuilder lhsPlanBuilder =
-      new ExplainPlanAttributesBuilder(lhsPlanAttributes);
-    lhsPlanBuilder
-      .setAbstractExplainPlan("SORT-MERGE-JOIN (" + joinType.toString().toUpperCase() + ")");
 
     for (String step : lhsPlanSteps) {
       steps.add("    " + step);
@@ -205,15 +201,20 @@ public class SortMergeJoinPlan implements QueryPlan {
     ExplainPlan rhsExplainPlan = rhsPlan.getExplainPlan();
     List<String> rhsPlanSteps = rhsExplainPlan.getPlanSteps();
     ExplainPlanAttributes rhsPlanAttributes = rhsExplainPlan.getPlanStepsAsAttributes();
-    ExplainPlanAttributesBuilder rhsPlanBuilder =
-      new ExplainPlanAttributesBuilder(rhsPlanAttributes);
-
-    lhsPlanBuilder.setRhsJoinQueryExplainPlan(rhsPlanBuilder.build());
 
     for (String step : rhsPlanSteps) {
       steps.add("    " + step);
     }
-    return new ExplainPlan(steps, lhsPlanBuilder.build());
+
+    // Build a synthetic root that holds the join operator and its two operands as separate
+    // child plans so nested sort-merge-joins can be represented.
+    ExplainPlanAttributesBuilder rootBuilder = new ExplainPlanAttributesBuilder();
+    rootBuilder
+      .setAbstractExplainPlan("SORT-MERGE-JOIN (" + joinType.toString().toUpperCase() + ")");
+    rootBuilder.setSortMergeSkipMerge(rhsSchema.getFieldCount() == 0);
+    rootBuilder.setLhsJoinQueryExplainPlan(lhsPlanAttributes);
+    rootBuilder.setRhsJoinQueryExplainPlan(rhsPlanAttributes);
+    return new ExplainPlan(steps, rootBuilder.build());
   }
 
   @Override
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/execute/TupleProjectionPlan.java b/phoenix-core-client/src/main/java/org/apache/phoenix/execute/TupleProjectionPlan.java
index ac38657f18..413f046d22 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/execute/TupleProjectionPlan.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/execute/TupleProjectionPlan.java
@@ -147,10 +147,12 @@ public class TupleProjectionPlan extends DelegateQueryPlan {
     List<String> planSteps = Lists.newArrayList(explainPlan.getPlanSteps());
     ExplainPlanAttributes explainPlanAttributes = explainPlan.getPlanStepsAsAttributes();
     if (postFilter != null) {
-      planSteps.add("CLIENT FILTER BY " + postFilter.toString());
+      String step = "CLIENT FILTER BY " + postFilter.toString();
+      planSteps.add(step);
       ExplainPlanAttributesBuilder newBuilder =
         new ExplainPlanAttributesBuilder(explainPlanAttributes);
       newBuilder.setClientFilterBy(postFilter.toString());
+      newBuilder.addClientStep(step);
       explainPlanAttributes = newBuilder.build();
     }
 
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/CursorResultIterator.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/CursorResultIterator.java
index 9c44579366..113c6fad45 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/CursorResultIterator.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/CursorResultIterator.java
@@ -60,7 +60,9 @@ public class CursorResultIterator implements ResultIterator {
     ExplainPlanAttributesBuilder explainPlanAttributesBuilder) {
     delegate.explain(planSteps, explainPlanAttributesBuilder);
     explainPlanAttributesBuilder.setClientCursorName(cursorName);
-    planSteps.add("CLIENT CURSOR " + cursorName);
+    String step = "CLIENT CURSOR " + cursorName;
+    planSteps.add(step);
+    explainPlanAttributesBuilder.addClientStep(step);
   }
 
   @Override
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/DistinctAggregatingResultIterator.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/DistinctAggregatingResultIterator.java
index 10f081c8a4..6dfdfb8857 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/DistinctAggregatingResultIterator.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/DistinctAggregatingResultIterator.java
@@ -134,7 +134,9 @@ public class DistinctAggregatingResultIterator implements AggregatingResultItera
     ExplainPlanAttributesBuilder explainPlanAttributesBuilder) {
     targetAggregatingResultIterator.explain(planSteps, explainPlanAttributesBuilder);
     explainPlanAttributesBuilder.setClientDistinctFilter(rowProjector.toString());
-    planSteps.add("CLIENT DISTINCT ON " + rowProjector.toString());
+    String step = "CLIENT DISTINCT ON " + rowProjector.toString();
+    planSteps.add(step);
+    explainPlanAttributesBuilder.addClientStep(step);
   }
 
   @Override
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/ExplainTable.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/ExplainTable.java
index 221a69c8dd..8382100561 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/ExplainTable.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/ExplainTable.java
@@ -24,7 +24,6 @@ import java.util.Collections;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
-import java.util.NoSuchElementException;
 import java.util.Set;
 import org.apache.hadoop.hbase.HRegionLocation;
 import org.apache.hadoop.hbase.client.Consistency;
@@ -53,7 +52,6 @@ import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.query.QueryServicesOptions;
 import org.apache.phoenix.schema.PColumn;
 import org.apache.phoenix.schema.PTable;
-import org.apache.phoenix.schema.RowKeySchema;
 import org.apache.phoenix.schema.SortOrder;
 import org.apache.phoenix.schema.TableRef;
 import org.apache.phoenix.schema.types.PDataType;
@@ -288,8 +286,11 @@ public abstract class ExplainTable {
       }
       if (explainPlanAttributesBuilder != null) {
         explainPlanAttributesBuilder.setServerOffset(offset);
-        if (pageFilter != null) {
-          explainPlanAttributesBuilder.setServerRowLimit(pageFilter.getPageSize());
+        // Populate the attribute whenever a "SERVER n ROW LIMIT" step is emitted, including the
+        // uncovered-index/server-merge path where the limit originates from the INDEX_LIMIT scan
+        // attribute rather than a PageFilter.
+        if (limit != null) {
+          explainPlanAttributesBuilder.setServerRowLimit(limit);
         }
       }
     }
@@ -365,7 +366,8 @@ public abstract class ExplainTable {
           regionLocations.subList(0, maxLimitRegionLoc);
         if (explainPlanAttributesBuilder != null) {
           explainPlanAttributesBuilder
-            .setRegionLocations(Collections.unmodifiableList(trimmedRegionLocations));
+            .setRegionLocations(Collections.unmodifiableList(trimmedRegionLocations))
+            .setRegionLocationsTotalSize(originalSize);
         }
         buf.append(trimmedRegionLocations);
         buf.append("...total size = ");
@@ -374,7 +376,8 @@ public abstract class ExplainTable {
         buf.append(regionLocations);
         if (explainPlanAttributesBuilder != null) {
           explainPlanAttributesBuilder
-            .setRegionLocations(Collections.unmodifiableList(regionLocations));
+            .setRegionLocations(Collections.unmodifiableList(regionLocations))
+            .setRegionLocationsTotalSize(regionLocations.size());
         }
       }
       buf.append(") ");
@@ -418,6 +421,7 @@ public abstract class ExplainTable {
     }
   }
 
+  @SuppressWarnings("rawtypes")
   private void appendPKColumnValue(StringBuilder buf, byte[] range, Boolean isNull, int slotIndex,
     boolean changeViewIndexId) {
     if (Boolean.TRUE.equals(isNull)) {
@@ -449,55 +453,13 @@ public abstract class ExplainTable {
     }
   }
 
+  @SuppressWarnings("rawtypes")
   private Long getViewIndexValue(PDataType type, byte[] range) {
     boolean useLongViewIndex = MetaDataUtil.getViewIndexIdDataType().equals(type);
     Object s = type.toObject(range);
     return (useLongViewIndex ? (Long) s : (Short) s) + Short.MAX_VALUE + 2;
   }
 
-  private static class RowKeyValueIterator implements Iterator<byte[]> {
-    private final RowKeySchema schema;
-    private ImmutableBytesWritable ptr = new ImmutableBytesWritable();
-    private int position = 0;
-    private final int maxOffset;
-    private byte[] nextValue;
-
-    public RowKeyValueIterator(RowKeySchema schema, byte[] rowKey) {
-      this.schema = schema;
-      this.maxOffset = schema.iterator(rowKey, ptr);
-      iterate();
-    }
-
-    private void iterate() {
-      if (schema.next(ptr, position++, maxOffset) == null) {
-        nextValue = null;
-      } else {
-        nextValue = ptr.copyBytes();
-      }
-    }
-
-    @Override
-    public boolean hasNext() {
-      return nextValue != null;
-    }
-
-    @Override
-    public byte[] next() {
-      if (nextValue == null) {
-        throw new NoSuchElementException();
-      }
-      byte[] value = nextValue;
-      iterate();
-      return value;
-    }
-
-    @Override
-    public void remove() {
-      throw new UnsupportedOperationException();
-    }
-
-  }
-
   private void appendScanRow(StringBuilder buf, Bound bound) {
     ScanRanges scanRanges = context.getScanRanges();
     Iterator<byte[]> minMaxIterator = Collections.emptyIterator();
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/FilterAggregatingResultIterator.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/FilterAggregatingResultIterator.java
index fb3609066c..82d6ba6824 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/FilterAggregatingResultIterator.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/FilterAggregatingResultIterator.java
@@ -82,7 +82,9 @@ public class FilterAggregatingResultIterator implements AggregatingResultIterato
     ExplainPlanAttributesBuilder explainPlanAttributesBuilder) {
     delegate.explain(planSteps, explainPlanAttributesBuilder);
     explainPlanAttributesBuilder.setClientFilterBy(expression.toString());
-    planSteps.add("CLIENT FILTER BY " + expression.toString());
+    String step = "CLIENT FILTER BY " + expression.toString();
+    planSteps.add(step);
+    explainPlanAttributesBuilder.addClientStep(step);
   }
 
   @Override
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/FilterResultIterator.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/FilterResultIterator.java
index f6631dee43..9435f20464 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/FilterResultIterator.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/FilterResultIterator.java
@@ -80,7 +80,9 @@ public class FilterResultIterator extends LookAheadResultIterator {
     ExplainPlanAttributesBuilder explainPlanAttributesBuilder) {
     delegate.explain(planSteps, explainPlanAttributesBuilder);
     explainPlanAttributesBuilder.setClientFilterBy(expression.toString());
-    planSteps.add("CLIENT FILTER BY " + expression.toString());
+    String step = "CLIENT FILTER BY " + expression.toString();
+    planSteps.add(step);
+    explainPlanAttributesBuilder.addClientStep(step);
   }
 
   @Override
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/LimitingResultIterator.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/LimitingResultIterator.java
index 0d60c3b04d..1a90c87d3b 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/LimitingResultIterator.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/LimitingResultIterator.java
@@ -55,7 +55,9 @@ public class LimitingResultIterator extends DelegateResultIterator {
     ExplainPlanAttributesBuilder explainPlanAttributesBuilder) {
     super.explain(planSteps, explainPlanAttributesBuilder);
     explainPlanAttributesBuilder.setClientRowLimit(limit);
-    planSteps.add("CLIENT " + limit + " ROW LIMIT");
+    String step = "CLIENT " + limit + " ROW LIMIT";
+    planSteps.add(step);
+    explainPlanAttributesBuilder.addClientStep(step);
   }
 
   @Override
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/MergeSortRowKeyResultIterator.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/MergeSortRowKeyResultIterator.java
index 2412c2a092..7691504d93 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/MergeSortRowKeyResultIterator.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/MergeSortRowKeyResultIterator.java
@@ -59,6 +59,7 @@ public class MergeSortRowKeyResultIterator extends MergeSortResultIterator {
     resultIterators.explain(planSteps, explainPlanAttributesBuilder);
     explainPlanAttributesBuilder.setClientSortAlgo("CLIENT MERGE SORT");
     planSteps.add("CLIENT MERGE SORT");
+    explainPlanAttributesBuilder.addClientStep("CLIENT MERGE SORT");
   }
 
   @Override
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/MergeSortTopNResultIterator.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/MergeSortTopNResultIterator.java
index 2c72682e19..767656a950 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/MergeSortTopNResultIterator.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/MergeSortTopNResultIterator.java
@@ -116,13 +116,18 @@ public class MergeSortTopNResultIterator extends MergeSortResultIterator {
     resultIterators.explain(planSteps, explainPlanAttributesBuilder);
     explainPlanAttributesBuilder.setClientSortAlgo("CLIENT MERGE SORT");
     planSteps.add("CLIENT MERGE SORT");
+    explainPlanAttributesBuilder.addClientStep("CLIENT MERGE SORT");
     if (offset > 0) {
       explainPlanAttributesBuilder.setClientOffset(offset);
-      planSteps.add("CLIENT OFFSET " + offset);
+      String step = "CLIENT OFFSET " + offset;
+      planSteps.add(step);
+      explainPlanAttributesBuilder.addClientStep(step);
     }
     if (limit > 0) {
       explainPlanAttributesBuilder.setClientRowLimit(limit);
-      planSteps.add("CLIENT LIMIT " + limit);
+      String step = "CLIENT LIMIT " + limit;
+      planSteps.add(step);
+      explainPlanAttributesBuilder.addClientStep(step);
     }
   }
 
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/OffsetResultIterator.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/OffsetResultIterator.java
index bc092a0a2e..fc369eed25 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/OffsetResultIterator.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/OffsetResultIterator.java
@@ -92,7 +92,9 @@ public class OffsetResultIterator extends DelegateResultIterator {
     ExplainPlanAttributesBuilder explainPlanAttributesBuilder) {
     super.explain(planSteps, explainPlanAttributesBuilder);
     explainPlanAttributesBuilder.setClientOffset(offset);
-    planSteps.add("CLIENT OFFSET " + offset);
+    String step = "CLIENT OFFSET " + offset;
+    planSteps.add(step);
+    explainPlanAttributesBuilder.addClientStep(step);
   }
 
   @Override
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/OrderedResultIterator.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/OrderedResultIterator.java
index 2cc3ccb3f6..1662b5b465 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/OrderedResultIterator.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/OrderedResultIterator.java
@@ -514,9 +514,11 @@ public class OrderedResultIterator implements PeekingResultIterator {
     explainPlanAttributesBuilder.setClientOffset(offset);
     explainPlanAttributesBuilder.setClientRowLimit(limit);
     explainPlanAttributesBuilder.setClientSortedBy(orderByExpressions.toString());
-    planSteps.add("CLIENT" + (offset == null || offset == 0 ? "" : " OFFSET " + offset)
+    String step = "CLIENT" + (offset == null || offset == 0 ? "" : " OFFSET " + offset)
       + (limit == null ? "" : " TOP " + limit + " ROW" + (limit == 1 ? "" : "S")) + " SORTED BY "
-      + orderByExpressions.toString());
+      + orderByExpressions.toString();
+    planSteps.add(step);
+    explainPlanAttributesBuilder.addClientStep(step);
   }
 
   @Override
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/SegmentResultIterator.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/SegmentResultIterator.java
index 1bed34afbd..752600a296 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/SegmentResultIterator.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/SegmentResultIterator.java
@@ -120,5 +120,6 @@ public class SegmentResultIterator extends BaseResultIterator {
   public void explain(List<String> planSteps,
     ExplainPlanAttributesBuilder explainPlanAttributesBuilder) {
     planSteps.add("CLIENT SEGMENT SCAN");
+    explainPlanAttributesBuilder.addClientStep("CLIENT SEGMENT SCAN");
   }
 }
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/SequenceResultIterator.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/SequenceResultIterator.java
index b58ba58610..ae98654cfa 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/SequenceResultIterator.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/SequenceResultIterator.java
@@ -60,8 +60,10 @@ public class SequenceResultIterator extends DelegateResultIterator {
     super.explain(planSteps, explainPlanAttributesBuilder);
     int nSequences = sequenceManager.getSequenceCount();
     explainPlanAttributesBuilder.setClientSequenceCount(nSequences);
-    planSteps
-      .add("CLIENT RESERVE VALUES FROM " + nSequences + " SEQUENCE" + (nSequences == 1 ? "" : "S"));
+    String step =
+      "CLIENT RESERVE VALUES FROM " + nSequences + " SEQUENCE" + (nSequences == 1 ? "" : "S");
+    planSteps.add(step);
+    explainPlanAttributesBuilder.addClientStep(step);
   }
 
   @Override
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/AlterSessionIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/AlterSessionIT.java
index 1fe2d15e79..0f02a5b7a3 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/AlterSessionIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/AlterSessionIT.java
@@ -17,20 +17,18 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
 
 import java.sql.Connection;
 import java.sql.DriverManager;
-import java.sql.ResultSet;
 import java.sql.Statement;
 import java.util.Properties;
 import org.apache.hadoop.hbase.client.Consistency;
 import org.apache.phoenix.jdbc.PhoenixConnection;
 import org.apache.phoenix.util.PhoenixRuntime;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -58,16 +56,12 @@ public class AlterSessionIT extends ParallelStatsDisabledIT {
     try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
       Statement st = conn.createStatement();
       st.execute("alter session set Consistency = 'timeline'");
-      ResultSet rs = st.executeQuery("explain select * from " + tableName);
       assertEquals(Consistency.TIMELINE, conn.unwrap(PhoenixConnection.class).getConsistency());
-      String queryPlan = QueryUtil.getExplainPlan(rs);
-      assertTrue(queryPlan.indexOf("TIMELINE") > 0);
+      assertPlan(conn, "select * from " + tableName).consistency("TIMELINE");
 
       // turn off timeline read consistency
       st.execute("alter session set Consistency = 'strong'");
-      rs = st.executeQuery("explain select * from " + tableName);
-      queryPlan = QueryUtil.getExplainPlan(rs);
-      assertTrue(queryPlan.indexOf("TIMELINE") < 0);
+      assertPlan(conn, "select * from " + tableName).consistency("STRONG");
     }
   }
 
@@ -77,10 +71,7 @@ public class AlterSessionIT extends ParallelStatsDisabledIT {
     try (Connection conn = DriverManager.getConnection(
       getUrl() + PhoenixRuntime.JDBC_PROTOCOL_TERMINATOR + "Consistency=TIMELINE", props)) {
       assertEquals(Consistency.TIMELINE, ((PhoenixConnection) conn).getConsistency());
-      Statement st = conn.createStatement();
-      ResultSet rs = st.executeQuery("explain select * from " + tableName);
-      String queryPlan = QueryUtil.getExplainPlan(rs);
-      assertTrue(queryPlan.indexOf("TIMELINE") > 0);
+      assertPlan(conn, "select * from " + tableName).consistency("TIMELINE");
       conn.close();
     }
   }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java
index fde20a6130..2be8e8f772 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.apache.phoenix.util.TestUtil.assertResultSet;
 import static org.junit.Assert.assertEquals;
@@ -39,10 +40,7 @@ import org.apache.hadoop.hbase.client.Result;
 import org.apache.hadoop.hbase.client.ResultScanner;
 import org.apache.hadoop.hbase.client.Scan;
 import org.apache.hadoop.hbase.client.Table;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.jdbc.PhoenixConnection;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.ConnectionQueryServices;
 import org.apache.phoenix.query.KeyRange;
 import org.apache.phoenix.query.QueryServices;
@@ -513,20 +511,14 @@ public abstract class BaseAggregateIT extends ParallelStatsDisabledIT {
     assertEquals("abc", rs.getString(2));
     assertFalse(rs.next());
 
-    ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
-      .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals(
-      " ['000001111122222','333334444455555',0,*] - ['000001111122222','333334444455555',0,1]",
-      explainPlanAttributes.getKeyRanges());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals(
-      "SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [MATCH_STATUS, EXTERNAL_DATASOURCE_KEY]",
-      explainPlanAttributes.getServerAggregate());
-    assertEquals("COUNT(1) > 1", explainPlanAttributes.getClientFilterBy());
+    assertPlan(conn, queryBuilder.build()).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+      .table(tableName)
+      .keyRanges(
+        " ['000001111122222','333334444455555',0,*] - ['000001111122222','333334444455555',0,1]")
+      .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+      .serverAggregate(
+        "SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [MATCH_STATUS, EXTERNAL_DATASOURCE_KEY]")
+      .clientFilterBy("COUNT(1) > 1");
   }
 
   @Test
@@ -564,18 +556,10 @@ public abstract class BaseAggregateIT extends ParallelStatsDisabledIT {
     assertEquals("a", rs.getString(1));
     assertEquals(4, rs.getLong(2));
     assertFalse(rs.next());
-    ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
-      .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("REVERSE", explainPlanAttributes.getClientSortedBy());
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]",
-      explainPlanAttributes.getServerAggregate());
-    assertFalse("Explain plan regionLocation attribute should not be empty",
-      explainPlanAttributes.getRegionLocations().isEmpty());
+    assertPlan(conn, queryBuilder.build()).iteratorType("PARALLEL 1-WAY").clientSortedBy("REVERSE")
+      .scanType("FULL SCAN").table(tableName).serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+      .serverAggregate("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]")
+      .regionLocationsNotEmpty();
   }
 
   @Test
@@ -621,18 +605,10 @@ public abstract class BaseAggregateIT extends ParallelStatsDisabledIT {
     assertEquals("a", rs.getString(1));
     assertEquals(10, rs.getLong(2));
     assertFalse(rs.next());
-    ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
-      .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("REVERSE", explainPlanAttributes.getClientSortedBy());
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]",
-      explainPlanAttributes.getServerAggregate());
-    assertFalse("Explain plan regionLocation attribute should not be empty",
-      explainPlanAttributes.getRegionLocations().isEmpty());
+    assertPlan(conn, queryBuilder.build()).iteratorType("PARALLEL 1-WAY").clientSortedBy("REVERSE")
+      .scanType("FULL SCAN").table(tableName).serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+      .serverAggregate("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]")
+      .regionLocationsNotEmpty();
   }
 
   @Test
@@ -688,21 +664,14 @@ public abstract class BaseAggregateIT extends ParallelStatsDisabledIT {
     assertEquals("n", rs.getString(1));
     assertEquals(2, rs.getDouble(2), 1e-6);
     assertFalse(rs.next());
-    ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
-      .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]",
-      explainPlanAttributes.getServerAggregate());
+    assertPlan(conn, queryBuilder.build()).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+      .table(tableName).serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+      .serverAggregate("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]")
+      .regionLocationsNotEmpty();
     TestUtil.analyzeTable(conn, tableName);
     List<KeyRange> splits = TestUtil.getAllSplits(conn, tableName);
     // nGuideposts when stats are enabled, 4 when disabled
     assertEquals(4, splits.size());
-    assertFalse("Explain plan regionLocation attribute should not be empty",
-      explainPlanAttributes.getRegionLocations().isEmpty());
   }
 
   @Test
@@ -833,9 +802,6 @@ public abstract class BaseAggregateIT extends ParallelStatsDisabledIT {
       assertEquals("entityId3", rs.getString(1));
       assertEquals(1.4, rs.getDouble(2), 0.001);
       assertFalse(rs.next());
-
-      String expectedPhoenixPlan = "";
-      validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null);
     }
   }
 
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMoves2IT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMoves2IT.java
index 6ae7869cfe..7d908eecc1 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMoves2IT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMoves2IT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -31,9 +32,6 @@ import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.util.List;
 import java.util.Properties;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.KeyRange;
 import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.schema.types.PChar;
@@ -137,20 +135,14 @@ public class BaseAggregateWithRegionMoves2IT extends ParallelStatsDisabledWithRe
     assertEquals("abc", rs.getString(2));
     assertFalse(rs.next());
 
-    ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
-      .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals(
-      " ['000001111122222','333334444455555',0,*] - ['000001111122222','333334444455555',0,1]",
-      explainPlanAttributes.getKeyRanges());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals(
-      "SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [MATCH_STATUS, EXTERNAL_DATASOURCE_KEY]",
-      explainPlanAttributes.getServerAggregate());
-    assertEquals("COUNT(1) > 1", explainPlanAttributes.getClientFilterBy());
+    assertPlan(conn, queryBuilder.build()).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+      .table(tableName)
+      .keyRanges(
+        " ['000001111122222','333334444455555',0,*] - ['000001111122222','333334444455555',0,1]")
+      .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+      .serverAggregate(
+        "SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [MATCH_STATUS, EXTERNAL_DATASOURCE_KEY]")
+      .clientFilterBy("COUNT(1) > 1");
   }
 
   @Test
@@ -190,16 +182,9 @@ public class BaseAggregateWithRegionMoves2IT extends ParallelStatsDisabledWithRe
     assertEquals("a", rs.getString(1));
     assertEquals(4, rs.getLong(2));
     assertFalse(rs.next());
-    ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
-      .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("REVERSE", explainPlanAttributes.getClientSortedBy());
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]",
-      explainPlanAttributes.getServerAggregate());
+    assertPlan(conn, queryBuilder.build()).iteratorType("PARALLEL 1-WAY").clientSortedBy("REVERSE")
+      .scanType("FULL SCAN").table(tableName).serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+      .serverAggregate("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]");
   }
 
   @Test
@@ -249,16 +234,9 @@ public class BaseAggregateWithRegionMoves2IT extends ParallelStatsDisabledWithRe
     assertEquals("a", rs.getString(1));
     assertEquals(10, rs.getLong(2));
     assertFalse(rs.next());
-    ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
-      .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("REVERSE", explainPlanAttributes.getClientSortedBy());
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]",
-      explainPlanAttributes.getServerAggregate());
+    assertPlan(conn, queryBuilder.build()).iteratorType("PARALLEL 1-WAY").clientSortedBy("REVERSE")
+      .scanType("FULL SCAN").table(tableName).serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+      .serverAggregate("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]");
   }
 
   @Test
@@ -304,13 +282,8 @@ public class BaseAggregateWithRegionMoves2IT extends ParallelStatsDisabledWithRe
     assertEquals("a", rs.getString(1));
     assertEquals(10, rs.getLong(2));
     assertFalse(rs.next());
-    ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
-      .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("REVERSE", explainPlanAttributes.getClientSortedBy());
-    assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
+    assertPlan(conn, queryBuilder.build()).iteratorType("PARALLEL 1-WAY").clientSortedBy("REVERSE")
+      .scanType("RANGE SCAN").table(tableName);
   }
 
   @Test
@@ -463,15 +436,9 @@ public class BaseAggregateWithRegionMoves2IT extends ParallelStatsDisabledWithRe
     assertEquals("n", rs.getString(1));
     assertEquals(2, rs.getDouble(2), 1e-6);
     assertFalse(rs.next());
-    ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
-      .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]",
-      explainPlanAttributes.getServerAggregate());
+    assertPlan(conn, queryBuilder.build()).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+      .table(tableName).serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+      .serverAggregate("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]");
     TestUtil.analyzeTable(conn, tableName);
     List<KeyRange> splits = TestUtil.getAllSplits(conn, tableName);
     // nGuideposts when stats are enabled, 4 when disabled
@@ -527,9 +494,6 @@ public class BaseAggregateWithRegionMoves2IT extends ParallelStatsDisabledWithRe
       assertEquals("entityId3", rs.getString(1));
       assertEquals(1.4, rs.getDouble(2), 0.001);
       assertFalse(rs.next());
-
-      String expectedPhoenixPlan = "";
-      validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null);
     }
   }
 
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMovesIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMovesIT.java
index 621a3d3380..e363b0bf29 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMovesIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMovesIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -32,9 +33,6 @@ import java.sql.SQLException;
 import java.sql.Statement;
 import java.util.List;
 import java.util.Properties;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.KeyRange;
 import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.schema.types.PChar;
@@ -365,15 +363,9 @@ public abstract class BaseAggregateWithRegionMovesIT
     assertEquals("n", rs.getString(1));
     assertEquals(2, rs.getDouble(2), 1e-6);
     assertFalse(rs.next());
-    ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
-      .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]",
-      explainPlanAttributes.getServerAggregate());
+    assertPlan(conn, queryBuilder.build()).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+      .table(tableName).serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+      .serverAggregate("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]");
     TestUtil.analyzeTable(conn, tableName);
     List<KeyRange> splits = TestUtil.getAllSplits(conn, tableName);
     // nGuideposts when stats are enabled, 4 when disabled
@@ -402,15 +394,9 @@ public abstract class BaseAggregateWithRegionMovesIT
     assertEquals("a", rs.getString(1));
     assertEquals(3, rs.getDouble(2), 1e-6);
     assertFalse(rs.next());
-    ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
-      .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]",
-      explainPlanAttributes.getServerAggregate());
+    assertPlan(conn, queryBuilder.build()).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+      .table(tableName).serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+      .serverAggregate("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]");
     TestUtil.analyzeTable(conn, tableName);
     List<KeyRange> splits = TestUtil.getAllSplits(conn, tableName);
     // nGuideposts when stats are enabled, 4 when disabled
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseOrderByIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseOrderByIT.java
index 62e7a9271e..d02a8a7058 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseOrderByIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseOrderByIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.ROW1;
 import static org.apache.phoenix.util.TestUtil.ROW2;
 import static org.apache.phoenix.util.TestUtil.ROW3;
@@ -30,7 +31,6 @@ import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.apache.phoenix.util.TestUtil.assertResultSet;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 
 import java.sql.Connection;
@@ -40,9 +40,6 @@ import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
 import java.util.Properties;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.util.PropertiesUtil;
 import org.apache.phoenix.util.QueryBuilder;
@@ -290,18 +287,10 @@ public abstract class BaseOrderByIT extends ParallelStatsDisabledIT {
       .setSelectExpression("DISTINCT(K2)").setWhereClause("K2 = 'ABC'");
 
     // verify that the phoenix query plan doesn't contain an order by
-    ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
-      .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals("SERVER FILTER BY K2 = 'ABC'", explainPlanAttributes.getServerWhereFilter());
-    assertEquals("SERVER AGGREGATE INTO DISTINCT ROWS BY [K2, VAL1, VAL2]",
-      explainPlanAttributes.getServerAggregate());
-    assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-    assertNull(explainPlanAttributes.getClientSortedBy());
-    assertNull(explainPlanAttributes.getServerSortedBy());
+    assertPlan(conn, queryBuilder.build()).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+      .table(tableName).serverWhereFilter("SERVER FILTER BY K2 = 'ABC'")
+      .serverAggregate("SERVER AGGREGATE INTO DISTINCT ROWS BY [K2, VAL1, VAL2]")
+      .clientSortAlgo("CLIENT MERGE SORT").clientSortedBy(null).serverSortedBy(null);
 
     ResultSet rs = executeQuery(conn, queryBuilder);
     assertTrue(rs.next());
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseOrderByWithRegionMovesIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseOrderByWithRegionMovesIT.java
index bef4c8aace..2fb0d59022 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseOrderByWithRegionMovesIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseOrderByWithRegionMovesIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.ROW1;
 import static org.apache.phoenix.util.TestUtil.ROW2;
 import static org.apache.phoenix.util.TestUtil.ROW3;
@@ -30,7 +31,6 @@ import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.apache.phoenix.util.TestUtil.assertResultSet;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 
 import java.sql.Connection;
@@ -40,9 +40,6 @@ import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
 import java.util.Properties;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.util.PropertiesUtil;
 import org.apache.phoenix.util.QueryBuilder;
 import org.apache.phoenix.util.SchemaUtil;
@@ -362,18 +359,10 @@ public abstract class BaseOrderByWithRegionMovesIT extends ParallelStatsDisabled
       .setSelectExpression("DISTINCT(K2)").setWhereClause("K2 = 'ABC'");
 
     // verify that the phoenix query plan doesn't contain an order by
-    ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
-      .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals("SERVER FILTER BY K2 = 'ABC'", explainPlanAttributes.getServerWhereFilter());
-    assertEquals("SERVER AGGREGATE INTO DISTINCT ROWS BY [K2, VAL1, VAL2]",
-      explainPlanAttributes.getServerAggregate());
-    assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-    assertNull(explainPlanAttributes.getClientSortedBy());
-    assertNull(explainPlanAttributes.getServerSortedBy());
+    assertPlan(conn, queryBuilder.build()).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+      .table(tableName).serverWhereFilter("SERVER FILTER BY K2 = 'ABC'")
+      .serverAggregate("SERVER AGGREGATE INTO DISTINCT ROWS BY [K2, VAL1, VAL2]")
+      .clientSortAlgo("CLIENT MERGE SORT").clientSortedBy(null).serverSortedBy(null);
 
     ResultSet rs = executeQuery(conn, queryBuilder);
     assertTrue(rs.next());
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BasePermissionsIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BasePermissionsIT.java
index 4f8622aacc..e3fc2ac9ee 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BasePermissionsIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BasePermissionsIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotEquals;
@@ -85,7 +86,6 @@ import org.junit.runners.MethodSorters;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import org.apache.phoenix.thirdparty.com.google.common.base.Joiner;
 import org.apache.phoenix.thirdparty.com.google.common.base.Throwables;
 import org.apache.phoenix.thirdparty.com.google.common.collect.Lists;
 import org.apache.phoenix.thirdparty.com.google.common.collect.Maps;
@@ -754,12 +754,13 @@ public abstract class BasePermissionsIT extends BaseTest {
           ResultSet rs = stmt.executeQuery(readTableSQL);
           assertNotNull(rs);
           int i = 0;
-          String explainPlan = Joiner.on(" ")
-            .join(((PhoenixStatement) stmt).getQueryPlan().getExplainPlan().getPlanSteps());
+          String scannedTable = ((PhoenixStatement) stmt).getQueryPlan().getExplainPlan()
+            .getPlanStepsAsAttributes().getTableName();
           rs = stmt.executeQuery(readTableSQL);
           if (tenantId != null) {
             rs.next();
-            assertFalse(explainPlan.contains("_IDX_"));
+            assertFalse("expected scanned table <" + scannedTable + "> to not be a view index",
+              scannedTable != null && scannedTable.contains("_IDX_"));
             assertEquals(((PhoenixConnection) conn).getTenantId().toString(), tenantId);
             // For tenant ID "o3", the value in table will be 3
             assertEquals(Character.toString(tenantId.charAt(1)), rs.getString(1));
@@ -796,9 +797,7 @@ public abstract class BasePermissionsIT extends BaseTest {
           ResultSet rs = stmt.executeQuery(readTableSQL);
           assertNotNull(rs);
           int i = 0;
-          String explainPlan = Joiner.on(" ")
-            .join(((PhoenixStatement) stmt).getQueryPlan().getExplainPlan().getPlanSteps());
-          assertTrue(explainPlan.contains("_IDX_"));
+          assertPlan(((PhoenixStatement) stmt).getQueryPlan()).tableContains("_IDX_");
           rs = stmt.executeQuery(readTableSQL);
           if (tenantId != null) {
             rs.next();
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseTenantSpecificViewIndexIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseTenantSpecificViewIndexIT.java
index 539d1316ed..1fab8de99b 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseTenantSpecificViewIndexIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseTenantSpecificViewIndexIT.java
@@ -17,8 +17,8 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.thirdparty.com.google.common.collect.Sets.newHashSet;
-import static org.junit.Assert.assertEquals;
 
 import java.sql.Connection;
 import java.sql.DriverManager;
@@ -29,9 +29,6 @@ import java.util.List;
 import java.util.Properties;
 import java.util.Set;
 import org.apache.hadoop.hbase.util.Pair;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.schema.types.PVarbinary;
 import org.apache.phoenix.util.PhoenixRuntime;
 import org.apache.phoenix.util.SchemaUtil;
@@ -159,22 +156,10 @@ public abstract class BaseTenantSpecificViewIndexIT extends SplitSystemCatalogIT
     } else {
       conn.createStatement().execute("CREATE INDEX " + indexName + " ON " + viewName + "(v2)");
     }
+    // sanity check that we can upsert after index is there
     conn.createStatement()
-      .execute("UPSERT INTO " + viewName + "(k2,v1,v2) VALUES (-1, 'blah', 'superblah')"); // sanity
-                                                                                           // check
-                                                                                           // that
-                                                                                           // we can
-                                                                                           // upsert
-                                                                                           // after
-                                                                                           // index
-                                                                                           // is
-                                                                                           // there
+      .execute("UPSERT INTO " + viewName + "(k2,v1,v2) VALUES (-1, 'blah', 'superblah')");
     conn.commit();
-    ExplainPlan plan = conn
-      .prepareStatement(
-        "SELECT k1, k2, v2 FROM " + viewName + " WHERE v2='" + valuePrefix + "v2-1'")
-      .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
     final String iteratorTypeAndScanSize;
     final String clientSortAlgo;
     final String expectedTableName;
@@ -209,42 +194,27 @@ public abstract class BaseTenantSpecificViewIndexIT extends SplitSystemCatalogIT
       }
       expectedTableName = "_IDX_" + tableName;
     }
-    assertEquals(iteratorTypeAndScanSize, explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(clientSortAlgo, explainPlanAttributes.getClientSortAlgo());
-    assertEquals(expectedTableName, explainPlanAttributes.getTableName());
-    assertEquals(keyRanges, explainPlanAttributes.getKeyRanges());
+    assertPlan(conn, "SELECT k1, k2, v2 FROM " + viewName + " WHERE v2='" + valuePrefix + "v2-1'")
+      .iteratorType(iteratorTypeAndScanSize).serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+      .scanType("RANGE SCAN").clientSortAlgo(clientSortAlgo).table(expectedTableName)
+      .keyRanges(keyRanges);
   }
 
   private void createAndVerifyIndexNonStringTenantId(Connection conn, String viewName,
     String tableName, String tenantId, String valuePrefix) throws SQLException {
     String indexName = generateUniqueName();
     conn.createStatement().execute("CREATE LOCAL INDEX " + indexName + " ON " + viewName + "(v2)");
+    // sanity check that we can upsert after index is there
     conn.createStatement()
-      .execute("UPSERT INTO " + viewName + "(k2,v1,v2) VALUES (-1, 'blah', 'superblah')"); // sanity
-                                                                                           // check
-                                                                                           // that
-                                                                                           // we can
-                                                                                           // upsert
-                                                                                           // after
-                                                                                           // index
-                                                                                           // is
-                                                                                           // there
+      .execute("UPSERT INTO " + viewName + "(k2,v1,v2) VALUES (-1, 'blah', 'superblah')");
     conn.commit();
-    ExplainPlan plan = conn
-      .prepareStatement(
-        "SELECT k1, k2, v2 FROM " + viewName + " WHERE v2='" + valuePrefix + "v2-1'")
-      .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(SchemaUtil.getTableName(SchemaUtil.getSchemaNameFromFullName(viewName), indexName)
-      + "(" + tableName + ")", explainPlanAttributes.getTableName());
-    assertEquals(" [1," + tenantId + ",'" + valuePrefix + "v2-1']",
-      explainPlanAttributes.getKeyRanges());
-    assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+    assertPlan(conn, "SELECT k1, k2, v2 FROM " + viewName + " WHERE v2='" + valuePrefix + "v2-1'")
+      .iteratorType("PARALLEL 1-WAY").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+      .scanType("RANGE SCAN")
+      .table(SchemaUtil.getTableName(SchemaUtil.getSchemaNameFromFullName(viewName), indexName)
+        + "(" + tableName + ")")
+      .keyRanges(" [1," + tenantId + ",'" + valuePrefix + "v2-1']")
+      .clientSortAlgo("CLIENT MERGE SORT");
   }
 
   private Connection createTenantConnection(String tenantId) throws SQLException {
@@ -253,7 +223,6 @@ public abstract class BaseTenantSpecificViewIndexIT extends SplitSystemCatalogIT
     return DriverManager.getConnection(getUrl(), props);
   }
 
-  @SuppressWarnings("unchecked")
   private void verifyViewData(Connection conn, String viewName, String valuePrefix)
     throws SQLException {
     String query = "SELECT k1, k2, v2 FROM " + viewName + " WHERE v2='" + valuePrefix + "v2-1'";
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseViewIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseViewIT.java
index 2ca630f113..3b3f6f81d4 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseViewIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseViewIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.analyzeTable;
 import static org.apache.phoenix.util.TestUtil.getAllSplits;
 import static org.junit.Assert.assertEquals;
@@ -38,10 +39,7 @@ import org.apache.hadoop.hbase.client.Scan;
 import org.apache.hadoop.hbase.client.Table;
 import org.apache.hadoop.hbase.util.Bytes;
 import org.apache.hadoop.hbase.util.Pair;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.jdbc.PhoenixConnection;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.jdbc.PhoenixStatement;
 import org.apache.phoenix.query.KeyRange;
 import org.apache.phoenix.util.MetaDataUtil;
@@ -200,9 +198,6 @@ public abstract class BaseViewIT extends ParallelStatsEnabledIT {
     assertEquals("bar", rs.getString(4));
     assertFalse(rs.next());
 
-    ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-      .optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
     String iteratorTypeAndScanSize;
     String clientSortAlgo;
     String expectedTableName;
@@ -226,12 +221,9 @@ public abstract class BaseViewIT extends ParallelStatsEnabledIT {
       clientSortAlgo = saltBuckets == null ? null : "CLIENT MERGE SORT";
       serverFilterBy = null;
     }
-    assertEquals(iteratorTypeAndScanSize, explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(expectedTableName, explainPlanAttributes.getTableName());
-    assertEquals(clientSortAlgo, explainPlanAttributes.getClientSortAlgo());
-    assertEquals(keyRanges, explainPlanAttributes.getKeyRanges());
-    assertEquals(serverFilterBy, explainPlanAttributes.getServerWhereFilter());
+    assertPlan(conn, query).iteratorType(iteratorTypeAndScanSize).scanType("RANGE SCAN")
+      .table(expectedTableName).clientSortAlgo(clientSortAlgo).keyRanges(keyRanges)
+      .serverWhereFilter(serverFilterBy);
 
     String viewIndexName2 = "I_" + generateUniqueName();
     if (localIndex) {
@@ -260,10 +252,6 @@ public abstract class BaseViewIT extends ParallelStatsEnabledIT {
     assertEquals("foo", rs.getString(3));
     assertFalse(rs.next());
 
-    plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-      .getExplainPlan();
-    explainPlanAttributes = plan.getPlanStepsAsAttributes();
-
     String physicalTableName;
     if (localIndex) {
       physicalTableName = fullTableName;
@@ -280,12 +268,9 @@ public abstract class BaseViewIT extends ParallelStatsEnabledIT {
           + (Short.MIN_VALUE + 1) + ",'foo']";
       clientSortAlgo = saltBuckets == null ? null : "CLIENT MERGE SORT";
     }
-    assertEquals(physicalTableName, explainPlanAttributes.getTableName());
-    assertEquals(iteratorTypeAndScanSize, explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(keyRanges, explainPlanAttributes.getKeyRanges());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals(clientSortAlgo, explainPlanAttributes.getClientSortAlgo());
+    assertPlan(conn, query).table(physicalTableName).iteratorType(iteratorTypeAndScanSize)
+      .scanType("RANGE SCAN").keyRanges(keyRanges)
+      .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").clientSortAlgo(clientSortAlgo);
 
     conn.close();
     return new Pair<>(physicalTableName, scan);
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/Bson4IT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/Bson4IT.java
index 315932bdd0..7c2b93f4d3 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/Bson4IT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/Bson4IT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
@@ -43,7 +44,6 @@ import org.apache.commons.io.FileUtils;
 import org.apache.hadoop.hbase.util.Bytes;
 import org.apache.hadoop.hbase.util.Pair;
 import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.exception.SQLExceptionCode;
 import org.apache.phoenix.hbase.index.metrics.GlobalIndexCheckerSource;
 import org.apache.phoenix.hbase.index.metrics.GlobalIndexCheckerSourceImpl;
@@ -1188,21 +1188,15 @@ public class Bson4IT extends ParallelStatsDisabledIT {
 
   private static void validateExplainPlan(PreparedStatement ps, String tableName, String scanType)
     throws SQLException {
-    ExplainPlan plan = ps.unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    validatePlan(tableName, scanType, plan);
+    assertPlan(ps.unwrap(PhoenixPreparedStatement.class)).table(tableName)
+      .iteratorType("PARALLEL 1-WAY").scanType(scanType);
   }
 
   private static void validateExplainPlan(Statement stmt, String query, String tableName,
     String scanType) throws SQLException {
     ExplainPlan plan = stmt.unwrap(PhoenixStatement.class).optimizeQuery(query).getExplainPlan();
-    validatePlan(tableName, scanType, plan);
-  }
-
-  private static void validatePlan(String tableName, String scanType, ExplainPlan plan) {
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals(scanType, explainPlanAttributes.getExplainScanType());
+    assertPlan(plan.getPlanStepsAsAttributes()).table(tableName).iteratorType("PARALLEL 1-WAY")
+      .scanType(scanType);
   }
 
 }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/Bson5IT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/Bson5IT.java
index eea0ca8efe..0b7d4be140 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/Bson5IT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/Bson5IT.java
@@ -20,6 +20,7 @@ package org.apache.phoenix.end2end;
 import static org.apache.phoenix.hbase.index.IndexCDCConsumer.INDEX_CDC_CONSUMER_RETRY_PAUSE_MS;
 import static org.apache.phoenix.hbase.index.IndexCDCConsumer.INDEX_CDC_CONSUMER_TIMESTAMP_BUFFER_MS;
 import static org.apache.phoenix.hbase.index.IndexRegionObserver.PHOENIX_INDEX_CDC_MUTATION_SERIALIZE;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -43,8 +44,6 @@ import java.util.Map;
 import java.util.Properties;
 import org.apache.commons.io.FileUtils;
 import org.apache.hadoop.hbase.util.Bytes;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
 import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.QueryConstants;
@@ -600,6 +599,7 @@ public class Bson5IT extends ParallelStatsDisabledIT {
     }
   }
 
+  @SuppressWarnings("unchecked")
   private static void testCDCAfterFirstUpsert(Connection conn, String cdcName, Timestamp ts1,
     Timestamp ts2, BsonDocument bsonDocument1, BsonDocument bsonDocument2,
     BsonDocument bsonDocument3) throws SQLException, JsonProcessingException {
@@ -650,6 +650,7 @@ public class Bson5IT extends ParallelStatsDisabledIT {
     }
   }
 
+  @SuppressWarnings("unchecked")
   private static void testCDCPostUpdate(Connection conn, String cdcName, Timestamp ts1,
     Timestamp ts2, BsonDocument bsonDocument1, BsonDocument bsonDocument2,
     BsonDocument bsonDocument3) throws SQLException, IOException {
@@ -716,6 +717,7 @@ public class Bson5IT extends ParallelStatsDisabledIT {
     }
   }
 
+  @SuppressWarnings("unchecked")
   private static void testCDCUpdateOneRowChange(Connection conn, String cdcName, Timestamp ts1,
     Timestamp ts2, BsonDocument bsonDocument1) throws SQLException, IOException {
     try (
@@ -747,11 +749,8 @@ public class Bson5IT extends ParallelStatsDisabledIT {
 
   private static void validateExplainPlan(PreparedStatement ps, String tableName, String scanType)
     throws SQLException {
-    ExplainPlan plan = ps.unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals(scanType, explainPlanAttributes.getExplainScanType());
+    assertPlan(ps.unwrap(PhoenixPreparedStatement.class)).table(tableName)
+      .iteratorType("PARALLEL 1-WAY").scanType(scanType);
   }
 
 }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/CDCQueryIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/CDCQueryIT.java
index 0076ee171f..b15e240347 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/CDCQueryIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/CDCQueryIT.java
@@ -25,10 +25,12 @@ import static org.apache.phoenix.mapreduce.index.PhoenixIndexToolJobCounters.BEF
 import static org.apache.phoenix.mapreduce.index.PhoenixIndexToolJobCounters.BEFORE_REBUILD_UNKNOWN_INDEX_ROW_COUNT;
 import static org.apache.phoenix.mapreduce.index.PhoenixIndexToolJobCounters.REBUILT_INDEX_ROW_COUNT;
 import static org.apache.phoenix.query.QueryConstants.CDC_EVENT_TYPE;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.getExplainAttributes;
 import static org.apache.phoenix.schema.PTable.QualifierEncodingScheme.NON_ENCODED_QUALIFIERS;
 import static org.apache.phoenix.schema.PTable.QualifierEncodingScheme.TWO_BYTE_QUALIFIERS;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 
 import java.sql.Connection;
@@ -53,6 +55,7 @@ import org.apache.hadoop.hbase.client.Scan;
 import org.apache.hadoop.hbase.client.Table;
 import org.apache.hadoop.hbase.filter.Filter;
 import org.apache.hadoop.hbase.filter.FilterList;
+import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
 import org.apache.phoenix.filter.DistinctPrefixFilter;
 import org.apache.phoenix.iterate.ResultIterator;
@@ -66,7 +69,6 @@ import org.apache.phoenix.schema.PTable;
 import org.apache.phoenix.util.CDCUtil;
 import org.apache.phoenix.util.EnvironmentEdgeManager;
 import org.apache.phoenix.util.ManualEnvironmentEdge;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.ReadOnlyProps;
 import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.TestUtil;
@@ -156,10 +158,13 @@ public class CDCQueryIT extends CDCBaseIT {
 
   private void cdcIndexShouldNotBeUsedForDataTableQueries(Connection conn, String dataTableName,
     String cdcName) throws Exception {
-    ResultSet rs = conn.createStatement().executeQuery(
-      "EXPLAIN SELECT * FROM " + dataTableName + " WHERE PHOENIX_ROW_TIMESTAMP() < CURRENT_TIME()");
-    String explainPlan = QueryUtil.getExplainPlan(rs);
-    assertFalse(explainPlan.contains(cdcName));
+    String sql =
+      "SELECT * FROM " + dataTableName + " WHERE PHOENIX_ROW_TIMESTAMP() < CURRENT_TIME()";
+    ExplainPlanAttributes attributes = getExplainAttributes(conn, sql);
+    String scannedTable = attributes.getTableName();
+    assertNotNull(scannedTable);
+    assertFalse("CDC index " + cdcName + " should not be used, but plan scanned " + scannedTable,
+      scannedTable.contains(cdcName));
   }
 
   private boolean isDistinctPrefixFilterIncludedInFilterList(FilterList filterList) {
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/CastAndCoerceIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/CastAndCoerceIT.java
index 6f80b4b6fb..1d1203c17b 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/CastAndCoerceIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/CastAndCoerceIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.ROW1;
 import static org.apache.phoenix.util.TestUtil.ROW7;
 import static org.apache.phoenix.util.TestUtil.ROW9;
@@ -32,8 +33,6 @@ import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.util.Collection;
 import java.util.Properties;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.util.PropertiesUtil;
 import org.junit.Test;
@@ -164,12 +163,8 @@ public class CastAndCoerceIT extends BaseQueryIT {
       assertEquals(ROW9, rs.getString(1));
       assertFalse(rs.next());
 
-      ExplainPlan plan =
-        statement.unwrap(PhoenixPreparedStatement.class).optimizeQuery(query).getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals(tableName, explainPlanAttributes.getTableName());
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
+      assertPlan(statement.unwrap(PhoenixPreparedStatement.class)).table(tableName)
+        .iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN");
     }
   }
 
@@ -187,12 +182,8 @@ public class CastAndCoerceIT extends BaseQueryIT {
       assertEquals(ROW9, rs.getString(1));
       assertFalse(rs.next());
 
-      ExplainPlan plan =
-        statement.unwrap(PhoenixPreparedStatement.class).optimizeQuery(query).getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals(tableName, explainPlanAttributes.getTableName());
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
+      assertPlan(statement.unwrap(PhoenixPreparedStatement.class)).table(tableName)
+        .iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN");
     }
   }
 
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ClientHashAggregateIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ClientHashAggregateIT.java
index 9bf4caebe7..ab4333efa7 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ClientHashAggregateIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ClientHashAggregateIT.java
@@ -17,9 +17,12 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.getExplainAttributes;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 
 import java.sql.Connection;
@@ -28,8 +31,8 @@ import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.Statement;
 import java.util.Properties;
+import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
@@ -113,13 +116,15 @@ public class ClientHashAggregateIT extends ParallelStatsDisabledIT {
   private void verifyExplain(Connection conn, String table, boolean swap, boolean sort)
     throws Exception {
 
-    String query = "EXPLAIN " + getQuery(table, true, swap, sort);
-    Statement stmt = conn.createStatement();
-    ResultSet rs = stmt.executeQuery(query);
-    String plan = QueryUtil.getExplainPlan(rs);
-    rs.close();
-    assertTrue(plan != null && plan.contains("CLIENT HASH AGGREGATE"));
-    assertTrue(plan != null && (sort == plan.contains("CLIENT SORTED BY")));
+    String query = getQuery(table, true, swap, sort);
+    ExplainPlanAttributes attributes = getExplainAttributes(conn, query);
+    assertNotNull(attributes.getClientAggregate());
+    assertTrue(attributes.getClientAggregate().contains("CLIENT HASH AGGREGATE"));
+    if (sort) {
+      assertNotNull(attributes.getClientSortedBy());
+    } else {
+      assertNull(attributes.getClientSortedBy());
+    }
   }
 
   private void verifyResults(Connection conn, String table, int c1, int c2, boolean swap,
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/CostBasedDecisionIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/CostBasedDecisionIT.java
index 2acfd94ca7..e2bd9a66ed 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/CostBasedDecisionIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/CostBasedDecisionIT.java
@@ -17,14 +17,14 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertMutationPlan;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
 
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.PreparedStatement;
-import java.sql.ResultSet;
 import java.util.Map;
 import java.util.Properties;
 import org.apache.phoenix.compile.ExplainPlan;
@@ -33,7 +33,6 @@ import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.BaseTest;
 import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.ReadOnlyProps;
 import org.junit.BeforeClass;
 import org.junit.Test;
@@ -79,7 +78,7 @@ public class CostBasedDecisionIT extends BaseTest {
       String query =
         "SELECT rowkey, c1, c2 FROM " + tableName + " where c1 LIKE 'X0%' ORDER BY rowkey";
       // Use the data table plan that opts out order-by when stats are not available.
-      verifyQueryPlan(query, "FULL SCAN");
+      assertPlan(conn, query).scanType("FULL SCAN");
 
       PreparedStatement stmt =
         conn.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2) VALUES (?, ?, ?)");
@@ -94,7 +93,7 @@ public class CostBasedDecisionIT extends BaseTest {
       conn.createStatement().execute("UPDATE STATISTICS " + tableName);
 
       // Use the index table plan that has a lower cost when stats become available.
-      verifyQueryPlan(query, "RANGE SCAN");
+      assertPlan(conn, query).scanType("RANGE SCAN");
     } finally {
       conn.close();
     }
@@ -237,11 +236,12 @@ public class CostBasedDecisionIT extends BaseTest {
       String query = "UPSERT INTO " + tableName + " SELECT * FROM " + tableName
         + " where c1 BETWEEN 10 AND 20 AND c2 < 9000 AND C3 < 5000";
       // Use the idx2 plan with a wider PK slot span when stats are not available.
-      verifyQueryPlan(query,
-        "UPSERT SELECT\n" + "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexName2 + "(" + tableName
-          + ")" + " [2,*] - [2,9,000]\n"
-          + "    SERVER FILTER BY ((\"C1\" >= 10 AND \"C1\" <= 20) AND TO_INTEGER(\"C3\") < 5000)\n"
-          + "CLIENT MERGE SORT");
+      assertMutationPlan(conn, query).abstractExplainPlan("UPSERT SELECT").iteratorType("PARALLEL")
+        .scanType("RANGE SCAN").table(indexName2 + "(" + tableName + ")")
+        .keyRanges(" [2,*] - [2,9,000]")
+        .serverWhereFilter(
+          "SERVER FILTER BY ((\"C1\" >= 10 AND \"C1\" <= 20) AND TO_INTEGER(\"C3\") < 5000)")
+        .clientSortAlgo("CLIENT MERGE SORT");
 
       PreparedStatement stmt = conn
         .prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2, c3) VALUES (?, ?, ?, ?)");
@@ -256,10 +256,11 @@ public class CostBasedDecisionIT extends BaseTest {
       conn.createStatement().execute("UPDATE STATISTICS " + tableName);
 
       // Use the idx2 plan that scans less data when stats become available.
-      verifyQueryPlan(query,
-        "UPSERT SELECT\n" + "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexName1 + "(" + tableName
-          + ")" + " [1,10] - [1,20]\n" + "    SERVER FILTER BY (\"C2\" < 9000 AND \"C3\" < 5000)\n"
-          + "CLIENT MERGE SORT");
+      assertMutationPlan(conn, query).abstractExplainPlan("UPSERT SELECT").iteratorType("PARALLEL")
+        .scanType("RANGE SCAN").table(indexName1 + "(" + tableName + ")")
+        .keyRanges(" [1,10] - [1,20]")
+        .serverWhereFilter("SERVER FILTER BY (\"C2\" < 9000 AND \"C3\" < 5000)")
+        .clientSortAlgo("CLIENT MERGE SORT");
     } finally {
       conn.close();
     }
@@ -284,11 +285,12 @@ public class CostBasedDecisionIT extends BaseTest {
       String query =
         "DELETE FROM " + tableName + " where c1 BETWEEN 10 AND 20 AND c2 < 9000 AND C3 < 5000";
       // Use the idx2 plan with a wider PK slot span when stats are not available.
-      verifyQueryPlan(query,
-        "DELETE ROWS CLIENT SELECT\n" + "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexName2 + "("
-          + tableName + ")" + " [2,*] - [2,9,000]\n"
-          + "    SERVER FILTER BY ((\"C1\" >= 10 AND \"C1\" <= 20) AND TO_INTEGER(\"C3\") < 5000)\n"
-          + "CLIENT MERGE SORT");
+      assertMutationPlan(conn, query).abstractExplainPlan("DELETE ROWS CLIENT SELECT")
+        .iteratorType("PARALLEL").scanType("RANGE SCAN").table(indexName2 + "(" + tableName + ")")
+        .keyRanges(" [2,*] - [2,9,000]")
+        .serverWhereFilter(
+          "SERVER FILTER BY ((\"C1\" >= 10 AND \"C1\" <= 20) AND TO_INTEGER(\"C3\") < 5000)")
+        .clientSortAlgo("CLIENT MERGE SORT");
 
       PreparedStatement stmt = conn
         .prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2, c3) VALUES (?, ?, ?, ?)");
@@ -303,10 +305,11 @@ public class CostBasedDecisionIT extends BaseTest {
       conn.createStatement().execute("UPDATE STATISTICS " + tableName);
 
       // Use the idx2 plan that scans less data when stats become available.
-      verifyQueryPlan(query,
-        "DELETE ROWS CLIENT SELECT\n" + "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexName1 + "("
-          + tableName + ")" + " [1,10] - [1,20]\n"
-          + "    SERVER FILTER BY (\"C2\" < 9000 AND \"C3\" < 5000)\n" + "CLIENT MERGE SORT");
+      assertMutationPlan(conn, query).abstractExplainPlan("DELETE ROWS CLIENT SELECT")
+        .iteratorType("PARALLEL").scanType("RANGE SCAN").table(indexName1 + "(" + tableName + ")")
+        .keyRanges(" [1,10] - [1,20]")
+        .serverWhereFilter("SERVER FILTER BY (\"C2\" < 9000 AND \"C3\" < 5000)")
+        .clientSortAlgo("CLIENT MERGE SORT");
     } finally {
       conn.close();
     }
@@ -329,12 +332,13 @@ public class CostBasedDecisionIT extends BaseTest {
         + " where rowkey <= 'z' GROUP BY c1 " + "UNION ALL SELECT c1, max(rowkey), max(c2) FROM "
         + tableName + " where rowkey >= 'a' GROUP BY c1";
       // Use the default plan when stats are not available.
-      verifyQueryPlan(query,
-        "UNION ALL OVER 2 QUERIES\n" + "    CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName
-          + " [*] - ['z']\n" + "        SERVER AGGREGATE INTO DISTINCT ROWS BY [C1]\n"
-          + "    CLIENT MERGE SORT\n" + "    CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName
-          + " ['a'] - [*]\n" + "        SERVER AGGREGATE INTO DISTINCT ROWS BY [C1]\n"
-          + "    CLIENT MERGE SORT");
+      assertPlan(conn, query).abstractExplainPlan("UNION ALL OVER 2 QUERIES")
+        .iteratorType("PARALLEL").scanType("RANGE SCAN").table(tableName).keyRanges(" [*] - ['z']")
+        .serverAggregate("SERVER AGGREGATE INTO DISTINCT ROWS BY [C1]")
+        .clientSortAlgo("CLIENT MERGE SORT").rhs().iteratorType("PARALLEL").scanType("RANGE SCAN")
+        .table(tableName).keyRanges(" ['a'] - [*]")
+        .serverAggregate("SERVER AGGREGATE INTO DISTINCT ROWS BY [C1]")
+        .clientSortAlgo("CLIENT MERGE SORT");
 
       PreparedStatement stmt =
         conn.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2) VALUES (?, ?, ?)");
@@ -349,16 +353,16 @@ public class CostBasedDecisionIT extends BaseTest {
       conn.createStatement().execute("UPDATE STATISTICS " + tableName);
 
       // Use the optimal plan based on cost when stats become available.
-      verifyQueryPlan(query,
-        "UNION ALL OVER 2 QUERIES\n" + "    CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexName
-          + "(" + tableName + ") [1]\n" + "        SERVER MERGE [0.C2]\n"
-          + "        SERVER FILTER BY FIRST KEY ONLY AND \"ROWKEY\" <= 'z'\n"
-          + "        SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [\"C1\"]\n"
-          + "    CLIENT MERGE SORT\n" + "    CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexName
-          + "(" + tableName + ") [1]\n" + "        SERVER MERGE [0.C2]\n"
-          + "        SERVER FILTER BY FIRST KEY ONLY AND \"ROWKEY\" >= 'a'\n"
-          + "        SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [\"C1\"]\n"
-          + "    CLIENT MERGE SORT");
+      assertPlan(conn, query).abstractExplainPlan("UNION ALL OVER 2 QUERIES")
+        .iteratorType("PARALLEL").scanType("RANGE SCAN").table(indexName + "(" + tableName + ")")
+        .keyRanges(" [1]").serverMergeColumns("[0.C2]")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY AND \"ROWKEY\" <= 'z'")
+        .serverAggregate("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [\"C1\"]")
+        .clientSortAlgo("CLIENT MERGE SORT").rhs().iteratorType("PARALLEL").scanType("RANGE SCAN")
+        .table(indexName + "(" + tableName + ")").keyRanges(" [1]").serverMergeColumns("[0.C2]")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY AND \"ROWKEY\" >= 'a'")
+        .serverAggregate("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [\"C1\"]")
+        .clientSortAlgo("CLIENT MERGE SORT");
     } finally {
       conn.close();
     }
@@ -382,12 +386,13 @@ public class CostBasedDecisionIT extends BaseTest {
         + " where rowkey <= 'z' GROUP BY c1) t2 "
         + "ON t1.rowkey = t2.mrk WHERE t1.c1 LIKE 'X0%' ORDER BY t1.rowkey";
       // Use the default plan when stats are not available.
-      verifyQueryPlan(query,
-        "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + tableName + "\n"
-          + "    SERVER FILTER BY C1 LIKE 'X0%'\n" + "    PARALLEL INNER-JOIN TABLE 0\n"
-          + "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " [*] - ['z']\n"
-          + "            SERVER AGGREGATE INTO DISTINCT ROWS BY [C1]\n"
-          + "        CLIENT MERGE SORT\n" + "    DYNAMIC SERVER FILTER BY T1.ROWKEY IN (T2.MRK)");
+      assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").table(tableName)
+        .serverWhereFilter("SERVER FILTER BY C1 LIKE 'X0%'")
+        .dynamicServerFilter("DYNAMIC SERVER FILTER BY T1.ROWKEY IN (T2.MRK)").subPlanCount(1)
+        .subPlan(0).abstractExplainPlan("PARALLEL INNER-JOIN TABLE 0")
+        .iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN").table(tableName)
+        .keyRanges(" [*] - ['z']").serverAggregate("SERVER AGGREGATE INTO DISTINCT ROWS BY [C1]")
+        .clientSortAlgo("CLIENT MERGE SORT");
 
       PreparedStatement stmt =
         conn.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2) VALUES (?, ?, ?)");
@@ -402,17 +407,17 @@ public class CostBasedDecisionIT extends BaseTest {
       conn.createStatement().execute("UPDATE STATISTICS " + tableName);
 
       // Use the optimal plan based on cost when stats become available.
-      verifyQueryPlan(query,
-        "CLIENT PARALLEL 626-WAY RANGE SCAN OVER " + indexName + "(" + tableName
-          + ") [1,'X0'] - [1,'X1']\n" + "    SERVER MERGE [0.C2]\n"
-          + "    SERVER FILTER BY FIRST KEY ONLY\n" + "    SERVER SORTED BY [\"T1.:ROWKEY\"]\n"
-          + "CLIENT MERGE SORT\n" + "    PARALLEL INNER-JOIN TABLE 0\n"
-          + "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexName + "(" + tableName
-          + ") [1]\n" + "            SERVER MERGE [0.C2]\n"
-          + "            SERVER FILTER BY FIRST KEY ONLY AND \"ROWKEY\" <= 'z'\n"
-          + "            SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [\"C1\"]\n"
-          + "        CLIENT MERGE SORT\n"
-          + "    DYNAMIC SERVER FILTER BY \"T1.:ROWKEY\" IN (T2.MRK)");
+      assertPlan(conn, query).iteratorType("PARALLEL 626-WAY").scanType("RANGE SCAN")
+        .table(indexName + "(" + tableName + ")").keyRanges(" [1,'X0'] - [1,'X1']")
+        .serverMergeColumns("[0.C2]").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .serverSortedBy("[\"T1.:ROWKEY\"]").clientSortAlgo("CLIENT MERGE SORT")
+        .dynamicServerFilter("DYNAMIC SERVER FILTER BY \"T1.:ROWKEY\" IN (T2.MRK)").subPlanCount(1)
+        .subPlan(0).abstractExplainPlan("PARALLEL INNER-JOIN TABLE 0")
+        .iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+        .table(indexName + "(" + tableName + ")").keyRanges(" [1]").serverMergeColumns("[0.C2]")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY AND \"ROWKEY\" <= 'z'")
+        .serverAggregate("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [\"C1\"]")
+        .clientSortAlgo("CLIENT MERGE SORT");
     } finally {
       conn.close();
     }
@@ -479,17 +484,9 @@ public class CostBasedDecisionIT extends BaseTest {
       + "ON t1.ID = t2.ID";
     Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
     try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
-      ExplainPlan plan = conn.prepareStatement(q).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("SORT-MERGE-JOIN (INNER)", explainPlanAttributes.getAbstractExplainPlan());
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(testTable500, explainPlanAttributes.getTableName());
-      ExplainPlanAttributes rhsTable = explainPlanAttributes.getRhsJoinQueryExplainPlan();
-      assertEquals("PARALLEL 1-WAY", rhsTable.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", rhsTable.getExplainScanType());
-      assertEquals(testTable1000, rhsTable.getTableName());
+      assertPlan(conn, q).abstractExplainPlan("SORT-MERGE-JOIN (INNER)").lhs()
+        .iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").table(testTable500).end().rhs()
+        .iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").table(testTable1000);
     }
   }
 
@@ -502,20 +499,11 @@ public class CostBasedDecisionIT extends BaseTest {
       + "ON t1.ID = t2.ID\n" + "WHERE t1.COL1 < 200";
     Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
     try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
-      ExplainPlan plan = conn.prepareStatement(q).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("SORT-MERGE-JOIN (INNER)", explainPlanAttributes.getAbstractExplainPlan());
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals("SERVER FILTER BY COL1 < 200", explainPlanAttributes.getServerWhereFilter());
-      assertEquals(testTable500, explainPlanAttributes.getTableName());
-      assertEquals("CLIENT AGGREGATE INTO SINGLE ROW", explainPlanAttributes.getClientAggregate());
-      ExplainPlanAttributes rhsTable = explainPlanAttributes.getRhsJoinQueryExplainPlan();
-      assertEquals("PARALLEL 1-WAY", rhsTable.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", rhsTable.getExplainScanType());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", rhsTable.getServerWhereFilter());
-      assertEquals(testTable1000, rhsTable.getTableName());
+      assertPlan(conn, q).abstractExplainPlan("SORT-MERGE-JOIN (INNER)")
+        .clientAggregate("CLIENT AGGREGATE INTO SINGLE ROW").lhs().iteratorType("PARALLEL 1-WAY")
+        .scanType("FULL SCAN").table(testTable500).serverWhereFilter("SERVER FILTER BY COL1 < 200")
+        .end().rhs().iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").table(testTable1000)
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY");
     }
   }
 
@@ -524,10 +512,14 @@ public class CostBasedDecisionIT extends BaseTest {
   public void testJoinStrategy3() throws Exception {
     String q = "SELECT *\n" + "FROM " + testTable500 + " t1 JOIN " + testTable1000 + " t2\n"
       + "ON t1.COL1 = t2.ID\n" + "WHERE t1.ID > 200";
-    String expected = "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable1000 + "\n"
-      + "    PARALLEL INNER-JOIN TABLE 0\n" + "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER "
-      + testTable500 + " [201] - [*]\n" + "    DYNAMIC SERVER FILTER BY T2.ID IN (T1.COL1)";
-    verifyQueryPlan(q, expected);
+    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+    try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+      assertPlan(conn, q).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").table(testTable1000)
+        .dynamicServerFilter("DYNAMIC SERVER FILTER BY T2.ID IN (T1.COL1)").subPlanCount(1)
+        .subPlan(0).abstractExplainPlan("PARALLEL INNER-JOIN TABLE 0")
+        .iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN").table(testTable500)
+        .keyRanges(" [201] - [*]");
+    }
   }
 
   /**
@@ -538,10 +530,13 @@ public class CostBasedDecisionIT extends BaseTest {
   public void testJoinStrategy4() throws Exception {
     String q = "SELECT *\n" + "FROM " + testTable990 + " t1 JOIN " + testTable1000 + " t2\n"
       + "ON t1.ID = t2.COL1";
-    String expected = "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable990 + "\n"
-      + "    PARALLEL INNER-JOIN TABLE 0\n" + "        CLIENT PARALLEL 1-WAY FULL SCAN OVER "
-      + testTable1000 + "\n" + "    DYNAMIC SERVER FILTER BY T1.ID IN (T2.COL1)";
-    verifyQueryPlan(q, expected);
+    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+    try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+      assertPlan(conn, q).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").table(testTable990)
+        .dynamicServerFilter("DYNAMIC SERVER FILTER BY T1.ID IN (T2.COL1)").subPlanCount(1)
+        .subPlan(0).abstractExplainPlan("PARALLEL INNER-JOIN TABLE 0")
+        .iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").table(testTable1000);
+    }
   }
 
   /** Hash-join wins over sort-merge-join w/ smaller side ordered. */
@@ -549,10 +544,13 @@ public class CostBasedDecisionIT extends BaseTest {
   public void testJoinStrategy5() throws Exception {
     String q = "SELECT *\n" + "FROM " + testTable500 + " t1 JOIN " + testTable1000 + " t2\n"
       + "ON t1.ID = t2.COL1\n" + "WHERE t1.ID > 200";
-    String expected = "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable1000 + "\n"
-      + "    PARALLEL INNER-JOIN TABLE 0\n" + "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER "
-      + testTable500 + " [201] - [*]";
-    verifyQueryPlan(q, expected);
+    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+    try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+      assertPlan(conn, q).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").table(testTable1000)
+        .subPlanCount(1).subPlan(0).abstractExplainPlan("PARALLEL INNER-JOIN TABLE 0")
+        .iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN").table(testTable500)
+        .keyRanges(" [201] - [*]");
+    }
   }
 
   /** Hash-join wins over sort-merge-join w/o any side ordered. */
@@ -560,10 +558,13 @@ public class CostBasedDecisionIT extends BaseTest {
   public void testJoinStrategy6() throws Exception {
     String q = "SELECT *\n" + "FROM " + testTable500 + " t1 JOIN " + testTable1000 + " t2\n"
       + "ON t1.COL1 = t2.COL1\n" + "WHERE t1.ID > 200";
-    String expected = "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable1000 + "\n"
-      + "    PARALLEL INNER-JOIN TABLE 0\n" + "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER "
-      + testTable500 + " [201] - [*]";
-    verifyQueryPlan(q, expected);
+    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+    try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+      assertPlan(conn, q).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").table(testTable1000)
+        .subPlanCount(1).subPlan(0).abstractExplainPlan("PARALLEL INNER-JOIN TABLE 0")
+        .iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN").table(testTable500)
+        .keyRanges(" [201] - [*]");
+    }
   }
 
   /**
@@ -575,11 +576,14 @@ public class CostBasedDecisionIT extends BaseTest {
   public void testJoinStrategy7() throws Exception {
     String q = "SELECT *\n" + "FROM " + testTable500 + " t1 JOIN " + testTable1000 + " t2\n"
       + "ON t1.ID = t2.ID\n" + "ORDER BY t1.COL1";
-    String expected = "CLIENT PARALLEL 1001-WAY FULL SCAN OVER " + testTable1000 + "\n"
-      + "    SERVER SORTED BY [T1.COL1]\n" + "CLIENT MERGE SORT\n"
-      + "    PARALLEL INNER-JOIN TABLE 0\n" + "        CLIENT PARALLEL 1-WAY FULL SCAN OVER "
-      + testTable500 + "\n" + "    DYNAMIC SERVER FILTER BY T2.ID IN (T1.ID)";
-    verifyQueryPlan(q, expected);
+    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+    try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+      assertPlan(conn, q).iteratorType("PARALLEL 1001-WAY").scanType("FULL SCAN")
+        .table(testTable1000).serverSortedBy("[T1.COL1]").clientSortAlgo("CLIENT MERGE SORT")
+        .dynamicServerFilter("DYNAMIC SERVER FILTER BY T2.ID IN (T1.ID)").subPlanCount(1).subPlan(0)
+        .abstractExplainPlan("PARALLEL INNER-JOIN TABLE 0").iteratorType("PARALLEL 1-WAY")
+        .scanType("FULL SCAN").table(testTable500);
+    }
   }
 
   /**
@@ -593,19 +597,10 @@ public class CostBasedDecisionIT extends BaseTest {
       + "ON t1.ID = t2.ID\n" + "ORDER BY t1.COL1 LIMIT 5";
     Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
     try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
-      ExplainPlan plan = conn.prepareStatement(q).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("SORT-MERGE-JOIN (INNER)", explainPlanAttributes.getAbstractExplainPlan());
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(testTable500, explainPlanAttributes.getTableName());
-      assertEquals("[T1.COL1]", explainPlanAttributes.getClientSortedBy());
-      assertEquals(new Integer(5), explainPlanAttributes.getClientRowLimit());
-      ExplainPlanAttributes rhsTable = explainPlanAttributes.getRhsJoinQueryExplainPlan();
-      assertEquals("PARALLEL 1-WAY", rhsTable.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", rhsTable.getExplainScanType());
-      assertEquals(testTable1000, rhsTable.getTableName());
+      assertPlan(conn, q).abstractExplainPlan("SORT-MERGE-JOIN (INNER)").clientSortedBy("[T1.COL1]")
+        .clientRowLimit(5).lhs().iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+        .table(testTable500).end().rhs().iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+        .table(testTable1000);
     }
   }
 
@@ -617,11 +612,15 @@ public class CostBasedDecisionIT extends BaseTest {
     String q = "SELECT *\n" + "FROM " + testTable1000 + " t1 LEFT JOIN " + testTable500 + " t2\n"
       + "ON t1.ID = t2.ID AND t2.ID > 200\n" + "LEFT JOIN " + testTable990 + " t3\n"
       + "ON t1.ID = t3.ID AND t3.ID < 100";
-    String expected = "SORT-MERGE-JOIN (LEFT) TABLES\n" + "    SORT-MERGE-JOIN (LEFT) TABLES\n"
-      + "        CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable1000 + "\n" + "    AND\n"
-      + "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable500 + " [201] - [*]\n" + "AND\n"
-      + "    CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable990 + " [*] - [100]";
-    verifyQueryPlan(q, expected);
+    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+    try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+      assertPlan(conn, q).abstractExplainPlan("SORT-MERGE-JOIN (LEFT)").lhs()
+        .abstractExplainPlan("SORT-MERGE-JOIN (LEFT)").lhs().iteratorType("PARALLEL 1-WAY")
+        .scanType("FULL SCAN").table(testTable1000).end().rhs().iteratorType("PARALLEL 1-WAY")
+        .scanType("RANGE SCAN").table(testTable500).keyRanges(" [201] - [*]").end().end().rhs()
+        .iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN").table(testTable990)
+        .keyRanges(" [*] - [100]");
+    }
   }
 
   /**
@@ -632,13 +631,16 @@ public class CostBasedDecisionIT extends BaseTest {
     String q = "SELECT *\n" + "FROM " + testTable1000 + " t1 JOIN " + testTable500 + " t2\n"
       + "ON t1.ID = t2.COL1 AND t2.ID > 200\n" + "JOIN " + testTable990 + " t3\n"
       + "ON t1.ID = t3.ID AND t3.ID < 100";
-    String expected =
-      "SORT-MERGE-JOIN (INNER) TABLES\n" + "    CLIENT PARALLEL 1-WAY FULL SCAN OVER "
-        + testTable1000 + "\n" + "        PARALLEL INNER-JOIN TABLE 0\n"
-        + "            CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable500 + " [201] - [*]\n"
-        + "        DYNAMIC SERVER FILTER BY T1.ID IN (T2.COL1)\n" + "AND\n"
-        + "    CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable990 + " [*] - [100]";
-    verifyQueryPlan(q, expected);
+    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+    try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+      assertPlan(conn, q).abstractExplainPlan("SORT-MERGE-JOIN (INNER)").lhs()
+        .iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").table(testTable1000)
+        .dynamicServerFilter("DYNAMIC SERVER FILTER BY T1.ID IN (T2.COL1)").subPlanCount(1)
+        .subPlan(0).abstractExplainPlan("PARALLEL INNER-JOIN TABLE 0")
+        .iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN").table(testTable500)
+        .keyRanges(" [201] - [*]").end().end().rhs().iteratorType("PARALLEL 1-WAY")
+        .scanType("RANGE SCAN").table(testTable990).keyRanges(" [*] - [100]");
+    }
   }
 
   /**
@@ -650,11 +652,15 @@ public class CostBasedDecisionIT extends BaseTest {
     String q = "SELECT *\n" + "FROM " + testTable1000 + " t1 JOIN " + testTable500 + " t2\n"
       + "ON t1.COL2 = t2.COL1 AND t2.ID > 200\n" + "JOIN " + testTable990 + " t3\n"
       + "ON t1.COL1 = t3.COL2 AND t3.ID < 100";
-    String expected = "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable1000 + "\n"
-      + "    PARALLEL INNER-JOIN TABLE 0\n" + "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER "
-      + testTable500 + " [201] - [*]\n" + "    PARALLEL INNER-JOIN TABLE 1\n"
-      + "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable990 + " [*] - [100]";
-    verifyQueryPlan(q, expected);
+    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+    try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+      assertPlan(conn, q).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").table(testTable1000)
+        .subPlanCount(2).subPlan(0).abstractExplainPlan("PARALLEL INNER-JOIN TABLE 0")
+        .iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN").table(testTable500)
+        .keyRanges(" [201] - [*]").end().subPlan(1)
+        .abstractExplainPlan("PARALLEL INNER-JOIN TABLE 1").iteratorType("PARALLEL 1-WAY")
+        .scanType("RANGE SCAN").table(testTable990).keyRanges(" [*] - [100]");
+    }
   }
 
   /**
@@ -665,22 +671,16 @@ public class CostBasedDecisionIT extends BaseTest {
   public void testJoinStrategy12() throws Exception {
     String q = "SELECT *\n" + "FROM " + testTable1000 + " t1 JOIN " + testTable990 + " t2\n"
       + "ON t1.COL2 = t2.COL1\n" + "JOIN " + testTable990 + " t3\n" + "ON t1.COL1 = t3.COL2";
-    String expected =
-      "SORT-MERGE-JOIN (INNER) TABLES\n" + "    CLIENT PARALLEL 1001-WAY FULL SCAN OVER "
-        + testTable1000 + "\n" + "        SERVER SORTED BY [T1.COL1]\n" + "    CLIENT MERGE SORT\n"
-        + "        PARALLEL INNER-JOIN TABLE 0\n"
-        + "            CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable990 + "\n" + "AND\n"
-        + "    CLIENT PARALLEL 991-WAY FULL SCAN OVER " + testTable990 + "\n"
-        + "        SERVER SORTED BY [T3.COL2]\n" + "    CLIENT MERGE SORT";
-    verifyQueryPlan(q, expected);
-  }
-
-  private static void verifyQueryPlan(String query, String expected) throws Exception {
     Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
-    Connection conn = DriverManager.getConnection(getUrl(), props);
-    ResultSet rs = conn.createStatement().executeQuery("explain " + query);
-    String plan = QueryUtil.getExplainPlan(rs);
-    assertTrue("Expected '" + expected + "' in the plan:\n" + plan + ".", plan.contains(expected));
+    try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+      assertPlan(conn, q).abstractExplainPlan("SORT-MERGE-JOIN (INNER)").lhs()
+        .iteratorType("PARALLEL 1001-WAY").scanType("FULL SCAN").table(testTable1000)
+        .serverSortedBy("[T1.COL1]").clientSortAlgo("CLIENT MERGE SORT").subPlanCount(1).subPlan(0)
+        .abstractExplainPlan("PARALLEL INNER-JOIN TABLE 0").iteratorType("PARALLEL 1-WAY")
+        .scanType("FULL SCAN").table(testTable990).end().end().rhs()
+        .iteratorType("PARALLEL 991-WAY").scanType("FULL SCAN").table(testTable990)
+        .serverSortedBy("[T3.COL2]").clientSortAlgo("CLIENT MERGE SORT");
+    }
   }
 
   private static String initTestTableValues(int rows) throws Exception {
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/CountDistinctApproximateHyperLogLogIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/CountDistinctApproximateHyperLogLogIT.java
index 193e0bf0fc..0d30793c23 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/CountDistinctApproximateHyperLogLogIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/CountDistinctApproximateHyperLogLogIT.java
@@ -17,14 +17,12 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.*;
 
 import java.sql.*;
 import java.util.Properties;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.schema.ColumnNotFoundException;
 import org.apache.phoenix.util.PropertiesUtil;
 import org.junit.Before;
@@ -124,14 +122,9 @@ public class CountDistinctApproximateHyperLogLogIT extends ParallelStatsDisabled
     String query = "SELECT APPROX_COUNT_DISTINCT(i1||i2) FROM " + tableName;
     try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
       prepareTableWithValues(conn, 100);
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals(tableName, explainPlanAttributes.getTableName());
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-      assertEquals("SERVER AGGREGATE INTO SINGLE ROW", explainPlanAttributes.getServerAggregate());
+      assertPlan(conn, query).table(tableName).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .serverAggregate("SERVER AGGREGATE INTO SINGLE ROW");
     }
   }
 
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/CreateTableIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/CreateTableIT.java
index f4f57bafc8..c196118b78 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/CreateTableIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/CreateTableIT.java
@@ -19,6 +19,7 @@ package org.apache.phoenix.end2end;
 
 import static org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants.PHOENIX_MAX_LOOKBACK_AGE_CONF_KEY;
 import static org.apache.phoenix.mapreduce.index.IndexUpgradeTool.ROLLBACK_OP;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -83,7 +84,6 @@ import org.apache.phoenix.util.ByteUtil;
 import org.apache.phoenix.util.EnvironmentEdgeManager;
 import org.apache.phoenix.util.IndexUtil;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.ReadOnlyProps;
 import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.TestUtil;
@@ -1072,9 +1072,7 @@ public class CreateTableIT extends ParallelStatsDisabledIT {
         conn.createStatement()
           .execute("CREATE TABLE " + table + " (PK VARCHAR PRIMARY KEY, " + CF + ".COL VARCHAR)");
 
-        assertTrue(QueryUtil
-          .getExplainPlan(conn.createStatement().executeQuery("explain select * from " + table))
-          .contains(NS + ":" + TBL));
+        assertPlan(conn, "select * from " + table).tableContains(NS + ":" + TBL);
 
         conn.createStatement().execute("DROP TABLE " + table);
       }
@@ -1085,9 +1083,7 @@ public class CreateTableIT extends ParallelStatsDisabledIT {
         conn.createStatement()
           .execute("CREATE TABLE " + table + " (PK VARCHAR PRIMARY KEY, " + CF + ".COL VARCHAR)");
 
-        assertTrue(QueryUtil
-          .getExplainPlan(conn.createStatement().executeQuery("explain select * from " + table))
-          .contains(NS + "." + TBL));
+        assertPlan(conn, "select * from " + table).tableContains(NS + "." + TBL);
 
         conn.createStatement().execute("DROP TABLE " + table);
       }
@@ -1098,9 +1094,7 @@ public class CreateTableIT extends ParallelStatsDisabledIT {
         conn.createStatement()
           .execute("CREATE TABLE " + table + " (PK VARCHAR PRIMARY KEY, " + CF + ".COL VARCHAR)");
 
-        assertTrue(QueryUtil
-          .getExplainPlan(conn.createStatement().executeQuery("explain select * from " + table))
-          .contains(NS + ":" + NS + "." + TBL));
+        assertPlan(conn, "select * from " + table).tableContains(NS + ":" + NS + "." + TBL);
 
         conn.createStatement().execute("DROP TABLE " + table);
       }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/CsvBulkLoadToolIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/CsvBulkLoadToolIT.java
index abd6a212e9..5fa004dd40 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/CsvBulkLoadToolIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/CsvBulkLoadToolIT.java
@@ -18,6 +18,7 @@
 package org.apache.phoenix.end2end;
 
 import static org.apache.phoenix.query.QueryServices.DATE_FORMAT_ATTRIB;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -45,7 +46,6 @@ import org.apache.phoenix.schema.PTable;
 import org.apache.phoenix.schema.PTableKey;
 import org.apache.phoenix.util.DateUtil;
 import org.apache.phoenix.util.PhoenixRuntime;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.ReadOnlyProps;
 import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.TestUtil;
@@ -521,8 +521,7 @@ public class CsvBulkLoadToolIT extends BaseOwnClusterIT {
     assertEquals("FirstName 2", rs.getString(2));
     String selectFromIndex =
       "SELECT FIRST_NAME FROM " + fullTableName + " where FIRST_NAME='FirstName 1'";
-    rs = stmt.executeQuery("EXPLAIN " + selectFromIndex);
-    assertTrue(QueryUtil.getExplainPlan(rs).contains(indexTableName));
+    assertPlan(conn, selectFromIndex).tableContains(indexTableName);
     rs = stmt.executeQuery(selectFromIndex);
     assertTrue(rs.next());
     assertEquals("FirstName 1", rs.getString(1));
@@ -538,8 +537,7 @@ public class CsvBulkLoadToolIT extends BaseOwnClusterIT {
         "--index-table", indexTableName, "--zookeeper", zkQuorum, "--corruptindexes" });
     assertEquals(0, exitCode);
     selectFromIndex = "SELECT FIRST_NAME FROM " + fullTableName + " where FIRST_NAME='FirstName 3'";
-    rs = stmt.executeQuery("EXPLAIN " + selectFromIndex);
-    assertTrue(QueryUtil.getExplainPlan(rs).contains(indexTableName));
+    assertPlan(conn, selectFromIndex).tableContains(indexTableName);
     rs = stmt.executeQuery(selectFromIndex);
     assertTrue(rs.next());
     assertEquals("FirstName 3", rs.getString(1));
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/DeleteIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/DeleteIT.java
index c2a31842f9..4a652ab3ff 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/DeleteIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/DeleteIT.java
@@ -17,6 +17,8 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertMutationPlan;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -52,16 +54,17 @@ import org.apache.hadoop.hbase.regionserver.HRegion;
 import org.apache.hadoop.hbase.regionserver.RegionScanner;
 import org.apache.hadoop.hbase.util.Bytes;
 import org.apache.phoenix.compile.DeleteCompiler;
+import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.compile.MutationPlan;
 import org.apache.phoenix.end2end.index.IndexTestUtil;
 import org.apache.phoenix.jdbc.PhoenixConnection;
+import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.jdbc.PhoenixStatement;
 import org.apache.phoenix.parse.DeleteStatement;
 import org.apache.phoenix.parse.SQLParser;
 import org.apache.phoenix.query.ConnectionQueryServices;
 import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 import org.junit.runner.RunWith;
@@ -192,20 +195,27 @@ public class DeleteIT extends ParallelStatsDisabledIT {
 
   private static void assertIndexUsed(Connection conn, String query, List<Object> binds,
     String indexName, boolean expectedToBeUsed, boolean local) throws SQLException {
-    PreparedStatement stmt = conn.prepareStatement("EXPLAIN " + query);
+    PhoenixPreparedStatement stmt =
+      conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class);
     for (int i = 0; i < binds.size(); i++) {
       stmt.setObject(i + 1, binds.get(i));
     }
-    ResultSet rs = stmt.executeQuery();
-    String explainPlan = QueryUtil.getExplainPlan(rs);
-    // It's very difficult currently to check if a local index is being used
-    // This check is brittle as it checks that the index ID appears in the range scan
-    // TODO: surface QueryPlan from MutationPlan
+    boolean isMutation = query.trim().toUpperCase().startsWith("DELETE")
+      || query.trim().toUpperCase().startsWith("UPSERT");
+    ExplainPlanAttributes attributes =
+      (isMutation ? stmt.compileMutation().getExplainPlan() : stmt.optimizeQuery().getExplainPlan())
+        .getPlanStepsAsAttributes();
+    // It's very difficult currently to check if a local index is being used.
+    // This check is brittle as it checks that the index ID appears in the range scan.
     if (local) {
-      assertEquals(expectedToBeUsed,
-        explainPlan.contains(indexName + " [1]") || explainPlan.contains(indexName + " [1,"));
+      String keyRanges = attributes.getKeyRanges();
+      boolean used = indexName.equals(attributes.getTableName()) && keyRanges != null
+        && (keyRanges.startsWith(" [1]") || keyRanges.startsWith(" [1,"));
+      assertEquals(expectedToBeUsed, used);
+    } else if (expectedToBeUsed) {
+      assertPlan(attributes).table(indexName);
     } else {
-      assertEquals(expectedToBeUsed, explainPlan.contains(" SCAN OVER " + indexName));
+      assertNotEquals(indexName, attributes.getTableName());
     }
   }
 
@@ -499,16 +509,18 @@ public class DeleteIT extends ParallelStatsDisabledIT {
       if (!autoCommit) {
         con.commit();
       }
-      psDelete = con.prepareStatement("EXPLAIN " + dml);
-      psDelete.setString(1, "AA");
-      psDelete.setString(2, "BB");
-      psDelete.setString(3, "CC");
-      psDelete.setDate(4, date);
-      String explainPlan = QueryUtil.getExplainPlan(psDelete.executeQuery());
+      PhoenixPreparedStatement explainStmt =
+        con.prepareStatement(dml).unwrap(PhoenixPreparedStatement.class);
+      explainStmt.setString(1, "AA");
+      explainStmt.setString(2, "BB");
+      explainStmt.setString(3, "CC");
+      explainStmt.setDate(4, date);
+      ExplainPlanAttributes attributes =
+        explainStmt.compileMutation().getExplainPlan().getPlanStepsAsAttributes();
       if (addNonPKIndex) {
-        assertNotEquals("DELETE SINGLE ROW", explainPlan);
+        assertNotEquals("DELETE SINGLE ROW", attributes.getAbstractExplainPlan());
       } else {
-        assertEquals("DELETE SINGLE ROW", explainPlan);
+        assertPlan(attributes).abstractExplainPlan("DELETE SINGLE ROW");
       }
 
       assertDeleted(con, tableName, indexName1, indexName2, indexName3);
@@ -927,26 +939,20 @@ public class DeleteIT extends ParallelStatsDisabledIT {
     }
     try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
       conn.setAutoCommit(true);
-      try (Statement statement = conn.createStatement()) {
-        ResultSet rs = statement.executeQuery("EXPLAIN " + delete);
-        String explainPlan = QueryUtil.getExplainPlan(rs);
-        // Verify index is used for the delete query
-        IndexToolIT.assertExplainPlan(false, explainPlan, tableName, indexName1);
-      }
+      // Verify index is used for the delete query
+      assertMutationPlan(conn, delete).scanType("RANGE SCAN").table(indexName1);
       // Created the second index
       try (Statement statement = conn.createStatement()) {
         statement.execute(indexDdl2);
       }
+      // Verify index is used for the delete query
+      assertMutationPlan(conn, delete).scanType("RANGE SCAN").table(indexName1);
       try (Statement statement = conn.createStatement()) {
-        ResultSet rs = statement.executeQuery("EXPLAIN " + delete);
-        String explainPlan = QueryUtil.getExplainPlan(rs);
-        // Verify index is used for the delete query
-        IndexToolIT.assertExplainPlan(false, explainPlan, tableName, indexName1);
         statement.executeUpdate(delete);
         // Count the number of rows
         String query = "SELECT COUNT(*) from " + tableName;
         // There should be no rows on the data table
-        rs = conn.createStatement().executeQuery(query);
+        ResultSet rs = conn.createStatement().executeQuery(query);
         assertTrue(rs.next());
         assertEquals(0, rs.getInt(1));
         query = "SELECT COUNT(*) from " + indexName1;
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/DerivedTableIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/DerivedTableIT.java
index d6cde17cf0..85ac718ac6 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/DerivedTableIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/DerivedTableIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.A_VALUE;
 import static org.apache.phoenix.util.TestUtil.B_VALUE;
 import static org.apache.phoenix.util.TestUtil.C_VALUE;
@@ -40,11 +41,11 @@ import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
+import java.sql.SQLException;
 import java.util.Collection;
 import java.util.List;
 import java.util.Properties;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Rule;
@@ -54,8 +55,6 @@ import org.junit.rules.TestName;
 import org.junit.runner.RunWith;
 import org.junit.runners.Parameterized;
 import org.junit.runners.Parameterized.Parameters;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 import org.apache.phoenix.thirdparty.com.google.common.collect.Lists;
 
@@ -68,12 +67,10 @@ public class DerivedTableIT extends ParallelStatsDisabledIT {
   public TestName name = new TestName();
 
   private String[] indexDDL;
-  private String[] plans;
+  private PlanSpec[] plans;
   private String tableName;
 
-  private static final Logger LOGGER = LoggerFactory.getLogger(DerivedTableIT.class);
-
-  public DerivedTableIT(String[] indexDDL, String[] plans) {
+  public DerivedTableIT(String[] indexDDL, PlanSpec[] plans) {
     this.indexDDL = indexDDL;
     this.plans = plans;
   }
@@ -92,13 +89,6 @@ public class DerivedTableIT extends ParallelStatsDisabledIT {
         conn.createStatement().execute(ddl);
       }
     }
-    String[] newplan = new String[plans.length];
-    if (plans != null && plans.length > 0) {
-      for (int i = 0; i < plans.length; i++) {
-        newplan[i] = plans[i].replace(dynamicTableName, tableName);
-      }
-      plans = newplan;
-    }
   }
 
   @After
@@ -108,31 +98,53 @@ public class DerivedTableIT extends ParallelStatsDisabledIT {
     assertFalse("refCount leaked", refCountLeaked);
   }
 
+  /** Structured EXPLAIN plan expectations for a derived-table query */
+  private static final class PlanSpec {
+    final String iteratorType;
+    final String tableSuffix;
+    final String serverAggregate;
+    final String[] clientSteps;
+
+    PlanSpec(String iteratorType, String tableSuffix, String serverAggregate,
+      String... clientSteps) {
+      this.iteratorType = iteratorType;
+      this.tableSuffix = tableSuffix;
+      this.serverAggregate = serverAggregate;
+      this.clientSteps = clientSteps;
+    }
+  }
+
+  private void verifyPlan(Connection conn, String query, PlanSpec spec) throws SQLException {
+    assertPlan(conn, query).iteratorType(spec.iteratorType).scanType("FULL SCAN")
+      .table(tableName + spec.tableSuffix).serverAggregate(spec.serverAggregate)
+      .clientSteps(spec.clientSteps);
+  }
+
   @Parameters(name = "DerivedTableIT_{index}") // name is used by failsafe as file name in reports
   public static synchronized Collection<Object> data() {
     List<Object> testCases = Lists.newArrayList();
-    testCases.add(new String[][] {
-      { "CREATE INDEX " + dynamicTableName + "_DERIVED_IDX ON " + dynamicTableName
+    testCases.add(new Object[] {
+      new String[] { "CREATE INDEX " + dynamicTableName + "_DERIVED_IDX ON " + dynamicTableName
         + " (a_byte) INCLUDE (A_STRING, B_STRING)" },
-      { "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + dynamicTableName + "_DERIVED_IDX \n"
-        + "    SERVER AGGREGATE INTO DISTINCT ROWS BY [\"A_STRING\", \"B_STRING\"]\n"
-        + "CLIENT MERGE SORT\n" + "CLIENT SORTED BY [\"B_STRING\"]\n" + "CLIENT SORTED BY [A]\n"
-        + "CLIENT AGGREGATE INTO DISTINCT ROWS BY [A]\n" + "CLIENT SORTED BY [A DESC]",
-
-        "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + dynamicTableName + "_DERIVED_IDX \n"
-          + "    SERVER AGGREGATE INTO DISTINCT ROWS BY [\"A_STRING\", \"B_STRING\"]\n"
-          + "CLIENT MERGE SORT\n" + "CLIENT AGGREGATE INTO ORDERED DISTINCT ROWS BY [A]\n"
-          + "CLIENT DISTINCT ON [COLLECTDISTINCT(B)]\n" + "CLIENT SORTED BY [A DESC]" } });
-    testCases.add(new String[][] { {},
-      { "CLIENT PARALLEL 4-WAY FULL SCAN OVER " + dynamicTableName + " \n"
-        + "    SERVER AGGREGATE INTO DISTINCT ROWS BY [A_STRING, B_STRING]\n"
-        + "CLIENT MERGE SORT\n" + "CLIENT SORTED BY [B_STRING]\n" + "CLIENT SORTED BY [A]\n"
-        + "CLIENT AGGREGATE INTO DISTINCT ROWS BY [A]\n" + "CLIENT SORTED BY [A DESC]",
-
-        "CLIENT PARALLEL 4-WAY FULL SCAN OVER " + dynamicTableName + " \n"
-          + "    SERVER AGGREGATE INTO DISTINCT ROWS BY [A_STRING, B_STRING]\n"
-          + "CLIENT MERGE SORT\n" + "CLIENT AGGREGATE INTO ORDERED DISTINCT ROWS BY [A]\n"
-          + "CLIENT DISTINCT ON [COLLECTDISTINCT(B)]\n" + "CLIENT SORTED BY [A DESC]" } });
+      new PlanSpec[] {
+        new PlanSpec("PARALLEL 1-WAY", "_DERIVED_IDX",
+          "SERVER AGGREGATE INTO DISTINCT ROWS BY [\"A_STRING\", \"B_STRING\"]",
+          "CLIENT MERGE SORT", "CLIENT SORTED BY [\"B_STRING\"]", "CLIENT SORTED BY [A]",
+          "CLIENT AGGREGATE INTO DISTINCT ROWS BY [A]", "CLIENT SORTED BY [A DESC]"),
+        new PlanSpec("PARALLEL 1-WAY", "_DERIVED_IDX",
+          "SERVER AGGREGATE INTO DISTINCT ROWS BY [\"A_STRING\", \"B_STRING\"]",
+          "CLIENT MERGE SORT", "CLIENT AGGREGATE INTO ORDERED DISTINCT ROWS BY [A]",
+          "CLIENT DISTINCT ON [COLLECTDISTINCT(B)]", "CLIENT SORTED BY [A DESC]") } });
+    testCases.add(new Object[] { new String[] {},
+      new PlanSpec[] {
+        new PlanSpec("PARALLEL 4-WAY", "",
+          "SERVER AGGREGATE INTO DISTINCT ROWS BY [A_STRING, B_STRING]", "CLIENT MERGE SORT",
+          "CLIENT SORTED BY [B_STRING]", "CLIENT SORTED BY [A]",
+          "CLIENT AGGREGATE INTO DISTINCT ROWS BY [A]", "CLIENT SORTED BY [A DESC]"),
+        new PlanSpec("PARALLEL 4-WAY", "",
+          "SERVER AGGREGATE INTO DISTINCT ROWS BY [A_STRING, B_STRING]", "CLIENT MERGE SORT",
+          "CLIENT AGGREGATE INTO ORDERED DISTINCT ROWS BY [A]",
+          "CLIENT DISTINCT ON [COLLECTDISTINCT(B)]", "CLIENT SORTED BY [A DESC]") } });
     return testCases;
   }
 
@@ -384,12 +396,7 @@ public class DerivedTableIT extends ParallelStatsDisabledIT {
 
       assertFalse(rs.next());
 
-      rs = conn.createStatement().executeQuery("EXPLAIN WITH REGIONS " + query);
-      String explainPlanOutput = QueryUtil.getExplainPlan(rs);
-      LOGGER.info("Explain plan output: {}", explainPlanOutput);
-      String[] splitExplainPlan = explainPlanOutput.split("\\n \\(region locations = \\[region=");
-      String[] secondSplitExplainPlan = splitExplainPlan[1].split("]\\)");
-      assertEquals(plans[0], splitExplainPlan[0] + secondSplitExplainPlan[1]);
+      verifyPlan(conn, query, plans[0]);
 
       // distinct b (groupby a, b) groupby a orderby a
       query = "SELECT DISTINCT COLLECTDISTINCT(t.b) FROM (SELECT b_string b, a_string a FROM "
@@ -411,12 +418,7 @@ public class DerivedTableIT extends ParallelStatsDisabledIT {
 
       assertFalse(rs.next());
 
-      rs = conn.createStatement().executeQuery("EXPLAIN WITH REGIONS " + query);
-      explainPlanOutput = QueryUtil.getExplainPlan(rs);
-      LOGGER.info("Explain plan output: {}", explainPlanOutput);
-      splitExplainPlan = explainPlanOutput.split("\\n \\(region locations = \\[region=");
-      secondSplitExplainPlan = splitExplainPlan[1].split("]\\)");
-      assertEquals(plans[1], splitExplainPlan[0] + secondSplitExplainPlan[1]);
+      verifyPlan(conn, query, plans[1]);
 
       // (orderby) groupby
       query = "SELECT t.a_string, count(*) FROM (SELECT * FROM " + tableName
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/DistinctPrefixFilterIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/DistinctPrefixFilterIT.java
index bebf007fb8..e1eedac0e7 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/DistinctPrefixFilterIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/DistinctPrefixFilterIT.java
@@ -17,10 +17,13 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.getExplainAttributes;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 
 import java.sql.Connection;
@@ -29,8 +32,8 @@ import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.util.Properties;
+import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -232,8 +235,12 @@ public class DistinctPrefixFilterIT extends ParallelStatsDisabledIT {
   }
 
   private void testPlan(String query, boolean optimizable) throws Exception {
-    ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + query);
-    assertEquals(optimizable, QueryUtil.getExplainPlan(rs).contains(PREFIX));
+    ExplainPlanAttributes attributes = getExplainAttributes(conn, query);
+    if (optimizable) {
+      assertNotNull(attributes.getServerDistinctFilter());
+    } else {
+      assertNull(attributes.getServerDistinctFilter());
+    }
   }
 
   @Test
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/EmptyColumnIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/EmptyColumnIT.java
index 5e0033bb4f..45ba6fc22d 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/EmptyColumnIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/EmptyColumnIT.java
@@ -29,10 +29,12 @@ import static org.apache.phoenix.query.PhoenixTestBuilder.SchemaBuilder.TableInd
 import static org.apache.phoenix.query.PhoenixTestBuilder.SchemaBuilder.TableOptions;
 import static org.apache.phoenix.query.PhoenixTestBuilder.SchemaBuilder.TenantViewIndexOptions;
 import static org.apache.phoenix.query.PhoenixTestBuilder.SchemaBuilder.TenantViewOptions;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.getExplainAttributes;
 import static org.apache.phoenix.util.PhoenixRuntime.TENANT_ID_ATTRIB;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
 
 import java.io.IOException;
 import java.sql.Connection;
@@ -50,7 +52,7 @@ import org.apache.hadoop.hbase.client.ResultScanner;
 import org.apache.hadoop.hbase.client.Scan;
 import org.apache.hadoop.hbase.client.Table;
 import org.apache.hadoop.hbase.util.Bytes;
-import org.apache.phoenix.jdbc.PhoenixResultSet;
+import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.query.PhoenixTestBuilder.BasicDataWriter;
 import org.apache.phoenix.query.PhoenixTestBuilder.DataSupplier;
 import org.apache.phoenix.query.PhoenixTestBuilder.DataWriter;
@@ -60,7 +62,6 @@ import org.apache.phoenix.schema.PTable;
 import org.apache.phoenix.util.EnvironmentEdgeManager;
 import org.apache.phoenix.util.IndexUtil;
 import org.apache.phoenix.util.ManualEnvironmentEdge;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.TestUtil;
 import org.junit.Ignore;
@@ -746,11 +747,10 @@ public class EmptyColumnIT extends ParallelStatsDisabledIT {
         injectEdge.setValue(EnvironmentEdgeManager.currentTimeMillis() + ttl * 1000 + 2);
         EnvironmentEdgeManager.injectEdge(injectEdge);
         String distinctQuery = "SELECT DISTINCT id1 FROM " + dataTableName;
+        ExplainPlanAttributes attributes = getExplainAttributes(conn, distinctQuery);
+        assertPlan(attributes).serverWhereFilter("SERVER FILTER BY EMPTY COLUMN ONLY");
+        assertNotNull(attributes.getServerDistinctFilter());
         try (ResultSet rs = conn.createStatement().executeQuery(distinctQuery)) {
-          PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
-          String explainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
-          assertTrue(explainPlan.contains("SERVER FILTER BY EMPTY COLUMN ONLY"));
-          assertTrue(explainPlan.contains("SERVER DISTINCT PREFIX FILTER OVER"));
           // all the rows should have been masked
           assertFalse(rs.next());
         }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ExplainPlanWithStatsDisabledIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ExplainPlanWithStatsDisabledIT.java
index 2565a3ba80..7606aec6fd 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ExplainPlanWithStatsDisabledIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ExplainPlanWithStatsDisabledIT.java
@@ -18,6 +18,7 @@
 package org.apache.phoenix.end2end;
 
 import static org.apache.phoenix.end2end.ExplainPlanWithStatsEnabledIT.getByteRowEstimates;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
@@ -27,14 +28,10 @@ import java.sql.DriverManager;
 import java.sql.ResultSet;
 import java.util.List;
 import java.util.Properties;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.end2end.ExplainPlanWithStatsEnabledIT.Estimate;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.util.PhoenixRuntime;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
@@ -256,12 +253,10 @@ public class ExplainPlanWithStatsDisabledIT extends ParallelStatsDisabledIT {
           + "              ) IMMUTABLE_ROWS=true\n" + "                ,SALT_BUCKETS=20");
       String query =
         "select * from foo where a = 'a' and b >= timestamp '2016-01-28 00:00:00' and b < timestamp '2016-01-29 00:00:00'";
-      ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + query);
-      String queryPlan = QueryUtil.getExplainPlan(rs);
-      assertEquals(
-        "CLIENT PARALLEL 20-WAY RANGE SCAN OVER FOO [X'00','a',~'2016-01-28 23:59:59.999'] - [X'13','a',~'2016-01-28 00:00:00.000']\n"
-          + "    SERVER FILTER BY FIRST KEY ONLY\n" + "CLIENT MERGE SORT",
-        queryPlan);
+      assertPlan(conn, query).scanType("RANGE SCAN").table("FOO")
+        .keyRanges(
+          " [X'00','a',~'2016-01-28 23:59:59.999'] -" + " [X'13','a',~'2016-01-28 00:00:00.000']")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").clientSortAlgo("CLIENT MERGE SORT");
     }
   }
 
@@ -278,11 +273,10 @@ public class ExplainPlanWithStatsDisabledIT extends ParallelStatsDisabledIT {
           + "              ) IMMUTABLE_ROWS=true\n" + "                ,SALT_BUCKETS=20");
       String query = "select * from " + tableName
         + " where a = 'a' and b >= timestamp '2016-01-28 00:00:00' and b < timestamp '2016-01-29 00:00:00'";
-      ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + query);
-      String queryPlan = QueryUtil.getExplainPlan(rs);
-      assertEquals("CLIENT PARALLEL 20-WAY ROUND ROBIN RANGE SCAN OVER " + tableName
-        + " [X'00','a',~'2016-01-28 23:59:59.999'] - [X'13','a',~'2016-01-28 00:00:00.000']\n"
-        + "    SERVER FILTER BY FIRST KEY ONLY", queryPlan);
+      assertPlan(conn, query).useRoundRobinIterator(true).scanType("RANGE SCAN").table(tableName)
+        .keyRanges(
+          " [X'00','a',~'2016-01-28 23:59:59.999'] -" + " [X'13','a',~'2016-01-28 00:00:00.000']")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY");
     }
   }
 
@@ -346,61 +340,33 @@ public class ExplainPlanWithStatsDisabledIT extends ParallelStatsDisabledIT {
       ResultSet rs = conn.createStatement().executeQuery(query);
       assertTrue(rs.next());
       assertEquals(53, rs.getInt(1));
-      rs = conn.createStatement().executeQuery("EXPLAIN " + query);
-      String queryPlan = QueryUtil.getExplainPlan(rs);
-      assertEquals(
-        "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " [*] - ['b']\n"
-          + "    SERVER FILTER BY FIRST KEY ONLY\n" + "    SERVER AGGREGATE INTO SINGLE ROW",
-        queryPlan);
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes planAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals(2, planAttributes.getNumRegionLocationLookups());
+      assertPlan(conn, query).scanType("RANGE SCAN").table(tableName).keyRanges(" [*] - ['b']")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .serverAggregate("SERVER AGGREGATE INTO SINGLE ROW").numRegionLocationLookups(2);
 
       query = "select count(*) from " + tableName + " where PK1 <= 'cd'";
       rs = conn.createStatement().executeQuery(query);
       assertTrue(rs.next());
       assertEquals(128, rs.getInt(1));
-      rs = conn.createStatement().executeQuery("EXPLAIN " + query);
-      queryPlan = QueryUtil.getExplainPlan(rs);
-      assertEquals(
-        "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " [*] - ['cd']\n"
-          + "    SERVER FILTER BY FIRST KEY ONLY\n" + "    SERVER AGGREGATE INTO SINGLE ROW",
-        queryPlan);
-      plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      planAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals(3, planAttributes.getNumRegionLocationLookups());
+      assertPlan(conn, query).scanType("RANGE SCAN").table(tableName).keyRanges(" [*] - ['cd']")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .serverAggregate("SERVER AGGREGATE INTO SINGLE ROW").numRegionLocationLookups(3);
 
       query = "select count(*) from " + tableName + " where PK1 LIKE 'ef%'";
       rs = conn.createStatement().executeQuery(query);
       assertTrue(rs.next());
       assertEquals(25, rs.getInt(1));
-      rs = conn.createStatement().executeQuery("EXPLAIN " + query);
-      queryPlan = QueryUtil.getExplainPlan(rs);
-      assertEquals(
-        "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " ['ef'] - ['eg']\n"
-          + "    SERVER FILTER BY FIRST KEY ONLY\n" + "    SERVER AGGREGATE INTO SINGLE ROW",
-        queryPlan);
-      plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      planAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals(1, planAttributes.getNumRegionLocationLookups());
+      assertPlan(conn, query).scanType("RANGE SCAN").table(tableName).keyRanges(" ['ef'] - ['eg']")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .serverAggregate("SERVER AGGREGATE INTO SINGLE ROW").numRegionLocationLookups(1);
 
       query = "select count(*) from " + tableName + " where PK1 > 'de'";
       rs = conn.createStatement().executeQuery(query);
       assertTrue(rs.next());
       assertEquals(75, rs.getInt(1));
-      rs = conn.createStatement().executeQuery("EXPLAIN " + query);
-      queryPlan = QueryUtil.getExplainPlan(rs);
-      assertEquals(
-        "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " ['de'] - [*]\n"
-          + "    SERVER FILTER BY FIRST KEY ONLY\n" + "    SERVER AGGREGATE INTO SINGLE ROW",
-        queryPlan);
-      plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      planAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals(1, planAttributes.getNumRegionLocationLookups());
+      assertPlan(conn, query).scanType("RANGE SCAN").table(tableName).keyRanges(" ['de'] - [*]")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .serverAggregate("SERVER AGGREGATE INTO SINGLE ROW").numRegionLocationLookups(1);
     }
   }
 
@@ -494,29 +460,15 @@ public class ExplainPlanWithStatsDisabledIT extends ParallelStatsDisabledIT {
         assertTrue(rs.next());
         assertEquals(50, rs.getInt(1));
 
-        rs = tenantConn.createStatement().executeQuery("EXPLAIN " + query);
-        String queryPlan = QueryUtil.getExplainPlan(rs);
-        assertEquals(
-          "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " ['ab12']\n"
-            + "    SERVER FILTER BY FIRST KEY ONLY\n" + "    SERVER AGGREGATE INTO SINGLE ROW",
-          queryPlan);
-        ExplainPlan plan = tenantConn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-          .optimizeQuery().getExplainPlan();
-        ExplainPlanAttributes planAttributes = plan.getPlanStepsAsAttributes();
-        assertEquals(1, planAttributes.getNumRegionLocationLookups());
+        assertPlan(tenantConn, query).scanType("RANGE SCAN").table(tableName).keyRanges(" ['ab12']")
+          .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+          .serverAggregate("SERVER AGGREGATE INTO SINGLE ROW").numRegionLocationLookups(1);
       }
 
       try (Connection tenantConn = getTenantConnection("cd12")) {
         String query = "select * from " + view03 + " order by col2";
-
-        ResultSet rs = tenantConn.createStatement().executeQuery("EXPLAIN " + query);
-        String queryPlan = QueryUtil.getExplainPlan(rs);
-        assertEquals("CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " ['cd12']\n"
-          + "    SERVER SORTED BY [COL2]\n" + "CLIENT MERGE SORT", queryPlan);
-        ExplainPlan plan = tenantConn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-          .optimizeQuery().getExplainPlan();
-        ExplainPlanAttributes planAttributes = plan.getPlanStepsAsAttributes();
-        assertEquals(1, planAttributes.getNumRegionLocationLookups());
+        assertPlan(tenantConn, query).scanType("RANGE SCAN").table(tableName).keyRanges(" ['cd12']")
+          .serverSortedBy("[COL2]").clientSortAlgo("CLIENT MERGE SORT").numRegionLocationLookups(1);
       }
 
       try (Connection tenantConn = getTenantConnection("de12")) {
@@ -528,14 +480,8 @@ public class ExplainPlanWithStatsDisabledIT extends ParallelStatsDisabledIT {
         }
         assertEquals(25, c);
 
-        rs = tenantConn.createStatement().executeQuery("EXPLAIN " + query);
-        String queryPlan = QueryUtil.getExplainPlan(rs);
-        assertEquals("CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " ['de12']\n"
-          + "    SERVER FILTER BY COL1 = 'col101'", queryPlan);
-        ExplainPlan plan = tenantConn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-          .optimizeQuery().getExplainPlan();
-        ExplainPlanAttributes planAttributes = plan.getPlanStepsAsAttributes();
-        assertEquals(1, planAttributes.getNumRegionLocationLookups());
+        assertPlan(tenantConn, query).scanType("RANGE SCAN").table(tableName).keyRanges(" ['de12']")
+          .serverWhereFilter("SERVER FILTER BY COL1 = 'col101'").numRegionLocationLookups(1);
       }
     }
   }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/FlappingLocalIndexIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/FlappingLocalIndexIT.java
index d84c3f6bb6..9fa2e49bd5 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/FlappingLocalIndexIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/FlappingLocalIndexIT.java
@@ -17,9 +17,9 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 
 import java.io.IOException;
@@ -42,24 +42,16 @@ import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
 import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
 import org.apache.hadoop.hbase.coprocessor.RegionObserver;
 import org.apache.hadoop.hbase.util.Pair;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.end2end.index.BaseLocalIndexIT;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.QueryConstants;
 import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.query.QueryServicesOptions;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.TestUtil;
 import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 public class FlappingLocalIndexIT extends BaseLocalIndexIT {
 
-  private static final Logger LOGGER = LoggerFactory.getLogger(FlappingLocalIndexIT.class);
-
   public FlappingLocalIndexIT(boolean isNamespaceMapped) {
     super(isNamespaceMapped);
   }
@@ -173,25 +165,13 @@ public class FlappingLocalIndexIT extends BaseLocalIndexIT {
 
       String query = "SELECT * FROM " + tableName + " where v1 like 'a%'";
 
-      String explainPlanOutput = QueryUtil
-        .getExplainPlan(conn1.createStatement().executeQuery("EXPLAIN WITH REGIONS " + query));
-      LOGGER.info("Explain plan output: {}", explainPlanOutput);
-      // MAX_REGION_LOCATIONS_SIZE_EXPLAIN_PLAN is set as 2
-      assertTrue("Expected total " + numRegions + " regions",
-        explainPlanOutput.contains("...total size = " + numRegions));
-
-      ExplainPlan plan = conn1.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL " + numRegions + "-WAY",
-        explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(indexTableName + "(" + indexPhysicalTableName + ")",
-        explainPlanAttributes.getTableName());
-      assertEquals(" [1,'a'] - [1,'b']", explainPlanAttributes.getKeyRanges());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-      assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-      assertEquals(trimmedRegionLocations, explainPlanAttributes.getRegionLocations().size());
+      // MAX_REGION_LOCATIONS_SIZE_EXPLAIN_PLAN is set as 2 so getRegionLocations() is trimmed. The
+      // full number of regions is reported via regionLocationsTotalSize.
+      assertPlan(conn1, query).iteratorType("PARALLEL " + numRegions + "-WAY")
+        .scanType("RANGE SCAN").table(indexTableName + "(" + indexPhysicalTableName + ")")
+        .keyRanges(" [1,'a'] - [1,'b']").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .clientSortAlgo("CLIENT MERGE SORT").regionLocationCount(trimmedRegionLocations)
+        .regionLocationsTotalSize(numRegions);
 
       rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -209,17 +189,10 @@ public class FlappingLocalIndexIT extends BaseLocalIndexIT {
       assertFalse(rs.next());
       query = "SELECT t_id, k1, k2,V1 FROM " + tableName + " where v1='a'";
 
-      plan = conn1.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL " + numRegions + "-WAY",
-        explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(indexTableName + "(" + indexPhysicalTableName + ")",
-        explainPlanAttributes.getTableName());
-      assertEquals(" [1,'a']", explainPlanAttributes.getKeyRanges());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-      assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+      assertPlan(conn1, query).iteratorType("PARALLEL " + numRegions + "-WAY")
+        .scanType("RANGE SCAN").table(indexTableName + "(" + indexPhysicalTableName + ")")
+        .keyRanges(" [1,'a']").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .clientSortAlgo("CLIENT MERGE SORT");
 
       rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -233,18 +206,10 @@ public class FlappingLocalIndexIT extends BaseLocalIndexIT {
       assertFalse(rs.next());
       query = "SELECT t_id, k1, k2,V1, k3 FROM " + tableName + " where v1<='z' order by k3";
 
-      plan = conn1.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL " + numRegions + "-WAY",
-        explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(indexTableName + "(" + indexPhysicalTableName + ")",
-        explainPlanAttributes.getTableName());
-      assertEquals(" [1,*] - [1,'z']", explainPlanAttributes.getKeyRanges());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-      assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-      assertEquals("[\"K3\"]", explainPlanAttributes.getServerSortedBy());
+      assertPlan(conn1, query).iteratorType("PARALLEL " + numRegions + "-WAY")
+        .scanType("RANGE SCAN").table(indexTableName + "(" + indexPhysicalTableName + ")")
+        .keyRanges(" [1,*] - [1,'z']").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .clientSortAlgo("CLIENT MERGE SORT").serverSortedBy("[\"K3\"]");
 
       rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -263,18 +228,10 @@ public class FlappingLocalIndexIT extends BaseLocalIndexIT {
 
       query = "SELECT t_id, k1, k2,v1 from " + tableName + " order by V1,t_id";
 
-      plan = conn1.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL " + numRegions + "-WAY",
-        explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(indexTableName + "(" + indexPhysicalTableName + ")",
-        explainPlanAttributes.getTableName());
-      assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-      assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-      assertNull(explainPlanAttributes.getServerSortedBy());
+      assertPlan(conn1, query).iteratorType("PARALLEL " + numRegions + "-WAY")
+        .scanType("RANGE SCAN").table(indexTableName + "(" + indexPhysicalTableName + ")")
+        .keyRanges(" [1]").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .clientSortAlgo("CLIENT MERGE SORT").serverSortedBy(null);
 
       rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/InListIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/InListIT.java
index 8d16b3a1c2..ccbd52caf0 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/InListIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/InListIT.java
@@ -19,6 +19,7 @@ package org.apache.phoenix.end2end;
 
 import static java.util.Collections.singletonList;
 import static org.apache.phoenix.query.QueryServices.USE_BLOOMFILTER_FOR_MULTIKEY_POINTLOOKUP;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.PhoenixRuntime.TENANT_ID_ATTRIB;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
@@ -46,8 +47,6 @@ import java.util.Set;
 import java.util.function.Predicate;
 import java.util.stream.Collectors;
 import org.apache.commons.lang3.RandomStringUtils;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.compile.ExpressionCompiler;
 import org.apache.phoenix.compile.QueryPlan;
 import org.apache.phoenix.compile.StatementContext;
@@ -1024,20 +1023,14 @@ public class InListIT extends ParallelStatsDisabledIT {
 
         try (PreparedStatement preparedStmt = viewConn.prepareStatement("SELECT * FROM "
           + tenantView + " WHERE (ID1, ID2) " + "IN (('005xx000001Sv6o', '000000000000500'))")) {
-          QueryPlan queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
-          ExplainPlan plan = queryPlan.getExplainPlan();
-          ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-          assertTrue(explainPlanAttributes.getExplainScanType()
-            .startsWith(ExplainTable.POINT_LOOKUP_ON_STRING));
+          assertPlan(PhoenixRuntime.getOptimizedQueryPlan(preparedStmt))
+            .scanTypeStartsWith(ExplainTable.POINT_LOOKUP_ON_STRING);
         }
 
         try (PreparedStatement preparedStmt = viewConn.prepareStatement("SELECT * FROM "
           + tenantView + " WHERE (ID2, ID1) " + "IN (('000000000000500', '005xx000001Sv6o'))")) {
-          QueryPlan queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
-          ExplainPlan plan = queryPlan.getExplainPlan();
-          ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-          assertTrue(explainPlanAttributes.getExplainScanType()
-            .startsWith(ExplainTable.POINT_LOOKUP_ON_STRING));
+          assertPlan(PhoenixRuntime.getOptimizedQueryPlan(preparedStmt))
+            .scanTypeStartsWith(ExplainTable.POINT_LOOKUP_ON_STRING);
         }
 
         stmt.execute(
@@ -1071,21 +1064,15 @@ public class InListIT extends ParallelStatsDisabledIT {
         try (PreparedStatement preparedStmt = viewConn.prepareStatement("SELECT * FROM "
           + tenantView + " WHERE (ID1, ID2) " + "IN (('005xx000001Sv6o', '000000000000500'),"
           + "('bar', '000000000000400')," + "('foo', '000000000000300'))")) {
-          QueryPlan queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
-          ExplainPlan plan = queryPlan.getExplainPlan();
-          ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-          assertTrue(explainPlanAttributes.getExplainScanType()
-            .startsWith(ExplainTable.POINT_LOOKUP_ON_STRING));
+          assertPlan(PhoenixRuntime.getOptimizedQueryPlan(preparedStmt))
+            .scanTypeStartsWith(ExplainTable.POINT_LOOKUP_ON_STRING);
         }
 
         try (PreparedStatement preparedStmt =
           viewConn.prepareStatement("SELECT * FROM " + tenantView + " WHERE (ID2, ID1) IN "
             + "(('bar', '005xx000001Sv6o')," + "('foo', '005xx000001Sv6o'))")) {
-          QueryPlan queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
-          ExplainPlan plan = queryPlan.getExplainPlan();
-          ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-          assertTrue(explainPlanAttributes.getExplainScanType()
-            .startsWith(ExplainTable.POINT_LOOKUP_ON_STRING));
+          assertPlan(PhoenixRuntime.getOptimizedQueryPlan(preparedStmt))
+            .scanTypeStartsWith(ExplainTable.POINT_LOOKUP_ON_STRING);
         }
 
         stmt.execute("DELETE FROM " + tenantView + " WHERE (ID2, ID1) IN "
@@ -1123,21 +1110,15 @@ public class InListIT extends ParallelStatsDisabledIT {
           viewConn.prepareStatement("SELECT * FROM " + tenantView + " WHERE (ID1, ID2) IN "
             + "(('005xx000001Sv6o', '000000000000500')," + "('005xx000001Sv6o', '000000000000400'),"
             + "('005xx000001Sv6o', '000000000000300'))")) {
-          QueryPlan queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
-          ExplainPlan plan = queryPlan.getExplainPlan();
-          ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-          assertTrue(explainPlanAttributes.getExplainScanType()
-            .startsWith(ExplainTable.POINT_LOOKUP_ON_STRING));
+          assertPlan(PhoenixRuntime.getOptimizedQueryPlan(preparedStmt))
+            .scanTypeStartsWith(ExplainTable.POINT_LOOKUP_ON_STRING);
         }
 
         try (PreparedStatement preparedStmt = viewConn.prepareStatement("SELECT * FROM "
           + tenantView + " WHERE (ID2, ID1) IN " + "(('000000000000400', '005xx000001Sv6o'),"
           + "('000000000000300', '005xx000001Sv6o'))")) {
-          QueryPlan queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
-          ExplainPlan plan = queryPlan.getExplainPlan();
-          ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-          assertTrue(explainPlanAttributes.getExplainScanType()
-            .startsWith(ExplainTable.POINT_LOOKUP_ON_STRING));
+          assertPlan(PhoenixRuntime.getOptimizedQueryPlan(preparedStmt))
+            .scanTypeStartsWith(ExplainTable.POINT_LOOKUP_ON_STRING);
         }
         ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tenantView
           + " WHERE (ID2, ID1) IN " + "(('000000000000400', '005xx000001Sv6o'),"
@@ -1178,19 +1159,13 @@ public class InListIT extends ParallelStatsDisabledIT {
           + "(('005xx000001Sv6o', '000000000000500')," + "('005xx000001Sv6o', '000000000000400'))");
       QueryPlan queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
       assertEquals(numberOfRowsToScan, queryPlan.getEstimatedRowsToScan());
-      ExplainPlan plan = queryPlan.getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertTrue(
-        explainPlanAttributes.getExplainScanType().startsWith(ExplainTable.POINT_LOOKUP_ON_STRING));
+      assertPlan(queryPlan).scanTypeStartsWith(ExplainTable.POINT_LOOKUP_ON_STRING);
 
       viewConn.prepareStatement("DELETE FROM " + tenantView + " WHERE (ID1, ID2) IN "
         + "(('005xx000001Sv6o', '000000000000500')," + "('005xx000001Sv6o', '000000000000400'))");
       queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
       assertEquals(numberOfRowsToScan, queryPlan.getEstimatedRowsToScan());
-      plan = queryPlan.getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertTrue(
-        explainPlanAttributes.getExplainScanType().startsWith(ExplainTable.POINT_LOOKUP_ON_STRING));
+      assertPlan(queryPlan).scanTypeStartsWith(ExplainTable.POINT_LOOKUP_ON_STRING);
     }
   }
 
@@ -1199,30 +1174,22 @@ public class InListIT extends ParallelStatsDisabledIT {
       PreparedStatement preparedStmt = viewConn.prepareStatement("SELECT * FROM " + tenantView
         + " WHERE (ID1) IN " + "(('005xx000001Sv6o')," + "('005xx000001Sv6o'))");
       QueryPlan queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
-      ExplainPlan plan = queryPlan.getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
+      assertPlan(queryPlan).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN");
 
       viewConn.prepareStatement("DELETE FROM " + tenantView + " WHERE (ID1) IN "
         + "(('005xx000001Sv6o')," + "('005xx000001Sv6o'))");
       queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
-      assertTrue(
-        queryPlan.getExplainPlan().toString().contains("CLIENT PARALLEL 1-WAY RANGE SCAN OVER"));
+      assertPlan(queryPlan).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN");
 
       preparedStmt = viewConn.prepareStatement("SELECT * FROM " + tenantView + " WHERE (ID2) IN "
         + "(('000000000000500')," + "('000000000000400'))");
       queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
-      plan = queryPlan.getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
+      assertPlan(queryPlan).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN");
 
       viewConn.prepareStatement("DELETE FROM " + tenantView + " WHERE (ID2) IN "
         + "(('000000000000500')," + "('000000000000400'))");
       queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
-      assertTrue(
-        queryPlan.getExplainPlan().toString().contains("CLIENT PARALLEL 1-WAY RANGE SCAN OVER"));
+      assertPlan(queryPlan).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN");
     }
   }
 
@@ -1231,30 +1198,22 @@ public class InListIT extends ParallelStatsDisabledIT {
       PreparedStatement preparedStmt = viewConn.prepareStatement("SELECT * FROM " + tenantView
         + " WHERE (ID1, ID3) IN " + "(('005xx000001Sv6o', 1)," + "('005xx000001Sv6o', 2))");
       QueryPlan queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
-      ExplainPlan plan = queryPlan.getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
+      assertPlan(queryPlan).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN");
 
       viewConn.prepareStatement("DELETE FROM " + tenantView + " WHERE (ID1, ID3) IN "
         + "(('005xx000001Sv6o', 1)," + "('005xx000001Sv6o', 2))");
       queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
-      assertTrue(
-        queryPlan.getExplainPlan().toString().contains("CLIENT PARALLEL 1-WAY RANGE SCAN OVER"));
+      assertPlan(queryPlan).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN");
 
       preparedStmt = viewConn.prepareStatement("SELECT * FROM " + tenantView
         + " WHERE (ID2, ID3) IN " + "(('000000000000500', 1)," + "('000000000000400', 2))");
       queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
-      plan = queryPlan.getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
+      assertPlan(queryPlan).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN");
 
       viewConn.prepareStatement("DELETE FROM " + tenantView + " WHERE (ID2, ID3) IN "
         + "(('000000000000500', 1)," + "('000000000000400', 2))");
       queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
-      assertTrue(
-        queryPlan.getExplainPlan().toString().contains("CLIENT PARALLEL 1-WAY RANGE SCAN OVER"));
+      assertPlan(queryPlan).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN");
     }
   }
 
@@ -1264,16 +1223,12 @@ public class InListIT extends ParallelStatsDisabledIT {
       PreparedStatement preparedStmt = viewConn.prepareStatement(
         "SELECT * FROM " + tenantView + " WHERE (ID3, ID4) IN " + "((1, 1)," + "(2, 2))");
       QueryPlan queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
-      ExplainPlan plan = queryPlan.getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
+      assertPlan(queryPlan).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN");
 
       viewConn.prepareStatement(
         "DELETE FROM " + tenantView + " WHERE (ID3, ID4) IN " + "((1, 1)," + "(2, 2))");
       queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
-      assertTrue(
-        queryPlan.getExplainPlan().toString().contains("CLIENT PARALLEL 1-WAY RANGE SCAN OVER"));
+      assertPlan(queryPlan).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN");
     }
   }
 
@@ -1775,28 +1730,19 @@ public class InListIT extends ParallelStatsDisabledIT {
           "SELECT * FROM " + view + " WHERE (ID1, ID2) IN " + "((1, 1)," + "(2, 2))");
         QueryPlan queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
         assertEquals(new Long(2), queryPlan.getEstimatedRowsToScan());
-        ExplainPlan plan = queryPlan.getExplainPlan();
-        ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-        assertTrue(explainPlanAttributes.getExplainScanType()
-          .startsWith(ExplainTable.POINT_LOOKUP_ON_STRING));
+        assertPlan(queryPlan).scanTypeStartsWith(ExplainTable.POINT_LOOKUP_ON_STRING);
 
         preparedStmt =
           conn.prepareStatement("SELECT * FROM " + view + " WHERE (ID2, ID1) IN ((1, 1),(2, 2))");
         queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
         assertEquals(new Long(2), queryPlan.getEstimatedRowsToScan());
-        plan = queryPlan.getExplainPlan();
-        explainPlanAttributes = plan.getPlanStepsAsAttributes();
-        assertTrue(explainPlanAttributes.getExplainScanType()
-          .startsWith(ExplainTable.POINT_LOOKUP_ON_STRING));
+        assertPlan(queryPlan).scanTypeStartsWith(ExplainTable.POINT_LOOKUP_ON_STRING);
 
         preparedStmt =
           conn.prepareStatement("SELECT * FROM " + view + " WHERE (ID2, ID1) IN ((1, 1),(2, 2))");
         queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
         assertEquals(new Long(2), queryPlan.getEstimatedRowsToScan());
-        plan = queryPlan.getExplainPlan();
-        explainPlanAttributes = plan.getPlanStepsAsAttributes();
-        assertTrue(explainPlanAttributes.getExplainScanType()
-          .startsWith(ExplainTable.POINT_LOOKUP_ON_STRING));
+        assertPlan(queryPlan).scanTypeStartsWith(ExplainTable.POINT_LOOKUP_ON_STRING);
 
         ResultSet rs = stmt.executeQuery("SELECT ID1, ID2, ID5, ID4 FROM " + view
           + " WHERE (POWER(ID2, 2), ID1) IN " + "((4.0, 9)," + "(10, 12))");
@@ -1842,27 +1788,19 @@ public class InListIT extends ParallelStatsDisabledIT {
         PreparedStatement preparedStmt = conn.prepareStatement(
           "SELECT * FROM " + view + " WHERE (ID4, ID2) IN " + "((1, 1)," + "(2, 2))");
         QueryPlan queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
-        ExplainPlan plan = queryPlan.getExplainPlan();
-        ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
+        assertPlan(queryPlan).scanType("RANGE SCAN");
 
         preparedStmt = conn.prepareStatement(
           "SELECT ID1,ID5 FROM " + view + " WHERE (ID1, ID2) IN " + "((1, 1),(2, 2))");
         queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
         assertEquals(new Long(2), queryPlan.getEstimatedRowsToScan());
-        plan = queryPlan.getExplainPlan();
-        explainPlanAttributes = plan.getPlanStepsAsAttributes();
-        assertTrue(explainPlanAttributes.getExplainScanType()
-          .startsWith(ExplainTable.POINT_LOOKUP_ON_STRING));
+        assertPlan(queryPlan).scanTypeStartsWith(ExplainTable.POINT_LOOKUP_ON_STRING);
 
         preparedStmt =
           conn.prepareStatement("SELECT * FROM " + view + " WHERE (ID2, ID1) IN ((1, 1),(2, 2))");
         queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
         assertEquals(new Long(2), queryPlan.getEstimatedRowsToScan());
-        plan = queryPlan.getExplainPlan();
-        explainPlanAttributes = plan.getPlanStepsAsAttributes();
-        assertTrue(explainPlanAttributes.getExplainScanType()
-          .startsWith(ExplainTable.POINT_LOOKUP_ON_STRING));
+        assertPlan(queryPlan).scanTypeStartsWith(ExplainTable.POINT_LOOKUP_ON_STRING);
 
         ResultSet rs = stmt.executeQuery("SELECT ID1, ID2, ID5, ID4 FROM " + view
           + " WHERE (POWER(ID2, 2), ID1) IN " + "((4.0, 9)," + "(10, 12))");
@@ -1901,10 +1839,7 @@ public class InListIT extends ParallelStatsDisabledIT {
         "SELECT VAL2 FROM " + fullTableName + " WHERE (ID2, ID1) IN ((1, 1),(2, 2))");
       QueryPlan queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
       queryPlan.getTableRef().getTable().getType();
-      ExplainPlan plan = queryPlan.getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertTrue(
-        explainPlanAttributes.getExplainScanType().startsWith(ExplainTable.POINT_LOOKUP_ON_STRING));
+      assertPlan(queryPlan).scanTypeStartsWith(ExplainTable.POINT_LOOKUP_ON_STRING);
     }
   }
 
@@ -2247,11 +2182,10 @@ public class InListIT extends ParallelStatsDisabledIT {
       setBindVariables(stmt, lastBoundCol, numInLists, testPKTypes);
       QueryPlan plan = stmt.compileQuery(query.toString());
       if (expectSkipScan) {
-        assertTrue(
-          plan.getExplainPlan().toString().contains("CLIENT PARALLEL 1-WAY POINT LOOKUP ON"));
+        assertPlan(plan).iteratorType("PARALLEL 1-WAY")
+          .scanTypeStartsWith(ExplainTable.POINT_LOOKUP_ON_STRING);
       } else {
-        assertTrue(
-          plan.getExplainPlan().toString().contains("CLIENT PARALLEL 1-WAY RANGE SCAN OVER"));
+        assertPlan(plan).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN");
       }
 
       ResultSet rs = stmt.executeQuery(query.toString());
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/IndexBuildTimestampIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/IndexBuildTimestampIT.java
index e7ab684e8b..3491b0f2a1 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/IndexBuildTimestampIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/IndexBuildTimestampIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
@@ -41,8 +42,8 @@ import org.apache.phoenix.query.QueryServicesOptions;
 import org.apache.phoenix.schema.PTable;
 import org.apache.phoenix.util.EnvironmentEdge;
 import org.apache.phoenix.util.EnvironmentEdgeManager;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.ReadOnlyProps;
+import org.apache.phoenix.util.SchemaUtil;
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -136,11 +137,13 @@ public class IndexBuildTimestampIT extends BaseTest {
 
   public static void assertExplainPlan(Connection conn, boolean localIndex, String selectSql,
     String dataTableFullName, String indexTableFullName) throws SQLException {
-    ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql);
-    String actualExplainPlan = QueryUtil.getExplainPlan(rs);
-
-    IndexToolIT.assertExplainPlan(localIndex, actualExplainPlan, dataTableFullName,
-      indexTableFullName);
+    // Verify the query is served by a RANGE SCAN over the index table. For a local index the
+    // scanned name carries the data table in parentheses, e.g. IDX(DATA).
+    String expectedTable = localIndex
+      ? SchemaUtil.normalizeIdentifier(indexTableFullName) + "("
+        + SchemaUtil.normalizeIdentifier(dataTableFullName) + ")"
+      : SchemaUtil.normalizeIdentifier(indexTableFullName);
+    assertPlan(conn, selectSql).scanType("RANGE SCAN").tableContains(expectedTable);
   }
 
   private class MyClock extends EnvironmentEdge {
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/IndexExtendedIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/IndexExtendedIT.java
index d633c064e9..eda03aaa9c 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/IndexExtendedIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/IndexExtendedIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.apache.phoenix.util.TestUtil.checkIndexState;
 import static org.apache.phoenix.util.TestUtil.getRowCount;
@@ -35,13 +36,10 @@ import java.util.Map;
 import java.util.Properties;
 import org.apache.hadoop.hbase.client.Table;
 import org.apache.hadoop.hbase.util.Bytes;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.coprocessor.BaseScannerRegionObserver;
 import org.apache.phoenix.coprocessor.IndexRebuildRegionScanner;
 import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
 import org.apache.phoenix.jdbc.PhoenixConnection;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.mapreduce.index.IndexTool;
 import org.apache.phoenix.query.BaseTest;
 import org.apache.phoenix.query.QueryServices;
@@ -177,15 +175,10 @@ public class IndexExtendedIT extends BaseTest {
       String selectSql =
         String.format("SELECT ID FROM %s WHERE UPPER(NAME, 'en_US') ='UNAME2'", dataTableFullName);
 
-      ExplainPlan plan = conn.prepareStatement(selectSql).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
       // assert we are pulling from data table.
-      assertEquals(dataTableFullName, explainPlanAttributes.getTableName());
-      assertEquals("SERVER FILTER BY UPPER(NAME, 'en_US') = 'UNAME2'",
-        explainPlanAttributes.getServerWhereFilter());
+      assertPlan(conn, selectSql).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+        .table(dataTableFullName)
+        .serverWhereFilter("SERVER FILTER BY UPPER(NAME, 'en_US') = 'UNAME2'");
 
       ResultSet rs = stmt1.executeQuery(selectSql);
       assertTrue(rs.next());
@@ -195,13 +188,10 @@ public class IndexExtendedIT extends BaseTest {
       // run the index MR job.
       IndexToolIT.runIndexTool(useSnapshot, schemaName, dataTableName, indexTableName);
 
-      plan = conn.prepareStatement(selectSql).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
       // assert we are pulling from index table.
       String expectedTableName =
         localIndex ? indexTableFullName + "(" + dataTableFullName + ")" : indexTableFullName;
-      assertEquals(expectedTableName, explainPlanAttributes.getTableName());
+      assertPlan(conn, selectSql).table(expectedTableName);
 
       rs = stmt.executeQuery(selectSql);
       assertTrue(rs.next());
@@ -259,13 +249,8 @@ public class IndexExtendedIT extends BaseTest {
       // deleted
       String query = "SELECT pk3 from " + dataTableFullName + " ORDER BY pk3";
 
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(indexTableFullName, explainPlanAttributes.getTableName());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
+      assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+        .table(indexTableFullName).serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY");
 
       ResultSet rs = conn.createStatement().executeQuery(query);
       assertTrue(rs.next());
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/IndexToolForPartialBuildIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/IndexToolForPartialBuildIT.java
index c4f3be5c38..c9f5c84bbe 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/IndexToolForPartialBuildIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/IndexToolForPartialBuildIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -39,10 +40,7 @@ import org.apache.hadoop.hbase.client.Result;
 import org.apache.hadoop.hbase.client.ResultScanner;
 import org.apache.hadoop.hbase.client.Scan;
 import org.apache.hadoop.hbase.client.Table;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.jdbc.PhoenixConnection;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.mapreduce.index.IndexTool;
 import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.query.QueryServicesOptions;
@@ -165,15 +163,10 @@ public class IndexToolForPartialBuildIT extends BaseOwnClusterIT {
       String selectSql =
         String.format("SELECT LPAD(UPPER(NAME),11,'x')||'_xyz',ID FROM %s", fullTableName);
 
-      ExplainPlan plan = conn.prepareStatement(selectSql).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
       // assert we are pulling from data table.
-      assertEquals(SchemaUtil
-        .getPhysicalHBaseTableName(schemaName, dataTableName, isNamespaceEnabled).toString(),
-        explainPlanAttributes.getTableName());
+      assertPlan(conn, selectSql).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+        .table(SchemaUtil.getPhysicalHBaseTableName(schemaName, dataTableName, isNamespaceEnabled)
+          .toString());
 
       rs = stmt1.executeQuery(selectSql);
       for (int i = 1; i <= 7; i++) {
@@ -208,15 +201,9 @@ public class IndexToolForPartialBuildIT extends BaseOwnClusterIT {
       upsertRow(stmt1, 9000);
       conn.commit();
 
-      plan = conn.prepareStatement(selectSql).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
       // assert we are pulling from index table.
-      assertEquals(
-        SchemaUtil.getPhysicalHBaseTableName(schemaName, indxTable, isNamespaceEnabled).toString(),
-        explainPlanAttributes.getTableName());
+      assertPlan(conn, selectSql).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").table(
+        SchemaUtil.getPhysicalHBaseTableName(schemaName, indxTable, isNamespaceEnabled).toString());
 
       rs = stmt.executeQuery(selectSql);
 
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/IndexToolIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/IndexToolIT.java
index 23f083f096..8f7c732c40 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/IndexToolIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/IndexToolIT.java
@@ -38,6 +38,8 @@ import static org.apache.phoenix.mapreduce.index.PhoenixIndexToolJobCounters.BEF
 import static org.apache.phoenix.mapreduce.index.PhoenixIndexToolJobCounters.BEFORE_REPAIR_EXTRA_VERIFIED_INDEX_ROW_COUNT;
 import static org.apache.phoenix.mapreduce.index.PhoenixIndexToolJobCounters.REBUILT_INDEX_ROW_COUNT;
 import static org.apache.phoenix.mapreduce.index.PhoenixIndexToolJobCounters.SCANNED_DATA_ROW_COUNT;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.getExplainAttributes;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -82,11 +84,9 @@ import org.apache.hadoop.mapreduce.Counter;
 import org.apache.hadoop.mapreduce.CounterGroup;
 import org.apache.hadoop.mapreduce.Counters;
 import org.apache.hadoop.mapreduce.Job;
-import org.apache.phoenix.compile.ExplainPlan;
 import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.end2end.index.IndexTestUtil;
 import org.apache.phoenix.jdbc.PhoenixConnection;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.mapreduce.index.IndexTool;
 import org.apache.phoenix.mapreduce.index.IndexVerificationOutputRepository;
 import org.apache.phoenix.mapreduce.index.IndexVerificationResultRepository;
@@ -104,7 +104,6 @@ import org.apache.phoenix.transaction.TransactionFactory;
 import org.apache.phoenix.util.IndexScrutiny;
 import org.apache.phoenix.util.PhoenixRuntime;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.ReadOnlyProps;
 import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.TestUtil;
@@ -312,11 +311,8 @@ public class IndexToolIT extends BaseTest {
         dataTableFullName);
 
       // assert we are pulling from data table.
-      ExplainPlan plan = conn.prepareStatement(selectSql).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
+      ExplainPlanAttributes explainPlanAttributes = assertPlan(conn, selectSql)
+        .iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").attributes();
       assertEquals(dataTableFullName, explainPlanAttributes.getTableName().replaceAll(":", "."));
       assertEquals(
         "SERVER FILTER BY (LPAD(UPPER(NAME, 'en_US'), 8, 'x') || '_xyz') = 'xxUNAME2_xyz'",
@@ -345,10 +341,7 @@ public class IndexToolIT extends BaseTest {
           QueryConstants.VERIFIED_BYTES);
       }
       // assert we are pulling from index table.
-      plan = conn.prepareStatement(selectSql).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
+      explainPlanAttributes = assertPlan(conn, selectSql).scanType("RANGE SCAN").attributes();
       final String expectedTableName;
       if (localIndex) {
         expectedTableName = indexTableFullName + "(" + dataTableFullName + ")";
@@ -542,12 +535,8 @@ public class IndexToolIT extends BaseTest {
       runIndexTool(false, "", viewTenantName, indexNameTenant, tenantId, 0, new String[0]);
 
       String selectSql = String.format("SELECT ID FROM %s WHERE NAME='x'", viewTenantName);
-      ExplainPlan plan = connTenant.prepareStatement(selectSql)
-        .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(viewIndexTableName, explainPlanAttributes.getTableName());
+      assertPlan(connTenant, selectSql).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+        .table(viewIndexTableName);
 
       ResultSet rs = connTenant.createStatement().executeQuery(selectSql);
       assertTrue(rs.next());
@@ -779,16 +768,18 @@ public class IndexToolIT extends BaseTest {
         "SELECT ID FROM %s WHERE LPAD(UPPER(NAME, 'en_US'),8,'x')||'_xyz' = 'xxUNAME2_xyz'",
         qDataTableName);
 
-      ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql);
-      String actualExplainPlan = QueryUtil.getExplainPlan(rs);
-
       // assert we are pulling from data table.
-      assertEquals(String.format(
-        "CLIENT PARALLEL 1-WAY FULL SCAN OVER %s\n"
-          + "    SERVER FILTER BY (LPAD(UPPER(NAME, 'en_US'), 8, 'x') || '_xyz') = 'xxUNAME2_xyz'",
-        dataTableNameForExplain), actualExplainPlan.replaceAll(":", "."));
-
-      rs = stmt1.executeQuery(selectSql);
+      ExplainPlanAttributes dataAttributes = getExplainAttributes(conn, selectSql);
+      assertPlan(dataAttributes).scanType("FULL SCAN").serverWhereFilter(
+        "SERVER FILTER BY (LPAD(UPPER(NAME, 'en_US'), 8, 'x') || '_xyz') = 'xxUNAME2_xyz'");
+      // Table names are case-sensitive and (under namespace mapping) carry a ':' separator, so
+      // compare against the normalized ('.') form rather than via tableContains().
+      String dataScanTable = dataAttributes.getTableName() == null
+        ? null
+        : dataAttributes.getTableName().replaceAll(":", ".");
+      assertEquals(dataTableNameForExplain, dataScanTable);
+
+      ResultSet rs = stmt1.executeQuery(selectSql);
       assertTrue(rs.next());
       assertEquals(2, rs.getInt(1));
       assertFalse(rs.next());
@@ -803,12 +794,19 @@ public class IndexToolIT extends BaseTest {
       conn.commit();
 
       // assert we are pulling from index table.
-      rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql);
-      actualExplainPlan = QueryUtil.getExplainPlan(rs);
-      // Because the explain plan doesn't include double-quotes around case-sensitive table names,
-      // we need to tell assertExplainPlan to not normalize our table names.
-      assertExplainPlan(localIndex, actualExplainPlan, dataTableNameForExplain,
-        indexTableNameForExplain, false);
+      ExplainPlanAttributes indexAttributes = getExplainAttributes(conn, selectSql);
+      assertPlan(indexAttributes).scanType("RANGE SCAN");
+      // The explain plan doesn't include double-quotes around case-sensitive table names and (under
+      // namespace mapping) uses a ':' separator, so compare against the non-normalized ('.') form.
+      String indexScanTable = indexAttributes.getTableName() == null
+        ? null
+        : indexAttributes.getTableName().replaceAll(":", ".");
+      String expectedIndexTable = localIndex
+        ? indexTableNameForExplain + "(" + dataTableNameForExplain + ")"
+        : indexTableNameForExplain;
+      assertTrue(
+        "expected scanned table <" + indexScanTable + "> to use index <" + expectedIndexTable + ">",
+        indexScanTable != null && indexScanTable.contains(expectedIndexTable));
 
       rs = conn.createStatement().executeQuery(selectSql);
       assertTrue(rs.next());
@@ -899,28 +897,40 @@ public class IndexToolIT extends BaseTest {
     }
   }
 
-  public static void assertExplainPlan(boolean localIndex, String actualExplainPlan,
-    String dataTableFullName, String indexTableFullName) {
-    assertExplainPlan(localIndex, actualExplainPlan, dataTableFullName, indexTableFullName, true);
+  /**
+   * Verify the optimizer chose to scan {@code indexTableFullName}. For a local index the scanned
+   * "table" is reported as {@code IDX(DATA)} and the key range starts with {@code [1,}.
+   */
+  public static void assertExplainPlan(Connection conn, boolean localIndex, String selectSql,
+    String dataTableFullName, String indexTableFullName) throws SQLException {
+    assertExplainPlan(conn, localIndex, selectSql, dataTableFullName, indexTableFullName, true);
   }
 
-  public static void assertExplainPlan(boolean localIndex, String actualExplainPlan,
-    String dataTableFullName, String indexTableFullName, boolean normalizeTableNames) {
-    String expectedExplainPlan;
+  public static void assertExplainPlan(Connection conn, boolean localIndex, String selectSql,
+    String dataTableFullName, String indexTableFullName, boolean normalizeTableNames)
+    throws SQLException {
+    String expectedTable;
     if (localIndex) {
-      expectedExplainPlan = String.format(" RANGE SCAN OVER %s [1,",
-        normalizeTableNames
-          ? SchemaUtil.normalizeIdentifier(indexTableFullName) + "("
-            + SchemaUtil.normalizeIdentifier(dataTableFullName) + ")"
-          : indexTableFullName + "(" + dataTableFullName + ")");
+      expectedTable = normalizeTableNames
+        ? SchemaUtil.normalizeIdentifier(indexTableFullName) + "("
+          + SchemaUtil.normalizeIdentifier(dataTableFullName) + ")"
+        : indexTableFullName + "(" + dataTableFullName + ")";
     } else {
-      expectedExplainPlan = String.format(" RANGE SCAN OVER %s",
-        normalizeTableNames
-          ? SchemaUtil.normalizeIdentifier(indexTableFullName)
-          : indexTableFullName);
+      expectedTable = normalizeTableNames
+        ? SchemaUtil.normalizeIdentifier(indexTableFullName)
+        : indexTableFullName;
+    }
+    ExplainPlanAttributes attributes = getExplainAttributes(conn, selectSql);
+    assertPlan(attributes).scanType("RANGE SCAN");
+    String actualTable =
+      attributes.getTableName() == null ? null : attributes.getTableName().replaceAll(":", ".");
+    assertTrue("expected scanned table <" + actualTable + "> to contain <" + expectedTable + ">",
+      actualTable != null && actualTable.contains(expectedTable));
+    if (localIndex) {
+      String keyRanges = attributes.getKeyRanges();
+      assertTrue("expected local-index key ranges <" + keyRanges + "> to start with '[1,'",
+        keyRanges != null && keyRanges.trim().startsWith("[1,"));
     }
-    assertTrue(actualExplainPlan + "\n expected to contain \n" + expectedExplainPlan,
-      actualExplainPlan.replaceAll(":", ".").contains(expectedExplainPlan));
   }
 
   public static CounterGroup getMRJobCounters(IndexTool indexTool) throws IOException {
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/KeyOnlyIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/KeyOnlyIT.java
index e500cb4021..dffcea8379 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/KeyOnlyIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/KeyOnlyIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.apache.phoenix.util.TestUtil.analyzeTable;
 import static org.apache.phoenix.util.TestUtil.getAllSplits;
@@ -32,9 +33,6 @@ import java.sql.SQLException;
 import java.sql.Statement;
 import java.util.List;
 import java.util.Properties;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.KeyRange;
 import org.apache.phoenix.util.PropertiesUtil;
 import org.apache.phoenix.util.TestUtil;
@@ -145,15 +143,8 @@ public class KeyOnlyIT extends ParallelStatsEnabledIT {
     assertEquals(0, rs.getInt(1));
     assertFalse(rs.next());
 
-    ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-      .optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("SERIAL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals(1, explainPlanAttributes.getServerRowLimit().intValue());
-    assertEquals(1, explainPlanAttributes.getClientRowLimit().intValue());
+    assertPlan(conn, query).iteratorType("SERIAL 1-WAY").scanType("FULL SCAN").table(tableName)
+      .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").serverRowLimit(1L).clientRowLimit(1);
   }
 
   @Test
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/LocalIndexSplitMergeIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/LocalIndexSplitMergeIT.java
index e654fe0c19..eebcfaf6fd 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/LocalIndexSplitMergeIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/LocalIndexSplitMergeIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 
@@ -33,10 +34,7 @@ import org.apache.hadoop.hbase.TableName;
 import org.apache.hadoop.hbase.client.Admin;
 import org.apache.hadoop.hbase.client.RegionInfo;
 import org.apache.hadoop.hbase.util.Bytes;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.jdbc.PhoenixConnection;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.BaseTest;
 import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.query.QueryServicesOptions;
@@ -143,33 +141,17 @@ public class LocalIndexSplitMergeIT extends BaseTest {
           assertEquals(m, k1ColumnValue[m]);
         }
 
-        ExplainPlan plan = conn1.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-          .optimizeQuery().getExplainPlan();
-        ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-        assertEquals("PARALLEL " + (4 + i) + "-WAY",
-          explainPlanAttributes.getIteratorTypeAndScanSize());
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName + "(" + indexPhysicalTableName + ")",
-          explainPlanAttributes.getTableName());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
-        assertEquals("SERVER FILTER BY FIRST KEY ONLY",
-          explainPlanAttributes.getServerWhereFilter());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        assertPlan(conn1, query).iteratorType("PARALLEL " + (4 + i) + "-WAY").scanType("RANGE SCAN")
+          .table(fullIndexName + "(" + indexPhysicalTableName + ")").keyRanges(" [1]")
+          .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").clientSortAlgo("CLIENT MERGE SORT");
 
         query = "SELECT t_id,k1,k3 FROM " + tableName;
-        plan = conn1.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-          .getExplainPlan();
-        explainPlanAttributes = plan.getPlanStepsAsAttributes();
-        assertEquals(
-          "PARALLEL " + ((strings[3 * i].compareTo("j") < 0) ? (4 + i) : (4 + i - 1)) + "-WAY",
-          explainPlanAttributes.getIteratorTypeAndScanSize());
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName + "_2(" + indexPhysicalTableName + ")",
-          explainPlanAttributes.getTableName());
-        assertEquals(" [2]", explainPlanAttributes.getKeyRanges());
-        assertEquals("SERVER FILTER BY FIRST KEY ONLY",
-          explainPlanAttributes.getServerWhereFilter());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        assertPlan(conn1, query)
+          .iteratorType(
+            "PARALLEL " + ((strings[3 * i].compareTo("j") < 0) ? (4 + i) : (4 + i - 1)) + "-WAY")
+          .scanType("RANGE SCAN").table(fullIndexName + "_2(" + indexPhysicalTableName + ")")
+          .keyRanges(" [2]").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+          .clientSortAlgo("CLIENT MERGE SORT");
 
         rs = conn1.createStatement().executeQuery(query);
         Thread.sleep(1000);
@@ -245,28 +227,14 @@ public class LocalIndexSplitMergeIT extends BaseTest {
         assertEquals(strings[j], rs.getString("V1"));
       }
 
-      ExplainPlan plan = conn1.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 3-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(fullIndexName + "(" + indexPhysicalTableName + ")",
-        explainPlanAttributes.getTableName());
-      assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-      assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+      assertPlan(conn1, query).iteratorType("PARALLEL 3-WAY").scanType("RANGE SCAN")
+        .table(fullIndexName + "(" + indexPhysicalTableName + ")").keyRanges(" [1]")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").clientSortAlgo("CLIENT MERGE SORT");
 
       query = "SELECT t_id,k1,k3 FROM " + tableName;
-      plan = conn1.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 3-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(fullIndexName + "_2(" + indexPhysicalTableName + ")",
-        explainPlanAttributes.getTableName());
-      assertEquals(" [2]", explainPlanAttributes.getKeyRanges());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-      assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+      assertPlan(conn1, query).iteratorType("PARALLEL 3-WAY").scanType("RANGE SCAN")
+        .table(fullIndexName + "_2(" + indexPhysicalTableName + ")").keyRanges(" [2]")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").clientSortAlgo("CLIENT MERGE SORT");
 
       rs = conn1.createStatement().executeQuery(query);
       Thread.sleep(1000);
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/LogicalTableNameExtendedIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/LogicalTableNameExtendedIT.java
index 4b8496d9cc..9de4fd9f35 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/LogicalTableNameExtendedIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/LogicalTableNameExtendedIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 
@@ -36,7 +37,6 @@ import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.schema.types.PInteger;
 import org.apache.phoenix.util.ByteUtil;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.SchemaUtil;
 import org.junit.BeforeClass;
 import org.junit.Test;
@@ -216,13 +216,12 @@ public class LogicalTableNameExtendedIT extends LogicalTableNameBaseIT {
       populateTable(conn, tableName, 1, 2);
 
       String tableSelect = "SELECT V1,V2,V3 FROM " + tableName;
-      ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + tableSelect);
-      String plan = QueryUtil.getExplainPlan(rs);
+      String scannedTable = assertPlan(conn, tableSelect).attributes().getTableName();
       // plan should use one of the indexes
-      assertEquals(true, plan.contains(indexName) || plan.contains(indexName2));
+      assertEquals(true, scannedTable != null
+        && (scannedTable.contains(indexName) || scannedTable.contains(indexName2)));
       // Test hint for the other index
-      String hintedIndex =
-        QueryUtil.getExplainPlan(rs).contains(indexName) ? indexName2 : indexName;
+      String hintedIndex = scannedTable.contains(indexName) ? indexName2 : indexName;
       try (Admin admin = conn.unwrap(PhoenixConnection.class).getQueryServices().getAdmin()) {
         String snapshotName = new StringBuilder(hintedIndex).append("-Snapshot").toString();
         admin.snapshot(snapshotName, TableName.valueOf(hintedIndex));
@@ -232,9 +231,8 @@ public class LogicalTableNameExtendedIT extends LogicalTableNameBaseIT {
       }
       String indexSelect =
         "SELECT /*+ INDEX(" + tableName + " " + hintedIndex + ")*/ V1,V2,V3 FROM " + tableName;
-      rs = conn.createStatement().executeQuery("EXPLAIN " + indexSelect);
-      assertEquals(true, QueryUtil.getExplainPlan(rs).contains(hintedIndex));
-      rs = conn.createStatement().executeQuery(indexSelect);
+      assertPlan(conn, indexSelect).tableContains(hintedIndex);
+      ResultSet rs = conn.createStatement().executeQuery(indexSelect);
       assertEquals(true, rs.next());
     }
   }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/LogicalTableNameIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/LogicalTableNameIT.java
index d8f9bec76b..49c9c6b3b6 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/LogicalTableNameIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/LogicalTableNameIT.java
@@ -19,6 +19,7 @@ package org.apache.phoenix.end2end;
 
 import static org.apache.phoenix.mapreduce.index.PhoenixScrutinyJobCounters.INVALID_ROW_COUNT;
 import static org.apache.phoenix.mapreduce.index.PhoenixScrutinyJobCounters.VALID_ROW_COUNT;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.MetaDataUtil.VIEW_INDEX_TABLE_PREFIX;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.*;
@@ -42,7 +43,6 @@ import org.apache.phoenix.mapreduce.index.IndexScrutinyTool;
 import org.apache.phoenix.query.QueryConstants;
 import org.apache.phoenix.schema.PTable;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.SchemaUtil;
 import org.junit.BeforeClass;
 import org.junit.Ignore;
@@ -50,16 +50,12 @@ import org.junit.Test;
 import org.junit.experimental.categories.Category;
 import org.junit.runner.RunWith;
 import org.junit.runners.Parameterized;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 import org.apache.phoenix.thirdparty.com.google.common.collect.Lists;
 
 @RunWith(Parameterized.class)
 @Category(NeedsOwnMiniClusterTest.class)
 public class LogicalTableNameIT extends LogicalTableNameBaseIT {
-  private static final Logger LOGGER = LoggerFactory.getLogger(LogicalTableNameIT.class);
-
   protected boolean createChildAfterRename;
   private boolean immutable;
   private Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
@@ -213,8 +209,6 @@ public class LogicalTableNameIT extends LogicalTableNameBaseIT {
     String schemaName = "S_" + generateUniqueName();
     String tableName = "TBL_" + generateUniqueName();
     String indexName = "IDX_" + generateUniqueName();
-    String fullTableName = SchemaUtil.getTableName(schemaName, tableName);
-    String fullIndexName = SchemaUtil.getTableName(schemaName, indexName);
     try (Connection conn = getConnection(props)) {
       try (Connection conn2 = getConnection(props)) {
         test_IndexTableChange(conn, conn2, schemaName, tableName, indexName,
@@ -411,7 +405,6 @@ public class LogicalTableNameIT extends LogicalTableNameBaseIT {
         String upsert =
           "UPSERT INTO " + fullLevel2ViewName + " (PK1, V1, VIEW_COL1, CHV2) VALUES (?,?,?,?)";
         PreparedStatement upsertStmt = conn.prepareStatement(upsert);
-        ArrayList<String> row = new ArrayList<>();
         upsertStmt.setString(1, "PK10");
         upsertStmt.setString(2, "V10");
         upsertStmt.setString(3, "VIEW_COL1_10");
@@ -426,8 +419,7 @@ public class LogicalTableNameIT extends LogicalTableNameBaseIT {
 
         String indexSelect =
           "SELECT chv2, V1, VIEW_COL1 FROM " + fullLevel2ViewName + " WHERE chv2='CHV210'";
-        rs = conn2.createStatement().executeQuery("EXPLAIN " + indexSelect);
-        assertEquals(true, QueryUtil.getExplainPlan(rs).contains(VIEW_INDEX_TABLE_PREFIX));
+        assertPlan(conn2, indexSelect).tableContains(VIEW_INDEX_TABLE_PREFIX);
         rs = conn2.createStatement().executeQuery(indexSelect);
         assertEquals(true, rs.next());
         assertEquals(false, rs.next());
@@ -476,8 +468,7 @@ public class LogicalTableNameIT extends LogicalTableNameBaseIT {
     }
     Object[] arr = HashJoinGlobalIndexIT.data().toArray();
     String[] indexDDL = ((String[][]) arr[0])[0];
-    String[] plans = ((String[][]) arr[0])[1];
-    HashJoinGlobalIndexIT hjgit = new HashJoinGlobalIndexIT(indexDDL, plans);
+    HashJoinGlobalIndexIT hjgit = new HashJoinGlobalIndexIT(indexDDL);
     hjgit.createSchema();
     hjgit.testInnerJoin(false);
   }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/MaxLookbackExtendedIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/MaxLookbackExtendedIT.java
index 38a2c113db..4df082dd5a 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/MaxLookbackExtendedIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/MaxLookbackExtendedIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.assertRawCellCount;
 import static org.apache.phoenix.util.TestUtil.assertRawRowCount;
 import static org.apache.phoenix.util.TestUtil.assertRowExistsAtSCN;
@@ -52,7 +53,6 @@ import org.apache.phoenix.schema.PTable;
 import org.apache.phoenix.util.EnvironmentEdgeManager;
 import org.apache.phoenix.util.ManualEnvironmentEdge;
 import org.apache.phoenix.util.PhoenixRuntime;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.ReadOnlyProps;
 import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.TestUtil;
@@ -685,8 +685,8 @@ public class MaxLookbackExtendedIT extends BaseTest {
 
   public static void assertExplainPlan(Connection conn, String selectSql, String dataTableFullName,
     String indexTableFullName) throws SQLException {
-    ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql);
-    String actualExplainPlan = QueryUtil.getExplainPlan(rs);
-    IndexToolIT.assertExplainPlan(false, actualExplainPlan, dataTableFullName, indexTableFullName);
+    // Verify the query is served by a RANGE SCAN over the (global) index table.
+    assertPlan(conn, selectSql).scanType("RANGE SCAN")
+      .tableContains(SchemaUtil.normalizeIdentifier(indexTableFullName));
   }
 }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/MaxLookbackIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/MaxLookbackIT.java
index 881a1198a3..fc1baa642e 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/MaxLookbackIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/MaxLookbackIT.java
@@ -18,6 +18,7 @@
 package org.apache.phoenix.end2end;
 
 import static org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants.PHOENIX_MAX_LOOKBACK_AGE_CONF_KEY;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.assertRawCellCount;
 import static org.apache.phoenix.util.TestUtil.assertRawRowCount;
 import static org.apache.phoenix.util.TestUtil.assertRowExistsAtSCN;
@@ -28,7 +29,6 @@ import static org.junit.Assert.assertFalse;
 import java.io.IOException;
 import java.sql.Connection;
 import java.sql.DriverManager;
-import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
 import java.util.Map;
@@ -44,8 +44,8 @@ import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.util.EnvironmentEdgeManager;
 import org.apache.phoenix.util.ManualEnvironmentEdge;
 import org.apache.phoenix.util.PhoenixRuntime;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.ReadOnlyProps;
+import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.TestUtil;
 import org.junit.After;
 import org.junit.Assert;
@@ -390,9 +390,9 @@ public class MaxLookbackIT extends BaseTest {
 
   public static void assertExplainPlan(Connection conn, String selectSql, String dataTableFullName,
     String indexTableFullName) throws SQLException {
-    ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql);
-    String actualExplainPlan = QueryUtil.getExplainPlan(rs);
-    IndexToolIT.assertExplainPlan(false, actualExplainPlan, dataTableFullName, indexTableFullName);
+    // Verify the query is served by a RANGE SCAN over the (global) index table.
+    assertPlan(conn, selectSql).scanType("RANGE SCAN")
+      .tableContains(SchemaUtil.normalizeIdentifier(indexTableFullName));
   }
 
 }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/MultiCfQueryExecIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/MultiCfQueryExecIT.java
index 6b9a15b024..a5e3612397 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/MultiCfQueryExecIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/MultiCfQueryExecIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.apache.phoenix.util.TestUtil.analyzeTable;
 import static org.apache.phoenix.util.TestUtil.getAllSplits;
@@ -36,7 +37,6 @@ import java.util.List;
 import java.util.Properties;
 import org.apache.phoenix.query.KeyRange;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.TestUtil;
 import org.junit.Before;
@@ -536,10 +536,7 @@ public class MultiCfQueryExecIT extends ParallelStatsEnabledIT {
       // Tests for FORWARD_SCAN hint
       String query =
         "SELECT /*+ FORWARD_SCAN */ * FROM " + tableName + " WHERE COL2 = 'AAA' ORDER BY COL1 DESC";
-      try (ResultSet rs = stmt.executeQuery("EXPLAIN " + query)) {
-        String explainPlan = QueryUtil.getExplainPlan(rs);
-        assertFalse(explainPlan.contains("REVERSE"));
-      }
+      assertPlan(conn, query).clientSortedBy(null);
       try (ResultSet rs = stmt.executeQuery(query)) {
         assertTrue(rs.next());
         assertEquals(rs.getString("COL1"), "222");
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/OnDuplicateKey2IT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/OnDuplicateKey2IT.java
index b5a7b055f9..52d0e4ba4a 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/OnDuplicateKey2IT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/OnDuplicateKey2IT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
@@ -47,8 +48,6 @@ import org.apache.hadoop.hbase.client.Scan;
 import org.apache.hadoop.hbase.client.Table;
 import org.apache.hadoop.hbase.util.Pair;
 import org.apache.hadoop.hbase.util.VersionInfo;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.jdbc.PhoenixConnection;
 import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.jdbc.PhoenixStatement;
@@ -381,14 +380,12 @@ public class OnDuplicateKey2IT extends ParallelStatsDisabledIT {
     }
     assertFalse(resultSet.next());
 
-    ExplainPlan plan =
-      preparedStatement.unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals(indexDDL.contains("index")
+    String expectedTable = indexDDL.contains("index")
       ? (indexDDL.contains("local index")
         ? tableName + "_IDX(" + tableName + ")"
         : tableName + "_IDX")
-      : tableName, explainPlanAttributes.getTableName());
+      : tableName;
+    assertPlan(preparedStatement.unwrap(PhoenixPreparedStatement.class)).table(expectedTable);
   }
 
   private static void validateMultiRowDelete(String tableName, Connection conn,
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/OnDuplicateKeyIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/OnDuplicateKeyIT.java
index 754933b510..c004ccb40f 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/OnDuplicateKeyIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/OnDuplicateKeyIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -48,7 +49,7 @@ import org.apache.phoenix.util.EncodedColumnsUtil;
 import org.apache.phoenix.util.EnvironmentEdgeManager;
 import org.apache.phoenix.util.PhoenixRuntime;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
+import org.apache.phoenix.util.SchemaUtil;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 import org.junit.runner.RunWith;
@@ -561,10 +562,13 @@ public class OnDuplicateKeyIT extends ParallelStatsDisabledIT {
     ResultSet rs;
     String selectSql = "SELECT * FROM " + tableName + " WHERE counter1 >= 0";
     if (isIndexCreated) {
-      rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql);
-      String actualExplainPlan = QueryUtil.getExplainPlan(rs);
-      IndexToolIT.assertExplainPlan(this.indexDDL.contains("local"), actualExplainPlan, tableName,
-        tableName + "_IDX");
+      // Verify the query is served by a RANGE SCAN over the index table. For a local index the
+      // scanned name carries the data table in parentheses, e.g. IDX(DATA).
+      boolean localIndex = this.indexDDL.contains("local");
+      String index = SchemaUtil.normalizeIdentifier(tableName + "_IDX");
+      String expectedTable =
+        localIndex ? index + "(" + SchemaUtil.normalizeIdentifier(tableName) + ")" : index;
+      assertPlan(conn, selectSql).scanType("RANGE SCAN").tableContains(expectedTable);
     }
     rs = conn.createStatement().executeQuery(selectSql);
     assertTrue(rs.next());
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ParallelStatsDisabledIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ParallelStatsDisabledIT.java
index 8a1e55ad3a..378498e6d2 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ParallelStatsDisabledIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ParallelStatsDisabledIT.java
@@ -17,20 +17,16 @@
  */
 package org.apache.phoenix.end2end;
 
-import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
 import java.sql.Connection;
 import java.sql.ResultSet;
-import java.sql.SQLException;
 import java.util.Map;
-import org.apache.commons.lang3.StringUtils;
 import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
 import org.apache.phoenix.query.BaseTest;
 import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.util.QueryBuilder;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.ReadOnlyProps;
 import org.junit.AfterClass;
 import org.junit.BeforeClass;
@@ -72,12 +68,4 @@ public abstract class ParallelStatsDisabledIT extends BaseTest {
     }
     return rs;
   }
-
-  public static void validateQueryPlan(Connection conn, QueryBuilder queryBuilder,
-    String expectedPhoenixPlan, String expectedSparkPlan) throws SQLException {
-    if (StringUtils.isNotBlank(expectedPhoenixPlan)) {
-      ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + queryBuilder.build());
-      assertEquals(expectedPhoenixPlan, QueryUtil.getExplainPlan(rs));
-    }
-  }
 }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ParallelStatsDisabledWithRegionMovesIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ParallelStatsDisabledWithRegionMovesIT.java
index 5de095496f..e556f808d7 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ParallelStatsDisabledWithRegionMovesIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ParallelStatsDisabledWithRegionMovesIT.java
@@ -27,7 +27,6 @@ import static org.junit.Assert.fail;
 import java.io.IOException;
 import java.sql.Connection;
 import java.sql.ResultSet;
-import java.sql.SQLException;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -37,7 +36,6 @@ import java.util.Set;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
-import org.apache.commons.lang3.StringUtils;
 import org.apache.hadoop.hbase.HConstants;
 import org.apache.hadoop.hbase.ServerName;
 import org.apache.hadoop.hbase.TableName;
@@ -56,7 +54,6 @@ import org.apache.phoenix.query.BaseTest;
 import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.util.ByteUtil;
 import org.apache.phoenix.util.QueryBuilder;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.ReadOnlyProps;
 import org.junit.AfterClass;
 import org.junit.BeforeClass;
@@ -253,14 +250,6 @@ public abstract class ParallelStatsDisabledWithRegionMovesIT extends BaseTest {
     return rs;
   }
 
-  public static void validateQueryPlan(Connection conn, QueryBuilder queryBuilder,
-    String expectedPhoenixPlan, String expectedSparkPlan) throws SQLException {
-    if (StringUtils.isNotBlank(expectedPhoenixPlan)) {
-      ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + queryBuilder.build());
-      assertEquals(expectedPhoenixPlan, QueryUtil.getExplainPlan(rs));
-    }
-  }
-
   protected static void assertResultSetWithRegionMoves(ResultSet rs, Object[][] rows,
     String tableName) throws Exception {
     for (int rowIndex = 0; rowIndex < rows.length; rowIndex++) {
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProjectArrayElemAfterHashJoinIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProjectArrayElemAfterHashJoinIT.java
index 40545af925..0b882f3a16 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProjectArrayElemAfterHashJoinIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ProjectArrayElemAfterHashJoinIT.java
@@ -17,6 +17,8 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.getExplainAttributes;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -28,8 +30,8 @@ import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.Statement;
 import java.util.Properties;
+import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
@@ -109,18 +111,12 @@ public class ProjectArrayElemAfterHashJoinIT extends ParallelStatsDisabledIT {
   private void verifyExplain(Connection conn, String table, boolean fullArray, boolean hashJoin)
     throws Exception {
 
-    String query = "EXPLAIN " + getQuery(table, fullArray, hashJoin);
-    Statement stmt = conn.createStatement();
-    ResultSet rs = stmt.executeQuery(query);
-
-    try {
-      String plan = QueryUtil.getExplainPlan(rs);
-      assertTrue(plan != null);
-      assertTrue(fullArray || plan.contains("SERVER ARRAY ELEMENT PROJECTION"));
-      assertTrue(hashJoin == plan.contains("JOIN"));
-    } finally {
-      rs.close();
+    String query = getQuery(table, fullArray, hashJoin);
+    ExplainPlanAttributes attributes = getExplainAttributes(conn, query);
+    if (!fullArray) {
+      assertPlan(attributes).serverArrayElementProjection(true);
     }
+    assertPlan(attributes).subPlanCount(hashJoin ? 1 : 0);
   }
 
   private void verifyResults(Connection conn, String table, boolean fullArray, boolean hashJoin)
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryLoggerIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryLoggerIT.java
index 6504c92bca..cdfe3ab2f1 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryLoggerIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryLoggerIT.java
@@ -127,6 +127,8 @@ public class QueryLoggerIT extends BaseTest {
           assertEquals(rs.getString(BIND_PARAMETERS), null);
           assertEquals(rs.getString(USER), System.getProperty("user.name"));
           assertEquals(rs.getString(CLIENT_IP), InetAddress.getLocalHost().getHostAddress());
+          // The EXPLAIN_PLAN column logged by the query logger must be equal to a freshly
+          // computed plan.
           assertEquals(rs.getString(EXPLAIN_PLAN), QueryUtil.getExplainPlan(explainRS));
           assertEquals(rs.getString(GLOBAL_SCAN_DETAILS), context.getScan().toJSON());
           assertEquals(rs.getLong(NO_OF_RESULTS_ITERATED), 10);
@@ -311,6 +313,8 @@ public class QueryLoggerIT extends BaseTest {
               loglevel == LogLevel.TRACE ? "value5" : null);
             assertEquals(rs.getString(USER), System.getProperty("user.name"));
             assertEquals(rs.getString(CLIENT_IP), InetAddress.getLocalHost().getHostAddress());
+            // The EXPLAIN_PLAN column logged by the query logger must be equal to a freshly
+            // computed plan.
             assertEquals(rs.getString(EXPLAIN_PLAN), QueryUtil.getExplainPlan(explainRS));
             assertEquals(rs.getString(GLOBAL_SCAN_DETAILS), context.getScan().toJSON());
             assertEquals(rs.getLong(NO_OF_RESULTS_ITERATED), 1);
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryWithLimitIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryWithLimitIT.java
index 2278f7341c..e7666f9a68 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryWithLimitIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryWithLimitIT.java
@@ -18,6 +18,7 @@
 package org.apache.phoenix.end2end;
 
 import static org.apache.phoenix.query.QueryServicesOptions.UNLIMITED_QUEUE_SIZE;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
@@ -31,9 +32,6 @@ import java.sql.SQLException;
 import java.util.Map;
 import java.util.Properties;
 import java.util.concurrent.RejectedExecutionException;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.BaseTest;
 import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.util.PropertiesUtil;
@@ -91,15 +89,8 @@ public class QueryWithLimitIT extends BaseTest {
       assertEquals(0, rs.getInt(1));
       assertFalse(rs.next());
 
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("SERIAL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(tableName, explainPlanAttributes.getTableName());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-      assertEquals(1, explainPlanAttributes.getServerRowLimit().intValue());
-      assertEquals(1, explainPlanAttributes.getClientRowLimit().intValue());
+      assertPlan(conn, query).iteratorType("SERIAL 1-WAY").scanType("FULL SCAN").table(tableName)
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").serverRowLimit(1L).clientRowLimit(1);
     } finally {
       conn.close();
     }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryWithOffsetIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryWithOffsetIT.java
index 65ec34ff08..6cda98ab04 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryWithOffsetIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryWithOffsetIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -33,9 +34,6 @@ import java.sql.Types;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Properties;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.util.PropertiesUtil;
 import org.junit.Before;
@@ -129,20 +127,14 @@ public class QueryWithOffsetIT extends ParallelStatsDisabledIT {
     initTableValues(conn);
     updateStatistics(conn);
     String query = "SELECT t_id from " + tableName + " offset " + offset;
-    ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-      .optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals("SERVER FILTER BY EMPTY COLUMN ONLY",
-      explainPlanAttributes.getServerWhereFilter());
     if (!isSalted) {
-      assertEquals("SERIAL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals(offset, explainPlanAttributes.getServerOffset().intValue());
+      assertPlan(conn, query).scanType("FULL SCAN").table(tableName)
+        .serverWhereFilter("SERVER FILTER BY EMPTY COLUMN ONLY").iteratorType("SERIAL 1-WAY")
+        .serverOffset(offset);
     } else {
-      assertEquals("PARALLEL 10-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-      assertEquals(offset, explainPlanAttributes.getClientOffset().intValue());
+      assertPlan(conn, query).scanType("FULL SCAN").table(tableName)
+        .serverWhereFilter("SERVER FILTER BY EMPTY COLUMN ONLY").iteratorType("PARALLEL 10-WAY")
+        .clientSortAlgo("CLIENT MERGE SORT").clientOffset(offset);
     }
 
     ResultSet rs = conn.createStatement().executeQuery(query);
@@ -152,22 +144,16 @@ public class QueryWithOffsetIT extends ParallelStatsDisabledIT {
       assertEquals(STRINGS[offset + i - 1], rs.getString(1));
     }
     query = "SELECT t_id from " + tableName + " ORDER BY v1 offset " + offset;
-    plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-      .getExplainPlan();
-    explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals("[C2.V1]", explainPlanAttributes.getServerSortedBy());
-    assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-    assertEquals(offset, explainPlanAttributes.getClientOffset().intValue());
     if (!isSalted) {
       // When Parallel stats is actually disabled, it is PARALLEL 4-WAY
       // CLIENT PARALLEL 4-WAY FULL SCAN OVER T_N000001
       // SERVER SORTED BY [C2.V1] CLIENT MERGE SORT CLIENT OFFSET 10
       // When enabled, it is 5-WAY
-      assertEquals("PARALLEL 4-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
+      assertPlan(conn, query).scanType("FULL SCAN").table(tableName).serverSortedBy("[C2.V1]")
+        .clientSortAlgo("CLIENT MERGE SORT").clientOffset(offset).iteratorType("PARALLEL 4-WAY");
     } else {
-      assertEquals("PARALLEL 10-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
+      assertPlan(conn, query).scanType("FULL SCAN").table(tableName).serverSortedBy("[C2.V1]")
+        .clientSortAlgo("CLIENT MERGE SORT").clientOffset(offset).iteratorType("PARALLEL 10-WAY");
     }
     conn.close();
   }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryWithTableSampleIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryWithTableSampleIT.java
index 045e20aabf..ddbf213c45 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryWithTableSampleIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryWithTableSampleIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
@@ -26,12 +27,8 @@ import java.sql.DriverManager;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.util.Properties;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.exception.PhoenixParserException;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.TestUtil;
 import org.junit.Before;
 import org.junit.Test;
@@ -56,7 +53,7 @@ public class QueryWithTableSampleIT extends ParallelStatsEnabledIT {
       prepareTableWithValues(conn, 100);
       String query = "SELECT i1, i2 FROM " + tableName + " tablesample 15 ";
 
-      ResultSet rs = conn.createStatement().executeQuery(query);
+      conn.createStatement().executeQuery(query);
     } finally {
       conn.close();
     }
@@ -70,7 +67,7 @@ public class QueryWithTableSampleIT extends ParallelStatsEnabledIT {
       prepareTableWithValues(conn, 100);
       String query = "SELECT i1, i2 FROM " + tableName + " tablesample (175) ";
 
-      ResultSet rs = conn.createStatement().executeQuery(query);
+      conn.createStatement().executeQuery(query);
     } finally {
       conn.close();
     }
@@ -214,14 +211,8 @@ public class QueryWithTableSampleIT extends ParallelStatsEnabledIT {
     try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
       prepareTableWithValues(conn, 100);
       String query = "SELECT i1, i2 FROM " + tableName + " tablesample (45) ";
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(0.45D, explainPlanAttributes.getSamplingRate(), 0D);
-      assertEquals(tableName, explainPlanAttributes.getTableName());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
+      assertPlan(conn, query).iteratorType("PARALLEL").scanType("FULL SCAN").samplingRate(0.45d)
+        .table(tableName).serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY");
     }
   }
 
@@ -231,17 +222,14 @@ public class QueryWithTableSampleIT extends ParallelStatsEnabledIT {
     Connection conn = DriverManager.getConnection(getUrl(), props);
     try {
       prepareTableWithValues(conn, 100);
-      String query = "EXPLAIN SELECT * FROM " + tableName
-        + " tablesample (100) where i1<2 union all SELECT * FROM " + tableName
-        + " tablesample (2) where i2<6000";
-      ResultSet rs = conn.createStatement().executeQuery(query);
-
-      assertEquals(
-        "UNION ALL OVER 2 QUERIES\n" + "    CLIENT PARALLEL 1-WAY 1.0-SAMPLED RANGE SCAN OVER "
-          + tableName + " [*] - [2]\n" + "        SERVER FILTER BY FIRST KEY ONLY\n"
-          + "    CLIENT PARALLEL 1-WAY 0.02-SAMPLED FULL SCAN OVER " + tableName + "\n"
-          + "        SERVER FILTER BY FIRST KEY ONLY AND I2 < 6000",
-        QueryUtil.getExplainPlan(rs));
+      String query =
+        "SELECT * FROM " + tableName + " tablesample (100) where i1<2 union all SELECT * FROM "
+          + tableName + " tablesample (2) where i2<6000";
+      assertPlan(conn, query).abstractExplainPlan("UNION ALL OVER 2 QUERIES").scanType("RANGE SCAN")
+        .table(tableName).keyRanges(" [*] - [2]").samplingRate(1.0d)
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").rhs().scanType("FULL SCAN")
+        .table(tableName).samplingRate(0.02d)
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY AND I2 < 6000").end();
     } finally {
       conn.close();
     }
@@ -253,17 +241,16 @@ public class QueryWithTableSampleIT extends ParallelStatsEnabledIT {
     Connection conn = DriverManager.getConnection(getUrl(), props);
     try {
       prepareTableWithValues(conn, 100);
-      String query = "EXPLAIN SELECT count(*) FROM " + tableName + " as A tablesample (45), "
+      String query = "SELECT count(*) FROM " + tableName + " as A tablesample (45), "
         + joinedTableName + " as B tablesample (75) where A.i1=B.i1";
-      System.out.println(query);
-      ResultSet rs = conn.createStatement().executeQuery(query);
 
-      assertEquals("CLIENT PARALLEL 1-WAY 0.45-SAMPLED FULL SCAN OVER " + tableName + "\n"
-        + "    SERVER FILTER BY FIRST KEY ONLY\n" + "    SERVER AGGREGATE INTO SINGLE ROW\n"
-        + "    PARALLEL INNER-JOIN TABLE 0 (SKIP MERGE)\n"
-        + "        CLIENT PARALLEL 1-WAY 0.75-SAMPLED FULL SCAN OVER " + joinedTableName + "\n"
-        + "            SERVER FILTER BY FIRST KEY ONLY\n"
-        + "    DYNAMIC SERVER FILTER BY A.I1 IN (B.I1)", QueryUtil.getExplainPlan(rs));
+      assertPlan(conn, query).scanType("FULL SCAN").table(tableName).samplingRate(0.45d)
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .serverAggregate("SERVER AGGREGATE INTO SINGLE ROW")
+        .dynamicServerFilter("DYNAMIC SERVER FILTER BY A.I1 IN (B.I1)").subPlanCount(1).subPlan(0)
+        .abstractExplainPlan("PARALLEL INNER-JOIN TABLE 0 (SKIP MERGE)").scanType("FULL SCAN")
+        .table(joinedTableName).samplingRate(0.75d)
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").end();
     } finally {
       conn.close();
     }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/RTrimFunctionIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/RTrimFunctionIT.java
index b15d4d424e..e0f04eeab6 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/RTrimFunctionIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/RTrimFunctionIT.java
@@ -17,8 +17,8 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
-import static org.junit.Assert.assertTrue;
 
 import java.sql.Connection;
 import java.sql.DriverManager;
@@ -28,7 +28,6 @@ import java.util.List;
 import java.util.Properties;
 import org.apache.phoenix.schema.SortOrder;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
@@ -66,8 +65,7 @@ public class RTrimFunctionIT extends ParallelStatsDisabledIT {
     ResultSet rs = conn.createStatement().executeQuery(query);
     assertValueEqualsResultSet(rs, expectedResults);
 
-    rs = conn.createStatement().executeQuery("explain " + query);
-    assertTrue(QueryUtil.getExplainPlan(rs).contains("RANGE SCAN OVER " + tableName));
+    assertPlan(conn, query).scanType("RANGE SCAN").table(tableName);
 
     conn.close();
   }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ReverseScanIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ReverseScanIT.java
index 2fcf0c6a3e..d3eb617786 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ReverseScanIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ReverseScanIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.ROW2;
 import static org.apache.phoenix.util.TestUtil.ROW3;
 import static org.apache.phoenix.util.TestUtil.ROW4;
@@ -37,9 +38,6 @@ import java.sql.ResultSet;
 import java.sql.Statement;
 import java.util.Properties;
 import org.apache.hadoop.hbase.util.Bytes;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.util.PropertiesUtil;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -81,15 +79,9 @@ public class ReverseScanIT extends ParallelStatsDisabledIT {
 
       assertFalse(rs.next());
 
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("REVERSE", explainPlanAttributes.getClientSortedBy());
-      assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(tableName, explainPlanAttributes.getTableName());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY AND ENTITY_ID >= '00A323122312312'",
-        explainPlanAttributes.getServerWhereFilter());
+      assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").clientSortedBy("REVERSE")
+        .scanType("FULL SCAN").table(tableName)
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY AND ENTITY_ID >= '00A323122312312'");
 
       PreparedStatement statement = conn.prepareStatement("SELECT entity_id FROM " + tableName
         + " WHERE organization_id = ? AND entity_id >= ? ORDER BY organization_id DESC, entity_id DESC");
@@ -185,17 +177,9 @@ public class ReverseScanIT extends ParallelStatsDisabledIT {
       assertEquals(1, rs.getInt(1));
       assertFalse(rs.next());
 
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("SERIAL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("REVERSE", explainPlanAttributes.getClientSortedBy());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(indexName, explainPlanAttributes.getTableName());
-      assertEquals(" [not null]", explainPlanAttributes.getKeyRanges());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-      assertEquals(1, explainPlanAttributes.getServerRowLimit().intValue());
-      assertEquals(1, explainPlanAttributes.getClientRowLimit().intValue());
+      assertPlan(conn, query).iteratorType("SERIAL 1-WAY").clientSortedBy("REVERSE")
+        .scanType("RANGE SCAN").table(indexName).keyRanges(" [not null]")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").serverRowLimit(1L).clientRowLimit(1);
     }
 
   }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/RowValueConstructorIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/RowValueConstructorIT.java
index a10cc8745d..2757800b6d 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/RowValueConstructorIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/RowValueConstructorIT.java
@@ -18,6 +18,7 @@
 package org.apache.phoenix.end2end;
 
 import static org.apache.phoenix.query.QueryConstants.MILLIS_IN_DAY;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.ENTITYHISTID1;
 import static org.apache.phoenix.util.TestUtil.ENTITYHISTID3;
 import static org.apache.phoenix.util.TestUtil.ENTITYHISTID7;
@@ -54,8 +55,6 @@ import java.util.List;
 import java.util.Properties;
 import org.apache.hadoop.hbase.TableName;
 import org.apache.hadoop.hbase.util.Bytes;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.jdbc.PhoenixStatement;
 import org.apache.phoenix.util.DateUtil;
@@ -1349,14 +1348,9 @@ public class RowValueConstructorIT extends ParallelStatsDisabledIT {
 
       assertFalse(rs.next());
 
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 4-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("SKIP SCAN ON 12 KEYS ", explainPlanAttributes.getExplainScanType());
-      assertEquals(tempTableWithCompositePK, explainPlanAttributes.getTableName());
-      assertEquals(" [X'00',2] - [X'03',4]", explainPlanAttributes.getKeyRanges());
-      assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+      assertPlan(conn, query).iteratorType("PARALLEL 4-WAY").scanType("SKIP SCAN ON 12 KEYS")
+        .table(tempTableWithCompositePK).keyRanges(" [X'00',2] - [X'03',4]")
+        .clientSortAlgo("CLIENT MERGE SORT");
     } finally {
       conn.close();
     }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/RowValueConstructorOffsetIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/RowValueConstructorOffsetIT.java
index 1df2089056..590c793db9 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/RowValueConstructorOffsetIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/RowValueConstructorOffsetIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
@@ -41,7 +42,6 @@ import org.apache.phoenix.schema.PTableType;
 import org.apache.phoenix.schema.RowValueConstructorOffsetNotCoercibleException;
 import org.apache.phoenix.util.PhoenixRuntime;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.junit.AfterClass;
 import org.junit.BeforeClass;
 import org.junit.Test;
@@ -1079,16 +1079,8 @@ public class RowValueConstructorOffsetIT extends ParallelStatsDisabledIT {
 
   @Test
   public void testOffsetExplain() throws SQLException {
-    String sql =
-      "EXPLAIN SELECT * FROM " + DATA_TABLE_NAME + "  LIMIT 2 OFFSET (k1,k2,k3)=(2, 3, 2)";
-    try (Statement statement = conn.createStatement(); ResultSet rs = statement.executeQuery(sql)) {
-      StringBuilder explainStringBuilder = new StringBuilder();
-      while (rs.next()) {
-        String explain = rs.getString(1);
-        explainStringBuilder.append(explain);
-      }
-      assertTrue(explainStringBuilder.toString().contains("With RVC Offset"));
-    }
+    String sql = "SELECT * FROM " + DATA_TABLE_NAME + "  LIMIT 2 OFFSET (k1,k2,k3)=(2, 3, 2)";
+    assertPlan(conn, sql).hexStringRVCOffset("0x828383");
   }
 
   @Test
@@ -1271,12 +1263,8 @@ public class RowValueConstructorOffsetIT extends ParallelStatsDisabledIT {
       "SELECT /*+ INDEX(%s %s)*/ %s FROM %s "
         + "WHERE t_id = 'b' AND k1 = 2 AND k2 = 3 OFFSET (%s)=('a', 1, 2)",
       TABLE_NAME, INDEX_NAME, TABLE_ROW_KEY, TABLE_NAME, TABLE_ROW_KEY);
-    try (Statement statement = conn.createStatement()) {
-      ResultSet rs = statement.executeQuery("EXPLAIN " + sql);
-      String actualQueryPlan = QueryUtil.getExplainPlan(rs);
-      // As hinted plan is not applicable so use data plan which is point lookup
-      assertTrue(actualQueryPlan.contains("POINT LOOKUP ON 1 KEY OVER " + TABLE_NAME));
-    }
+    // As hinted plan is not applicable so use data plan which is point lookup
+    assertPlan(conn, sql).scanType("POINT LOOKUP ON 1 KEY").table(TABLE_NAME);
   }
 
   @Test
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/SequenceBulkAllocationIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/SequenceBulkAllocationIT.java
index 85133397d4..697b1aad8b 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/SequenceBulkAllocationIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/SequenceBulkAllocationIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.PhoenixRuntime.TENANT_ID_ATTRIB;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
@@ -37,10 +38,7 @@ import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.exception.SQLExceptionCode;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.util.PropertiesUtil;
 import org.apache.phoenix.util.SchemaUtil;
 import org.junit.After;
@@ -825,14 +823,8 @@ public class SequenceBulkAllocationIT extends ParallelStatsDisabledIT {
     String query = "SELECT NEXT 1000 VALUES FOR  " + sequenceName + "  FROM " + tableName;
 
     // Assert output for Explain Plain result is as expected
-    ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-      .optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals(1, explainPlanAttributes.getClientSequenceCount().intValue());
+    assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").table(tableName)
+      .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").clientSequenceCount(1);
   }
 
   /**
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/SequenceIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/SequenceIT.java
index 3cc3a0510d..0ff1bb53db 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/SequenceIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/SequenceIT.java
@@ -20,6 +20,7 @@ package org.apache.phoenix.end2end;
 import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA;
 import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TYPE_SEQUENCE;
 import static org.apache.phoenix.query.QueryServicesTestImpl.DEFAULT_SEQUENCE_CACHE_SIZE;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -35,12 +36,9 @@ import java.sql.SQLException;
 import java.sql.Statement;
 import java.util.List;
 import java.util.Properties;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.exception.SQLExceptionCode;
 import org.apache.phoenix.jdbc.PhoenixConnection;
 import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.jdbc.PhoenixStatement;
 import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.query.QueryServicesTestImpl;
@@ -824,14 +822,8 @@ public class SequenceIT extends ParallelStatsDisabledIT {
     Connection conn2 =
       DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TEST_PROPERTIES));
     String query = "SELECT NEXT VALUE FOR " + sequenceName + " FROM " + tableName;
-    ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-      .optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals(1, explainPlanAttributes.getClientSequenceCount().intValue());
+    assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").table(tableName)
+      .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").clientSequenceCount(1);
 
     ResultSet rs = conn.createStatement().executeQuery(
       "SELECT sequence_name, current_value FROM \"SYSTEM\".\"SEQUENCE\" WHERE sequence_name='"
@@ -1484,20 +1476,14 @@ public class SequenceIT extends ParallelStatsDisabledIT {
       .execute("CREATE SEQUENCE " + secondSeqName + " START WITH 2 INCREMENT BY 3");
 
     String query = "SELECT NEXT VALUE FOR " + seqName;
-    ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-      .optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals(new Integer(1), explainPlanAttributes.getClientSequenceCount());
+    assertPlan(conn, query).clientSequenceCount(1);
 
     rs = conn.createStatement().executeQuery(query);
     assertTrue(rs.next());
     assertEquals(1, rs.getInt(1));
 
     query = "SELECT CURRENT VALUE FOR " + seqName;
-    plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-      .getExplainPlan();
-    explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals(new Integer(1), explainPlanAttributes.getClientSequenceCount());
+    assertPlan(conn, query).clientSequenceCount(1);
 
     rs = conn.createStatement().executeQuery(query);
     assertTrue(rs.next());
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ServerPagingIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ServerPagingIT.java
index b86793badb..175ea4cd73 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ServerPagingIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ServerPagingIT.java
@@ -17,11 +17,11 @@
  */
 package org.apache.phoenix.end2end;
 
-import static org.apache.phoenix.end2end.index.GlobalIndexCheckerIT.assertExplainPlan;
 import static org.apache.phoenix.end2end.index.GlobalIndexCheckerIT.assertExplainPlanWithLimit;
 import static org.apache.phoenix.end2end.index.GlobalIndexCheckerIT.commitWithException;
 import static org.apache.phoenix.monitoring.GlobalClientMetrics.GLOBAL_PAGED_ROWS_COUNTER;
 import static org.apache.phoenix.query.QueryServices.USE_BLOOMFILTER_FOR_MULTIKEY_POINTLOOKUP;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -46,7 +46,6 @@ import org.apache.hadoop.hbase.util.Bytes;
 import org.apache.phoenix.coprocessor.PagingRegionScanner;
 import org.apache.phoenix.hbase.index.IndexRegionObserver;
 import org.apache.phoenix.jdbc.PhoenixConnection;
-import org.apache.phoenix.jdbc.PhoenixResultSet;
 import org.apache.phoenix.jdbc.PhoenixStatement;
 import org.apache.phoenix.monitoring.MetricType;
 import org.apache.phoenix.query.QueryServices;
@@ -55,7 +54,6 @@ import org.apache.phoenix.util.ByteUtil;
 import org.apache.phoenix.util.DateUtil;
 import org.apache.phoenix.util.PhoenixRuntime;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.ReadOnlyProps;
 import org.junit.Assert;
 import org.junit.BeforeClass;
@@ -146,11 +144,9 @@ public class ServerPagingIT extends ParallelStatsDisabledIT {
       conn.createStatement().execute(ddl);
       conn.commit();
 
+      assertPlan(conn, "select * from " + tablename + " limit " + limit).tableContains(indexName);
       stmt = conn.prepareStatement("select * from " + tablename + " limit " + limit);
       try (ResultSet rs = stmt.executeQuery()) {
-        PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
-        String explainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
-        assertTrue(explainPlan.contains(indexName));
         int expectedRowCount = 0;
         int expectedId1 = 4;
         int expectedId2 = 0;
@@ -434,10 +430,8 @@ public class ServerPagingIT extends ParallelStatsDisabledIT {
       }
       conn.commit();
       String dql = String.format("SELECT count(*) from %s where k3 = 5", tablename);
+      assertPlan(conn, dql).tableContains(indexname);
       try (ResultSet rs = conn.createStatement().executeQuery(dql)) {
-        PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
-        String explainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
-        assertTrue(explainPlan.contains(indexname));
         assertTrue(rs.next());
         assertEquals(totalRows / 10, rs.getInt(1));
         assertFalse(rs.next());
@@ -462,10 +456,8 @@ public class ServerPagingIT extends ParallelStatsDisabledIT {
       } finally {
         IndexRegionObserver.setFailDataTableUpdatesForTesting(false);
       }
+      assertPlan(conn, dql).tableContains(indexname);
       try (ResultSet rs = conn.createStatement().executeQuery(dql)) {
-        PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
-        String explainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
-        assertTrue(explainPlan.contains(indexname));
         assertTrue(rs.next());
         assertEquals(totalRows / 10, rs.getInt(1));
         assertFalse(rs.next());
@@ -658,7 +650,7 @@ public class ServerPagingIT extends ParallelStatsDisabledIT {
 
       selectSql = "SELECT count(val3) from " + dataTableName + " where val1 > '0' GROUP BY val1";
       // Verify that we will read from the index table
-      assertExplainPlan(conn, selectSql, dataTableName, indexTableName);
+      assertPlan(conn, selectSql).scanType("RANGE SCAN").tableContains(indexTableName);
       rs = conn.createStatement().executeQuery(selectSql);
       assertTrue(rs.next());
       assertEquals(2, rs.getInt(1));
@@ -668,7 +660,7 @@ public class ServerPagingIT extends ParallelStatsDisabledIT {
 
       selectSql = "SELECT count(val3) from " + dataTableName + " where val1 > '0'";
       // Verify that we will read from the index table
-      assertExplainPlan(conn, selectSql, dataTableName, indexTableName);
+      assertPlan(conn, selectSql).scanType("RANGE SCAN").tableContains(indexTableName);
       rs = conn.createStatement().executeQuery(selectSql);
       assertTrue(rs.next());
       assertEquals(3, rs.getInt(1));
@@ -676,7 +668,7 @@ public class ServerPagingIT extends ParallelStatsDisabledIT {
       // Run an order by query where the uncovered index should be used
       selectSql = "SELECT val3 from " + dataTableName + " where val1 > '0' ORDER BY val1";
       // Verify that we will read from the index table
-      assertExplainPlan(conn, selectSql, dataTableName, indexTableName);
+      assertPlan(conn, selectSql).scanType("RANGE SCAN").tableContains(indexTableName);
       rs = conn.createStatement().executeQuery(selectSql);
       assertTrue(rs.next());
       assertEquals("abcd", rs.getString(1));
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/SortMergeJoinMoreIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/SortMergeJoinMoreIT.java
index 24a5099134..1a57ae39e0 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/SortMergeJoinMoreIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/SortMergeJoinMoreIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.apache.phoenix.util.TestUtil.assertResultSet;
 import static org.junit.Assert.assertEquals;
@@ -30,7 +31,6 @@ import java.sql.ResultSet;
 import java.sql.Statement;
 import java.util.Properties;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
@@ -419,40 +419,32 @@ public class SortMergeJoinMoreIT extends ParallelStatsDisabledIT {
           + "         ) L\n" + "     ON L.BUCKET = E.BUCKET AND L.TIMESTAMP = E.TIMESTAMP\n"
           + " ) C\n" + " GROUP BY C.BUCKET, C.TIMESTAMP ORDER BY C.BUCKET, C.TIMESTAMP";
 
-        String p = i == 0
-          ? "SORT-MERGE-JOIN (INNER) TABLES\n"
-            + "    CLIENT PARALLEL 2-WAY SKIP SCAN ON 2 RANGES OVER " + eventCountTableName
-            + " [X'00','5SEC',~1462993520000000000,'Tr/Bal'] - [X'01','5SEC',~1462993420000000000,'Tr/Bal']\n"
-            + "        SERVER FILTER BY FIRST KEY ONLY\n"
-            + "        SERVER DISTINCT PREFIX FILTER OVER [BUCKET, TIMESTAMP, LOCATION]\n"
-            + "        SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [BUCKET, TIMESTAMP, LOCATION]\n"
-            + "    CLIENT MERGE SORT\n" + "    CLIENT SORTED BY [BUCKET, TIMESTAMP]\n"
-            + "AND (SKIP MERGE)\n" + "    CLIENT PARALLEL 2-WAY SKIP SCAN ON 2 RANGES OVER " + t[i]
-            + " [X'00','5SEC',~1462993520000000000,'Tr/Bal'] - [X'01','5SEC',~1462993420000000000,'Tr/Bal']\n"
-            + "        SERVER FILTER BY FIRST KEY ONLY AND SRC_LOCATION = DST_LOCATION\n"
-            + "        SERVER DISTINCT PREFIX FILTER OVER [BUCKET, \"TIMESTAMP\", SRC_LOCATION, DST_LOCATION]\n"
-            + "        SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [BUCKET, \"TIMESTAMP\", SRC_LOCATION, DST_LOCATION]\n"
-            + "    CLIENT MERGE SORT\n" + "    CLIENT SORTED BY [BUCKET, \"TIMESTAMP\"]\n"
-            + "CLIENT AGGREGATE INTO ORDERED DISTINCT ROWS BY [E.BUCKET, E.TIMESTAMP]"
-          : "SORT-MERGE-JOIN (INNER) TABLES\n"
-            + "    CLIENT PARALLEL 2-WAY SKIP SCAN ON 2 RANGES OVER " + eventCountTableName
-            + " [X'00','5SEC',~1462993520000000000,'Tr/Bal'] - [X'01','5SEC',~1462993420000000000,'Tr/Bal']\n"
-            + "        SERVER FILTER BY FIRST KEY ONLY\n"
-            + "        SERVER DISTINCT PREFIX FILTER OVER [BUCKET, TIMESTAMP, LOCATION]\n"
-            + "        SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [BUCKET, TIMESTAMP, LOCATION]\n"
-            + "    CLIENT MERGE SORT\n" + "    CLIENT SORTED BY [BUCKET, TIMESTAMP]\n"
-            + "AND (SKIP MERGE)\n" + "    CLIENT PARALLEL 2-WAY SKIP SCAN ON 2 RANGES OVER " + t[i]
-            + " [X'00','5SEC',1462993420000000001,'Tr/Bal'] - [X'01','5SEC',1462993520000000000,'Tr/Bal']\n"
-            + "        SERVER FILTER BY FIRST KEY ONLY AND SRC_LOCATION = DST_LOCATION\n"
-            + "        SERVER DISTINCT PREFIX FILTER OVER [BUCKET, \"TIMESTAMP\", SRC_LOCATION, DST_LOCATION]\n"
-            + "        SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [BUCKET, \"TIMESTAMP\", SRC_LOCATION, DST_LOCATION]\n"
-            + "    CLIENT MERGE SORT\n"
-            + "CLIENT AGGREGATE INTO ORDERED DISTINCT ROWS BY [E.BUCKET, E.TIMESTAMP]";
-
-        ResultSet rs = conn.createStatement().executeQuery("explain " + q);
-        assertEquals(p, QueryUtil.getExplainPlan(rs));
-
-        rs = conn.createStatement().executeQuery(q);
+        String lhsKeyRanges =
+          " [X'00','5SEC',~1462993520000000000,'Tr/Bal'] - [X'01','5SEC',~1462993420000000000,'Tr/Bal']";
+        String rhsKeyRanges = i == 0
+          ? lhsKeyRanges
+          : " [X'00','5SEC',1462993420000000001,'Tr/Bal'] - [X'01','5SEC',1462993520000000000,'Tr/Bal']";
+        String rhsClientSortedBy = i == 0 ? "[BUCKET, \"TIMESTAMP\"]" : null;
+
+        assertPlan(conn, q).abstractExplainPlan("SORT-MERGE-JOIN (INNER)").sortMergeSkipMerge(true)
+          .clientAggregate("CLIENT AGGREGATE INTO ORDERED DISTINCT ROWS BY [E.BUCKET, E.TIMESTAMP]")
+          .lhs().iteratorType("PARALLEL").scanType("SKIP SCAN ON 2 RANGES")
+          .table(eventCountTableName).keyRanges(lhsKeyRanges)
+          .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+          .serverDistinctFilter("SERVER DISTINCT PREFIX FILTER OVER [BUCKET, TIMESTAMP, LOCATION]")
+          .serverAggregate(
+            "SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [BUCKET, TIMESTAMP, LOCATION]")
+          .clientSortAlgo("CLIENT MERGE SORT").clientSortedBy("[BUCKET, TIMESTAMP]")
+          .end().rhs().iteratorType("PARALLEL").scanType("SKIP SCAN ON 2 RANGES").table(t[i])
+          .keyRanges(rhsKeyRanges)
+          .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY AND SRC_LOCATION = DST_LOCATION")
+          .serverDistinctFilter(
+            "SERVER DISTINCT PREFIX FILTER OVER [BUCKET, \"TIMESTAMP\", SRC_LOCATION, DST_LOCATION]")
+          .serverAggregate(
+            "SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [BUCKET, \"TIMESTAMP\", SRC_LOCATION, DST_LOCATION]")
+          .clientSortAlgo("CLIENT MERGE SORT").clientSortedBy(rhsClientSortedBy).end();
+
+        ResultSet rs = conn.createStatement().executeQuery(q);
         assertTrue(rs.next());
         assertEquals("5SEC", rs.getString(1));
         assertEquals(1462993430000000000L, rs.getLong(2));
@@ -721,12 +713,8 @@ public class SortMergeJoinMoreIT extends ParallelStatsDisabledIT {
       + "JOIN " + peopleTable + " ds ON ds.PERSON_ID = l.LOCALID";
 
     for (String q : new String[] { query1, query2 }) {
-      ResultSet rs = conn.createStatement().executeQuery("explain " + q);
-      String plan = QueryUtil.getExplainPlan(rs);
-      assertFalse("Tables should not be sorted over their PKs:\n" + plan,
-        plan.contains("SERVER SORTED BY"));
-
-      rs = conn.createStatement().executeQuery(q);
+      assertPlan(conn, q).lhs().serverSortedBy(null).end().rhs().serverSortedBy(null).end();
+      ResultSet rs = conn.createStatement().executeQuery(q);
       assertTrue(rs.next());
       assertEquals(2, rs.getInt(1));
       assertFalse(rs.next());
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/SpillableGroupByIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/SpillableGroupByIT.java
index ab65682080..3b14fe72ef 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/SpillableGroupByIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/SpillableGroupByIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.apache.phoenix.util.TestUtil.createGroupByTestTable;
 import static org.junit.Assert.assertEquals;
@@ -32,10 +33,7 @@ import java.sql.SQLException;
 import java.sql.Statement;
 import java.util.Map;
 import java.util.Properties;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.exception.SQLExceptionCode;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.util.PropertiesUtil;
 import org.apache.phoenix.util.ReadOnlyProps;
@@ -191,13 +189,8 @@ public class SpillableGroupByIT extends BaseOwnClusterIT {
     rs.close();
     stmt.close();
     String query = "SELECT * FROM " + tableName;
-    ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-      .optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals(new Integer(1), explainPlanAttributes.getSplitsChunk());
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(tableName, explainPlanAttributes.getTableName());
+    assertPlan(conn, query).splitsChunk(1).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+      .table(tableName);
     conn.close();
   }
 
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/SubBinaryFunctionIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/SubBinaryFunctionIT.java
index c2acef86dc..dc19d5afef 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/SubBinaryFunctionIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/SubBinaryFunctionIT.java
@@ -17,12 +17,13 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
+
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
-import org.apache.phoenix.util.QueryUtil;
 import org.junit.Assert;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -379,14 +380,11 @@ public class SubBinaryFunctionIT extends ParallelStatsDisabledIT {
       count++;
     }
     Assert.assertEquals(2, count);
-    rs = conn.createStatement().executeQuery("EXPLAIN " + sql);
-    String plan = QueryUtil.getExplainPlan(rs);
-    Assert.assertTrue(plan.contains("RANGE SCAN OVER " + tableName + " [1,X'01'] - [1,X'02']"));
+    assertPlan(conn, sql).scanType("RANGE SCAN").table(tableName)
+      .keyRanges(" [1,X'01'] - [1,X'02']");
 
     sql = "SELECT * FROM " + tableName + " WHERE id = 1 AND SUBBINARY(VAR_BIN_COL, 2, 1) = X'01'";
-    rs = conn.createStatement().executeQuery("EXPLAIN " + sql);
-    plan = QueryUtil.getExplainPlan(rs);
-    Assert.assertTrue(plan.contains("RANGE SCAN OVER " + tableName + " [1]"));
+    assertPlan(conn, sql).scanType("RANGE SCAN").table(tableName).keyRanges(" [1]");
   }
 
   private void upsertRow(PreparedStatement stmt, int id, byte[] b1, byte[] b2) throws SQLException {
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/TableTTLIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/TableTTLIT.java
index dcefcb4866..5ba04afeac 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/TableTTLIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/TableTTLIT.java
@@ -22,6 +22,7 @@ import static org.apache.phoenix.query.QueryConstants.CDC_POST_IMAGE;
 import static org.apache.phoenix.query.QueryConstants.CDC_PRE_IMAGE;
 import static org.apache.phoenix.query.QueryConstants.CDC_TTL_DELETE_EVENT_TYPE;
 import static org.apache.phoenix.query.QueryConstants.CDC_UPSERT_EVENT_TYPE;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.junit.Assert.*;
 
 import com.fasterxml.jackson.databind.ObjectMapper;
@@ -45,7 +46,6 @@ import org.apache.hadoop.hbase.util.Bytes;
 import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
 import org.apache.phoenix.hbase.index.IndexRegionObserver;
 import org.apache.phoenix.jdbc.PhoenixConnection;
-import org.apache.phoenix.jdbc.PhoenixResultSet;
 import org.apache.phoenix.query.BaseTest;
 import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.schema.PTable;
@@ -575,9 +575,7 @@ public class TableTTLIT extends BaseTest {
       String expectedValue;
       String dql = "select val1, val2 from " + tableName + " where id = 'a1'";
       try (ResultSet rs = conn.createStatement().executeQuery(dql)) {
-        PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
-        String explainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
-        assertFalse(explainPlan.contains(indexName));
+        assertPlan(conn, dql).table(tableName);
         assertTrue(rs.next());
         indexColumnValue = rs.getString(1);
         expectedValue = rs.getString(2);
@@ -609,9 +607,7 @@ public class TableTTLIT extends BaseTest {
       // do a read on the index which should trigger a read repair
       dql = "select val2 from " + tableName + " where val1 = '" + indexColumnValue + "'";
       try (ResultSet rs = conn.createStatement().executeQuery(dql)) {
-        PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
-        String explainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
-        assertTrue(explainPlan.contains(indexName));
+        assertPlan(conn, dql).tableContains(indexName);
         assertTrue(rs.next());
         assertEquals(rs.getString(1), expectedValue);
         assertFalse(rs.next());
@@ -622,9 +618,7 @@ public class TableTTLIT extends BaseTest {
       TestUtil.dumpTable(conn, TableName.valueOf(indexName));
       // run the same query again after compaction
       try (ResultSet rs = conn.createStatement().executeQuery(dql)) {
-        PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
-        String explainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
-        assertTrue(explainPlan.contains(indexName));
+        assertPlan(conn, dql).tableContains(indexName);
         assertTrue(rs.next());
         assertEquals(rs.getString(1), expectedValue);
         assertFalse(rs.next());
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/TenantSpecificTablesDDLIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/TenantSpecificTablesDDLIT.java
index 07ca749575..338daf1e3c 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/TenantSpecificTablesDDLIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/TenantSpecificTablesDDLIT.java
@@ -24,6 +24,7 @@ import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.KEY_SEQ;
 import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.ORDINAL_POSITION;
 import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA;
 import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_FUNCTION_TABLE;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.schema.PTableType.SYSTEM;
 import static org.apache.phoenix.schema.PTableType.TABLE;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
@@ -61,7 +62,6 @@ import org.apache.phoenix.schema.TableNotFoundException;
 import org.apache.phoenix.util.MetaDataUtil;
 import org.apache.phoenix.util.PhoenixRuntime;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.StringUtil;
 import org.apache.phoenix.util.TestUtil;
@@ -694,19 +694,14 @@ public class TenantSpecificTablesDDLIT extends BaseTenantSpecificTablesIT {
       String sql = "SELECT /*+ INDEX(" + fullGrandChildViewName + " " + viewIndexName + ")*/ "
         + "val2, id2, val1, id3, id1 FROM " + fullGrandChildViewName
         + " WHERE id2 = 'a2' AND (id1 = 'a1' OR id1 = 'b1') AND id3 = 3";
-      ResultSet rs = stmt.executeQuery("EXPLAIN " + sql);
-      String actualQueryPlan = QueryUtil.getExplainPlan(rs);
-      assertTrue(actualQueryPlan
-        .contains("1-WAY POINT LOOKUP ON 2 KEYS OVER " + physicalViewIndexTableName));
-      rs = stmt.executeQuery(sql);
+      assertPlan(conn, sql).scanType("POINT LOOKUP ON 2 KEYS")
+        .tableContains(physicalViewIndexTableName);
+      ResultSet rs = stmt.executeQuery(sql);
       assertTrue(rs.next());
       assertFalse(rs.next());
       sql = "SELECT val2, id2, val1, id3, id1 FROM " + fullGrandChildViewName
         + " WHERE id2 = 'a2' AND (id1 = 'a1' OR id1 = 'b1') AND id3 = 3";
-      rs = stmt.executeQuery("EXPLAIN " + sql);
-      actualQueryPlan = QueryUtil.getExplainPlan(rs);
-      assertTrue(
-        actualQueryPlan.contains("1-WAY POINT LOOKUP ON 2 KEYS OVER " + fullDataTableName));
+      assertPlan(conn, sql).scanType("POINT LOOKUP ON 2 KEYS").table(fullDataTableName);
       rs = stmt.executeQuery(sql);
       assertTrue(rs.next());
       assertFalse(rs.next());
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/TenantSpecificTablesDMLIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/TenantSpecificTablesDMLIT.java
index dff28f344b..938a9003c8 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/TenantSpecificTablesDMLIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/TenantSpecificTablesDMLIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.apache.phoenix.util.TestUtil.analyzeTable;
 import static org.apache.phoenix.util.TestUtil.getAllSplits;
@@ -31,12 +32,10 @@ import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.util.List;
 import java.util.Properties;
-import org.apache.phoenix.jdbc.PhoenixResultSet;
 import org.apache.phoenix.query.KeyRange;
 import org.apache.phoenix.schema.TableNotFoundException;
 import org.apache.phoenix.util.PhoenixRuntime;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
@@ -90,9 +89,7 @@ public class TenantSpecificTablesDMLIT extends BaseTenantSpecificTablesIT {
       String dql = String.format("SELECT * FROM %s where org_id='%s' AND kp='%s' LIMIT 1",
         tableName, tenantId, kp);
       try (ResultSet rs = conn.createStatement().executeQuery(dql)) {
-        PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
-        String explainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
-        assertTrue(explainPlan.contains("POINT LOOKUP ON 1 KEY"));
+        assertPlan(conn, dql).scanType("POINT LOOKUP ON 1 KEY");
         assertTrue(rs.next());
         assertEquals(tenantId, rs.getString(1));
         assertEquals(kp, rs.getString(2));
@@ -100,9 +97,7 @@ public class TenantSpecificTablesDMLIT extends BaseTenantSpecificTablesIT {
       dql = String.format("SELECT count(*) FROM %s where org_id='%s' AND kp='%s'", tableName,
         tenantId, kp);
       try (ResultSet rs = conn.createStatement().executeQuery(dql)) {
-        PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
-        String explainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
-        assertTrue(explainPlan.contains("POINT LOOKUP ON 1 KEY"));
+        assertPlan(conn, dql).scanType("POINT LOOKUP ON 1 KEY");
         assertTrue(rs.next());
         assertEquals(nRows, rs.getInt(1));
       }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/TenantSpecificViewIndexIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/TenantSpecificViewIndexIT.java
index 35614d565d..0223b8bca5 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/TenantSpecificViewIndexIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/TenantSpecificViewIndexIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.MetaDataUtil.getViewIndexSequenceName;
 import static org.apache.phoenix.util.MetaDataUtil.getViewIndexSequenceSchemaName;
 import static org.apache.phoenix.util.PhoenixRuntime.TENANT_ID_ATTRIB;
@@ -41,7 +42,6 @@ import org.apache.phoenix.schema.ColumnNotFoundException;
 import org.apache.phoenix.schema.PNameFactory;
 import org.apache.phoenix.util.MetaDataUtil;
 import org.apache.phoenix.util.PhoenixRuntime;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.SchemaUtil;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -358,27 +358,27 @@ public class TenantSpecificViewIndexIT extends BaseTenantSpecificViewIndexIT {
       viewConn.createStatement()
         .execute("CREATE VIEW IF NOT EXISTS " + viewName + " AS SELECT * FROM " + tableName);
 
-      String query = "EXPLAIN SELECT PARENT_ID FROM " + viewName + " WHERE PARENT_TYPE='001' "
+      String expectedIndexName = SchemaUtil.getTableName(SCHEMA1, "IDX");
+      String query1 = "SELECT PARENT_ID FROM " + viewName + " WHERE PARENT_TYPE='001' "
         + "AND (CREATED_DATE > to_date('2011-01-01') AND CREATED_DATE < to_date('2016-10-31'))"
         + "ORDER BY PARENT_TYPE,CREATED_DATE LIMIT 501";
-
-      ResultSet rs = viewConn.createStatement().executeQuery(query);
-      String exptectedIndexName = SchemaUtil.getTableName(SCHEMA1, "IDX");
-      String expectedPlanFormat = "CLIENT SERIAL 1-WAY RANGE SCAN OVER " + exptectedIndexName
-        + " ['tenant1        ','001','%s 00:00:00.001'] - ['tenant1        ','001','%s 00:00:00.000']"
-        + "\n" + "    SERVER FILTER BY FIRST KEY ONLY" + "\n" + "    SERVER 501 ROW LIMIT" + "\n"
-        + "CLIENT 501 ROW LIMIT";
-      assertEquals(String.format(expectedPlanFormat, "2011-01-01", "2016-10-31"),
-        QueryUtil.getExplainPlan(rs));
-
-      query = "EXPLAIN SELECT PARENT_ID FROM " + viewName + " WHERE PARENT_TYPE='001' "
+      assertPlan(viewConn, query1).iteratorType("SERIAL").scanType("RANGE SCAN")
+        .table(expectedIndexName)
+        .keyRanges(" ['tenant1        ','001','2011-01-01 00:00:00.001']"
+          + " - ['tenant1        ','001','2016-10-31 00:00:00.000']")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").serverRowLimit(501L)
+        .clientRowLimit(501).clientSteps("CLIENT 501 ROW LIMIT");
+
+      String query2 = "SELECT PARENT_ID FROM " + viewName + " WHERE PARENT_TYPE='001' "
         + " AND (CREATED_DATE >= to_date('2011-01-01') AND CREATED_DATE <= to_date('2016-01-01'))"
         + " AND (CREATED_DATE > to_date('2012-10-21') AND CREATED_DATE < to_date('2016-10-31')) "
         + "ORDER BY PARENT_TYPE,CREATED_DATE LIMIT 501";
-
-      rs = viewConn.createStatement().executeQuery(query);
-      assertEquals(String.format(expectedPlanFormat, "2012-10-21", "2016-01-01"),
-        QueryUtil.getExplainPlan(rs));
+      assertPlan(viewConn, query2).iteratorType("SERIAL").scanType("RANGE SCAN")
+        .table(expectedIndexName)
+        .keyRanges(" ['tenant1        ','001','2012-10-21 00:00:00.001']"
+          + " - ['tenant1        ','001','2016-01-01 00:00:00.000']")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").serverRowLimit(501L)
+        .clientRowLimit(501).clientSteps("CLIENT 501 ROW LIMIT");
     }
   }
 
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/UCFWithDisabledIndexIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/UCFWithDisabledIndexIT.java
index 6d097ef5e9..8e5ee75dc2 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/UCFWithDisabledIndexIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/UCFWithDisabledIndexIT.java
@@ -19,6 +19,7 @@ package org.apache.phoenix.end2end;
 
 import static org.apache.phoenix.query.QueryServices.DISABLE_VIEW_SUBTREE_VALIDATION;
 import static org.apache.phoenix.query.QueryServices.INDEX_USE_SERVER_METADATA_ATTRIB;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 
 import com.google.protobuf.RpcCallback;
 import com.google.protobuf.RpcController;
@@ -34,15 +35,12 @@ import org.apache.hadoop.hbase.DoNotRetryIOException;
 import org.apache.hadoop.hbase.TableName;
 import org.apache.hadoop.hbase.regionserver.HRegion;
 import org.apache.hadoop.hbase.util.Bytes;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.coprocessor.MetaDataEndpointImpl;
 import org.apache.phoenix.coprocessor.generated.MetaDataProtos;
 import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
 import org.apache.phoenix.exception.PhoenixIOException;
 import org.apache.phoenix.jdbc.PhoenixConnection;
 import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.protobuf.ProtobufUtil;
 import org.apache.phoenix.query.BaseTest;
 import org.apache.phoenix.query.QueryServices;
@@ -192,10 +190,7 @@ public class UCFWithDisabledIndexIT extends BaseTest {
       Assert.assertTrue(rs.next());
       Assert.assertFalse(rs.next());
 
-      ExplainPlan explainPlan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = explainPlan.getPlanStepsAsAttributes();
-      Assert.assertEquals(indexName, explainPlanAttributes.getTableName());
+      assertPlan(conn, query).table(indexName);
 
       TestUtil.removeCoprocessor(conn, "SYSTEM.CATALOG", TestMetaDataEndpointImpl.class);
       TestUtil.addCoprocessor(conn, "SYSTEM.CATALOG", MetaDataEndpointImpl.class);
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/UnionAllIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/UnionAllIT.java
index 208e18f88e..e63972ba38 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/UnionAllIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/UnionAllIT.java
@@ -17,10 +17,10 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
@@ -30,7 +30,6 @@ import java.sql.DriverManager;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
-import java.sql.Statement;
 import java.util.Properties;
 import org.apache.phoenix.compile.ExplainPlan;
 import org.apache.phoenix.compile.ExplainPlanAttributes;
@@ -38,7 +37,6 @@ import org.apache.phoenix.exception.SQLExceptionCode;
 import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.TestUtil;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -643,35 +641,16 @@ public class UnionAllIT extends ParallelStatsDisabledIT {
       assertEquals(1, rhsPlanAttributes.getClientRowLimit().intValue());
       assertEquals("CLIENT MERGE SORT", rhsPlanAttributes.getClientSortAlgo());
 
-      String limitPlan = "UNION ALL OVER 2 QUERIES\n" + "    CLIENT SERIAL 1-WAY FULL SCAN OVER "
-        + tableName1 + "\n" + "        SERVER 2 ROW LIMIT\n" + "    CLIENT 2 ROW LIMIT\n"
-        + "    CLIENT SERIAL 1-WAY FULL SCAN OVER " + tableName2 + "\n"
-        + "        SERVER 2 ROW LIMIT\n" + "    CLIENT 2 ROW LIMIT\n" + "CLIENT 2 ROW LIMIT";
-
+      // Each branch emits a SERIAL 1-WAY FULL SCAN with SERVER 2 ROW LIMIT and an inner CLIENT 2
+      // ROW LIMIT, and the union root carries an outer CLIENT 2 ROW LIMIT. The outer wrap shows
+      // up as a second "CLIENT 2 ROW LIMIT" entry in the root's clientSteps.
       ddl = "select a_string, col1 from " + tableName1 + " union all select a_string, col1 from "
         + tableName2 + " limit 2";
-      plan = conn.prepareStatement(ddl).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("UNION ALL OVER 2 QUERIES", explainPlanAttributes.getAbstractExplainPlan());
-      assertEquals("SERIAL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(tableName1, explainPlanAttributes.getTableName());
-      assertNull(explainPlanAttributes.getServerSortedBy());
-      assertEquals(2L, explainPlanAttributes.getServerRowLimit().longValue());
-      assertEquals(2, explainPlanAttributes.getClientRowLimit().intValue());
-      rhsPlanAttributes = explainPlanAttributes.getRhsJoinQueryExplainPlan();
-      assertEquals("SERIAL 1-WAY", rhsPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", rhsPlanAttributes.getExplainScanType());
-      assertEquals(tableName2, rhsPlanAttributes.getTableName());
-      assertNull(rhsPlanAttributes.getServerSortedBy());
-      assertEquals(2L, rhsPlanAttributes.getServerRowLimit().longValue());
-      assertEquals(2, rhsPlanAttributes.getClientRowLimit().intValue());
-
-      Statement stmt = conn.createStatement();
-      stmt.setMaxRows(2);
-      ResultSet rs = stmt.executeQuery("explain " + ddl);
-      assertEquals(limitPlan, QueryUtil.getExplainPlan(rs));
+      assertPlan(conn, ddl).abstractExplainPlan("UNION ALL OVER 2 QUERIES").iteratorType("SERIAL")
+        .scanType("FULL SCAN").table(tableName1).serverSortedBy(null).serverRowLimit(2L)
+        .clientRowLimit(2).clientSteps("CLIENT 2 ROW LIMIT", "CLIENT 2 ROW LIMIT").rhs()
+        .iteratorType("SERIAL").scanType("FULL SCAN").table(tableName2).serverSortedBy(null)
+        .serverRowLimit(2L).clientRowLimit(2).clientSteps("CLIENT 2 ROW LIMIT");
 
       ddl = "select a_string, col1 from " + tableName1 + " union all select a_string, col1 from "
         + tableName2;
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/UpsertSelectIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/UpsertSelectIT.java
index 0e454b78cf..588d0d7eb0 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/UpsertSelectIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/UpsertSelectIT.java
@@ -19,6 +19,7 @@ package org.apache.phoenix.end2end;
 
 import static org.apache.phoenix.hbase.index.IndexRegionObserver.PHOENIX_INDEX_CDC_CONSUMER_ENABLED;
 import static org.apache.phoenix.monitoring.GlobalClientMetrics.GLOBAL_OPEN_PHOENIX_CONNECTIONS;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertMutationPlan;
 import static org.apache.phoenix.util.PhoenixRuntime.TENANT_ID_ATTRIB;
 import static org.apache.phoenix.util.PhoenixRuntime.UPSERT_BATCH_SIZE_ATTRIB;
 import static org.apache.phoenix.util.TestUtil.A_VALUE;
@@ -51,6 +52,7 @@ import java.util.Properties;
 import org.apache.phoenix.compile.QueryPlan;
 import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
 import org.apache.phoenix.exception.SQLExceptionCode;
+import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.jdbc.PhoenixResultSet;
 import org.apache.phoenix.jdbc.PhoenixStatement;
 import org.apache.phoenix.monitoring.GlobalMetric;
@@ -60,7 +62,6 @@ import org.apache.phoenix.schema.types.PInteger;
 import org.apache.phoenix.util.EnvironmentEdgeManager;
 import org.apache.phoenix.util.PhoenixRuntime;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.ReadOnlyProps;
 import org.apache.phoenix.util.TestUtil;
 import org.junit.After;
@@ -197,12 +198,10 @@ public class UpsertSelectIT extends ParallelStatsDisabledIT {
         + "SELECT substr(entity_id, 4), substr(entity_id, 1, 3), organization_id, "
         + "a_string  FROM " + aTable + " WHERE ?=a_string";
       if (createIndex) { // Confirm index is used
-        try (PreparedStatement upsertStmt = conn.prepareStatement("EXPLAIN " + upsert)) {
+        try (PhoenixPreparedStatement upsertStmt =
+          conn.prepareStatement(upsert).unwrap(PhoenixPreparedStatement.class)) {
           upsertStmt.setString(1, tenantId);
-          ResultSet ers = upsertStmt.executeQuery();
-          assertTrue(ers.next());
-          String explainPlan = QueryUtil.getExplainPlan(ers);
-          assertTrue(explainPlan.contains(" SCAN OVER " + indexName));
+          assertMutationPlan(upsertStmt).tableContains(indexName);
         }
       }
 
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/UpsertSelectWithRegionMovesIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/UpsertSelectWithRegionMovesIT.java
index c2ffbc30a5..3098be4199 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/UpsertSelectWithRegionMovesIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/UpsertSelectWithRegionMovesIT.java
@@ -18,6 +18,7 @@
 package org.apache.phoenix.end2end;
 
 import static org.apache.phoenix.hbase.index.IndexRegionObserver.PHOENIX_INDEX_CDC_CONSUMER_ENABLED;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertMutationPlan;
 import static org.apache.phoenix.util.PhoenixRuntime.TENANT_ID_ATTRIB;
 import static org.apache.phoenix.util.PhoenixRuntime.UPSERT_BATCH_SIZE_ATTRIB;
 import static org.apache.phoenix.util.TestUtil.A_VALUE;
@@ -52,6 +53,7 @@ import org.apache.hadoop.hbase.TableName;
 import org.apache.phoenix.compile.QueryPlan;
 import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
 import org.apache.phoenix.exception.SQLExceptionCode;
+import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.jdbc.PhoenixResultSet;
 import org.apache.phoenix.jdbc.PhoenixStatement;
 import org.apache.phoenix.monitoring.GlobalMetric;
@@ -61,7 +63,6 @@ import org.apache.phoenix.schema.types.PInteger;
 import org.apache.phoenix.util.EnvironmentEdgeManager;
 import org.apache.phoenix.util.PhoenixRuntime;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.ReadOnlyProps;
 import org.apache.phoenix.util.TestUtil;
 import org.junit.After;
@@ -190,12 +191,10 @@ public class UpsertSelectWithRegionMovesIT extends ParallelStatsDisabledWithRegi
         + "SELECT substr(entity_id, 4), substr(entity_id, 1, 3), organization_id, "
         + "a_string  FROM " + aTable + " WHERE ?=a_string";
       if (createIndex) { // Confirm index is used
-        try (PreparedStatement upsertStmt = conn.prepareStatement("EXPLAIN " + upsert)) {
+        try (PhoenixPreparedStatement upsertStmt =
+          conn.prepareStatement(upsert).unwrap(PhoenixPreparedStatement.class)) {
           upsertStmt.setString(1, tenantId);
-          ResultSet ers = upsertStmt.executeQuery();
-          assertTrue(ers.next());
-          String explainPlan = QueryUtil.getExplainPlan(ers);
-          assertTrue(explainPlan.contains(" SCAN OVER " + indexName));
+          assertMutationPlan(upsertStmt).tableContains(indexName);
         }
       }
 
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/UserDefinedFunctionsIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/UserDefinedFunctionsIT.java
index 4f174bb2b2..231d877ecd 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/UserDefinedFunctionsIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/UserDefinedFunctionsIT.java
@@ -20,6 +20,7 @@ package org.apache.phoenix.end2end;
 import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA;
 import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_FUNCTION_TABLE;
 import static org.apache.phoenix.query.QueryServices.DYNAMIC_JARS_DIR_KEY;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR;
 import static org.apache.phoenix.util.PhoenixRuntime.JDBC_PROTOCOL_TERMINATOR;
 import static org.apache.phoenix.util.PhoenixRuntime.JDBC_PROTOCOL_ZK;
@@ -55,10 +56,7 @@ import org.apache.hadoop.fs.FileUtil;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.hbase.HBaseConfiguration;
 import org.apache.hadoop.hbase.HBaseTestingUtility;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.expression.function.UDFExpression;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.jdbc.PhoenixTestDriver;
 import org.apache.phoenix.query.QueryServices;
 import org.apache.phoenix.schema.FunctionAlreadyExistsException;
@@ -842,13 +840,8 @@ public class UserDefinedFunctionsIT extends BaseOwnClusterIT {
     stmt.execute("create index idx on t5(myreverse5(lastname_reverse))");
     String query = "select myreverse5(lastname_reverse) from t5";
 
-    ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-      .optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals("IDX", explainPlanAttributes.getTableName());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
+    assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").table("IDX")
+      .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY");
 
     ResultSet rs = stmt.executeQuery(query);
     assertTrue(rs.next());
@@ -858,15 +851,9 @@ public class UserDefinedFunctionsIT extends BaseOwnClusterIT {
     query =
       "select k,k1,myreverse5(lastname_reverse) from t5 where myreverse5(lastname_reverse)='kcoj'";
 
-    plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-      .getExplainPlan();
-    explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals("IDX2(T5)", explainPlanAttributes.getTableName());
-    assertEquals(" [1,'kcoj']", explainPlanAttributes.getKeyRanges());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+    assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN").table("IDX2(T5)")
+      .keyRanges(" [1,'kcoj']").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+      .clientSortAlgo("CLIENT MERGE SORT");
 
     rs = stmt.executeQuery(query);
     assertTrue(rs.next());
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/VarBinaryEncoded2IT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/VarBinaryEncoded2IT.java
index 6b05b7dd0a..205801164a 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/VarBinaryEncoded2IT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/VarBinaryEncoded2IT.java
@@ -20,6 +20,7 @@ package org.apache.phoenix.end2end;
 import static org.apache.phoenix.hbase.index.IndexCDCConsumer.INDEX_CDC_CONSUMER_RETRY_PAUSE_MS;
 import static org.apache.phoenix.hbase.index.IndexCDCConsumer.INDEX_CDC_CONSUMER_TIMESTAMP_BUFFER_MS;
 import static org.apache.phoenix.hbase.index.IndexRegionObserver.PHOENIX_INDEX_CDC_MUTATION_SERIALIZE;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 
 import java.sql.Connection;
@@ -33,8 +34,6 @@ import java.util.List;
 import java.util.Map;
 import java.util.Properties;
 import org.apache.hadoop.hbase.util.Bytes;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
 import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.QueryServices;
@@ -1275,12 +1274,8 @@ public class VarBinaryEncoded2IT extends ParallelStatsDisabledIT {
 
   private static void assertIndexUsed(PreparedStatement preparedStatement, String indexName,
     String scanType) throws SQLException {
-    ExplainPlan plan =
-      preparedStatement.unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes planAttributes = plan.getPlanStepsAsAttributes();
-
-    Assert.assertEquals(indexName, planAttributes.getTableName());
-    Assert.assertEquals(scanType, planAttributes.getExplainScanType());
+    assertPlan(preparedStatement.unwrap(PhoenixPreparedStatement.class)).table(indexName)
+      .scanType(scanType);
   }
 
   private static void upsertRow(PreparedStatement preparedStatement, byte[] b10, byte[] b20,
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ViewIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ViewIT.java
index c58946caae..e3bf620dc6 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ViewIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ViewIT.java
@@ -18,13 +18,13 @@
 package org.apache.phoenix.end2end;
 
 import static org.apache.phoenix.coprocessor.PhoenixMetaDataCoprocessorHost.PHOENIX_META_DATA_COPROCESSOR_CONF_KEY;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.thirdparty.com.google.common.collect.Lists.newArrayListWithExpectedSize;
 import static org.apache.phoenix.util.TestUtil.analyzeTable;
 import static org.apache.phoenix.util.TestUtil.getAllSplits;
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
@@ -49,12 +49,9 @@ import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
 import org.apache.hadoop.hbase.client.Scan;
 import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
 import org.apache.hadoop.hbase.util.Pair;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.compile.QueryPlan;
 import org.apache.phoenix.exception.SQLExceptionCode;
 import org.apache.phoenix.jdbc.PhoenixConnection;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.jdbc.PhoenixStatement;
 import org.apache.phoenix.query.KeyRange;
 import org.apache.phoenix.query.QueryServices;
@@ -523,26 +520,13 @@ public class ViewIT extends SplitSystemCatalogIT {
       assertEquals(100, rs.getInt(1));
       assertFalse(rs.next());
 
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("SKIP SCAN ON 4 KEYS ", explainPlanAttributes.getExplainScanType());
-      assertEquals("SERVER FILTER BY (\"S2\" = 'bas' AND \"S1\" = 'foo')",
-        explainPlanAttributes.getServerWhereFilter());
-
-      // Assert that in either case (local & global) that index from
-      // physical table used for query on view.
-      if (localIndex) {
-        assertEquals(fullIndexName1 + "(" + fullTableName + ")",
-          explainPlanAttributes.getTableName());
-        assertEquals(" [1,1,100] - [1,2,109]", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-      } else {
-        assertEquals(fullIndexName1, explainPlanAttributes.getTableName());
-        assertEquals(" [1,100] - [2,109]", explainPlanAttributes.getKeyRanges());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
-      }
+      String expectedTable =
+        localIndex ? fullIndexName1 + "(" + fullTableName + ")" : fullIndexName1;
+      String expectedKeyRanges = localIndex ? " [1,1,100] - [1,2,109]" : " [1,100] - [2,109]";
+      String expectedClientSortAlgo = localIndex ? "CLIENT MERGE SORT" : null;
+      assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("SKIP SCAN ON 4 KEYS")
+        .serverWhereFilter("SERVER FILTER BY (\"S2\" = 'bas' AND \"S1\" = 'foo')")
+        .table(expectedTable).keyRanges(expectedKeyRanges).clientSortAlgo(expectedClientSortAlgo);
     }
   }
 
@@ -979,36 +963,24 @@ public class ViewIT extends SplitSystemCatalogIT {
       assertEquals("bar", rs.getString(4));
       assertFalse(rs.next());
 
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-
       if (localIndex) {
-        assertEquals("PARALLEL " + (saltBuckets == null ? 1 : saltBuckets) + "-WAY",
-          explainPlanAttributes.getIteratorTypeAndScanSize());
-        assertEquals(viewIndexFullName1 + "(" + fullTableName + ")",
-          explainPlanAttributes.getTableName());
-        assertEquals(" [1,51]", explainPlanAttributes.getKeyRanges());
-        assertTrue(
-          explainPlanAttributes.getServerWhereFilter().equals("SERVER FILTER BY FIRST KEY ONLY")
-            || explainPlanAttributes.getServerWhereFilter()
-              .equals("SERVER FILTER BY EMPTY COLUMN ONLY"));
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        assertPlan(conn, query).scanType("RANGE SCAN")
+          .iteratorType("PARALLEL " + (saltBuckets == null ? 1 : saltBuckets) + "-WAY")
+          .table(viewIndexFullName1 + "(" + fullTableName + ")").keyRanges(" [1,51]")
+          .serverWhereFilterAnyOf("SERVER FILTER BY FIRST KEY ONLY",
+            "SERVER FILTER BY EMPTY COLUMN ONLY")
+          .clientSortAlgo("CLIENT MERGE SORT");
+      } else if (saltBuckets == null) {
+        assertPlan(conn, query).scanType("RANGE SCAN").iteratorType("PARALLEL 1-WAY")
+          .table(viewIndexPhysicalName).keyRanges(" [" + Short.MIN_VALUE + ",51]")
+          .clientSortAlgo(null);
       } else {
-        assertEquals(viewIndexPhysicalName, explainPlanAttributes.getTableName());
-        if (saltBuckets == null) {
-          assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-          assertEquals(" [" + Short.MIN_VALUE + ",51]", explainPlanAttributes.getKeyRanges());
-          assertNull(explainPlanAttributes.getClientSortAlgo());
-        } else {
-          assertEquals("PARALLEL " + saltBuckets + "-WAY",
-            explainPlanAttributes.getIteratorTypeAndScanSize());
-          assertEquals(" [X'00'," + Short.MIN_VALUE + ",51] - ["
+        assertPlan(conn, query).scanType("RANGE SCAN")
+          .iteratorType("PARALLEL " + saltBuckets + "-WAY").table(viewIndexPhysicalName)
+          .keyRanges(" [X'00'," + Short.MIN_VALUE + ",51] - ["
             + PVarbinary.INSTANCE.toStringLiteral(new byte[] { (byte) (saltBuckets - 1) }) + ","
-            + Short.MIN_VALUE + ",51]", explainPlanAttributes.getKeyRanges());
-          assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-        }
+            + Short.MIN_VALUE + ",51]")
+          .clientSortAlgo("CLIENT MERGE SORT");
       }
 
       String viewIndexName2 = "I_" + generateUniqueName();
@@ -1038,37 +1010,30 @@ public class ViewIT extends SplitSystemCatalogIT {
       assertFalse(rs.next());
       String physicalTableName;
 
-      plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-      assertTrue(
-        explainPlanAttributes.getServerWhereFilter().equals("SERVER FILTER BY FIRST KEY ONLY")
-          || explainPlanAttributes.getServerWhereFilter()
-            .equals("SERVER FILTER BY EMPTY COLUMN ONLY"));
       if (localIndex) {
         physicalTableName = fullTableName;
-        assertEquals("PARALLEL " + (saltBuckets == null ? 1 : saltBuckets) + "-WAY",
-          explainPlanAttributes.getIteratorTypeAndScanSize());
-        assertEquals(viewIndexFullName2 + "(" + fullTableName + ")",
-          explainPlanAttributes.getTableName());
-        assertEquals(" [" + (2) + ",'foo']", explainPlanAttributes.getKeyRanges());
+        assertPlan(conn, query).scanType("RANGE SCAN")
+          .serverWhereFilterAnyOf("SERVER FILTER BY FIRST KEY ONLY",
+            "SERVER FILTER BY EMPTY COLUMN ONLY")
+          .iteratorType("PARALLEL " + (saltBuckets == null ? 1 : saltBuckets) + "-WAY")
+          .table(viewIndexFullName2 + "(" + fullTableName + ")").keyRanges(" [" + (2) + ",'foo']");
+      } else if (saltBuckets == null) {
+        physicalTableName = viewIndexPhysicalName;
+        assertPlan(conn, query).scanType("RANGE SCAN")
+          .serverWhereFilterAnyOf("SERVER FILTER BY FIRST KEY ONLY",
+            "SERVER FILTER BY EMPTY COLUMN ONLY")
+          .iteratorType("PARALLEL 1-WAY").table(viewIndexPhysicalName)
+          .keyRanges(" [" + (Short.MIN_VALUE + 1) + ",'foo']").clientSortAlgo(null);
       } else {
         physicalTableName = viewIndexPhysicalName;
-        assertEquals(viewIndexPhysicalName, explainPlanAttributes.getTableName());
-        if (saltBuckets == null) {
-          assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-          assertEquals(" [" + (Short.MIN_VALUE + 1) + ",'foo']",
-            explainPlanAttributes.getKeyRanges());
-          assertNull(explainPlanAttributes.getClientSortAlgo());
-        } else {
-          assertEquals("PARALLEL " + saltBuckets + "-WAY",
-            explainPlanAttributes.getIteratorTypeAndScanSize());
-          assertEquals(" [X'00'," + (Short.MIN_VALUE + 1) + ",'foo'] - ["
+        assertPlan(conn, query).scanType("RANGE SCAN")
+          .serverWhereFilterAnyOf("SERVER FILTER BY FIRST KEY ONLY",
+            "SERVER FILTER BY EMPTY COLUMN ONLY")
+          .iteratorType("PARALLEL " + saltBuckets + "-WAY").table(viewIndexPhysicalName)
+          .keyRanges(" [X'00'," + (Short.MIN_VALUE + 1) + ",'foo'] - ["
             + PVarbinary.INSTANCE.toStringLiteral(new byte[] { (byte) (saltBuckets - 1) }) + ","
-            + (Short.MIN_VALUE + 1) + ",'foo']", explainPlanAttributes.getKeyRanges());
-          assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-        }
+            + (Short.MIN_VALUE + 1) + ",'foo']")
+          .clientSortAlgo("CLIENT MERGE SORT");
       }
       return new Pair<>(physicalTableName, scan);
     }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ViewMetadataIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ViewMetadataIT.java
index b3f28a08e9..aa306208e6 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ViewMetadataIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ViewMetadataIT.java
@@ -32,6 +32,8 @@ import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TASK_TYPE;
 import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TENANT_ID;
 import static org.apache.phoenix.query.QueryServices.DROP_METADATA_ATTRIB;
 import static org.apache.phoenix.query.QueryServicesOptions.DEFAULT_TASK_HANDLING_MAX_INTERVAL_MS;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.getPlanSteps;
 import static org.apache.phoenix.schema.PTable.TaskType.DROP_CHILD_VIEWS;
 import static org.apache.phoenix.thirdparty.com.google.common.collect.Lists.newArrayListWithExpectedSize;
 import static org.apache.phoenix.util.ByteUtil.EMPTY_BYTE_ARRAY;
@@ -80,7 +82,6 @@ import org.apache.phoenix.schema.PTableType;
 import org.apache.phoenix.schema.TableAlreadyExistsException;
 import org.apache.phoenix.schema.TableNotFoundException;
 import org.apache.phoenix.util.PhoenixRuntime;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.ReadOnlyProps;
 import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.ViewUtil;
@@ -235,9 +236,7 @@ public class ViewMetadataIT extends SplitSystemCatalogIT {
         conn.createStatement()
           .execute("CREATE VIEW " + view1 + " (PK VARCHAR PRIMARY KEY, " + CF + ".COL VARCHAR)");
 
-        assertTrue(QueryUtil
-          .getExplainPlan(conn.createStatement().executeQuery("explain select * from " + view1))
-          .contains(NS + ":" + TBL));
+        assertPlan(conn, "select * from " + view1).tableContains(NS + ":" + TBL);
 
         conn.createStatement().execute("DROP VIEW " + view1);
         admin.disableTable(tableName);
@@ -256,9 +255,7 @@ public class ViewMetadataIT extends SplitSystemCatalogIT {
         conn.createStatement()
           .execute("CREATE VIEW " + view2 + " (PK VARCHAR PRIMARY KEY, " + CF + ".COL VARCHAR)");
 
-        assertTrue(QueryUtil
-          .getExplainPlan(conn.createStatement().executeQuery("explain select * from " + view2))
-          .contains(NS + "." + TBL));
+        assertPlan(conn, "select * from " + view2).tableContains(NS + "." + TBL);
 
         conn.createStatement().execute("DROP VIEW " + view2);
         admin.disableTable(tableName);
@@ -277,9 +274,7 @@ public class ViewMetadataIT extends SplitSystemCatalogIT {
         conn.createStatement()
           .execute("CREATE VIEW " + view3 + " (PK VARCHAR PRIMARY KEY, " + CF + ".COL VARCHAR)");
 
-        assertTrue(QueryUtil
-          .getExplainPlan(conn.createStatement().executeQuery("explain select * from " + view3))
-          .contains(NS + ":" + NS + "." + TBL));
+        assertPlan(conn, "select * from " + view3).tableContains(NS + ":" + NS + "." + TBL);
 
         conn.createStatement().execute("DROP VIEW " + view3);
         admin.disableTable(tableName);
@@ -947,13 +942,13 @@ public class ViewMetadataIT extends SplitSystemCatalogIT {
     // Create a index on the table
     s1.execute("create index " + indexName + " ON " + tableName + " (col2)");
 
-    try (ResultSet rs = s2.executeQuery("explain select /*+ INDEX(" + viewName + " " + indexName
-      + ") */ * from " + viewName + " where col2 = 'aaa'")) {
-      String explainPlan = QueryUtil.getExplainPlan(rs);
-
-      // check if the query uses the index
-      assertTrue(explainPlan.contains(indexName));
-    }
+    String sql = "select /*+ INDEX(" + viewName + " " + indexName + ") */ * from " + viewName
+      + " where col2 = 'aaa'";
+    // This query produces a SKIP-SCAN-JOIN where the index is scanned in a sub-plan. Assert that
+    // the index name appears in the plan steps.
+    List<String> planSteps = getPlanSteps(s2.getConnection(), sql);
+    assertTrue("Expected plan to use index " + indexName + " but was: " + planSteps,
+      planSteps.toString().contains(indexName));
   }
 
   @Test
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/WhereOptimizerForArrayAnyIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/WhereOptimizerForArrayAnyIT.java
index c9651f2113..d7012009fe 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/WhereOptimizerForArrayAnyIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/WhereOptimizerForArrayAnyIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
@@ -34,8 +35,6 @@ import java.sql.Time;
 import java.sql.Timestamp;
 import java.sql.Types;
 import org.apache.hadoop.hbase.TableName;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.compile.QueryPlan;
 import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.jdbc.PhoenixStatement;
@@ -770,10 +769,7 @@ public class WhereOptimizerForArrayAnyIT extends WhereOptimizerForArrayAnyITBase
   }
 
   private void assertPointLookupsAreNotGenerated(PreparedStatement stmt) throws SQLException {
-    ExplainPlan explain =
-      stmt.unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes planAttributes = explain.getPlanStepsAsAttributes();
-    assertEquals("FULL SCAN ", planAttributes.getExplainScanType());
+    assertPlan(stmt.unwrap(PhoenixPreparedStatement.class)).scanType("FULL SCAN");
   }
 
   private void assertPointLookupsAreGenerated(Statement stmt, String selectSql,
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/WhereOptimizerForArrayAnyITBase.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/WhereOptimizerForArrayAnyITBase.java
index b33362e48d..40e2b6ec6b 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/WhereOptimizerForArrayAnyITBase.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/WhereOptimizerForArrayAnyITBase.java
@@ -17,14 +17,11 @@
  */
 package org.apache.phoenix.end2end;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 
 import java.sql.PreparedStatement;
 import java.sql.SQLException;
 import java.util.HashMap;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.compile.QueryPlan;
 import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.BaseTest;
@@ -49,35 +46,23 @@ public abstract class WhereOptimizerForArrayAnyITBase extends BaseTest {
 
   protected void assertPointLookupsAreGenerated(QueryPlan queryPlan, int noOfPointLookups)
     throws SQLException {
-    ExplainPlan explain = queryPlan.getExplainPlan();
-    ExplainPlanAttributes planAttributes = explain.getPlanStepsAsAttributes();
     String expectedScanType =
-      "POINT LOOKUP ON " + noOfPointLookups + " KEY" + (noOfPointLookups > 1 ? "S " : " ");
-    assertEquals(expectedScanType, planAttributes.getExplainScanType());
+      "POINT LOOKUP ON " + noOfPointLookups + " KEY" + (noOfPointLookups > 1 ? "S" : "");
+    assertPlan(queryPlan.getExplainPlan().getPlanStepsAsAttributes()).scanType(expectedScanType);
   }
 
   protected void assertSkipScanIsGenerated(PreparedStatement stmt, int skipListSize)
     throws SQLException {
-    QueryPlan queryPlan = stmt.unwrap(PhoenixPreparedStatement.class).optimizeQuery();
-    ExplainPlan explain = queryPlan.getExplainPlan();
-    ExplainPlanAttributes planAttributes = explain.getPlanStepsAsAttributes();
     String expectedScanType =
-      "SKIP SCAN ON " + skipListSize + " KEY" + (skipListSize > 1 ? "S " : " ");
-    assertEquals(expectedScanType, planAttributes.getExplainScanType());
+      "SKIP SCAN ON " + skipListSize + " KEY" + (skipListSize > 1 ? "S" : "");
+    assertPlan(stmt.unwrap(PhoenixPreparedStatement.class)).scanType(expectedScanType);
   }
 
   protected void assertRangeScanIsGenerated(PreparedStatement stmt) throws SQLException {
-    QueryPlan queryPlan = stmt.unwrap(PhoenixPreparedStatement.class).optimizeQuery();
-    ExplainPlan explain = queryPlan.getExplainPlan();
-    ExplainPlanAttributes planAttributes = explain.getPlanStepsAsAttributes();
-    String expectedScanType = "RANGE SCAN ";
-    assertEquals(expectedScanType, planAttributes.getExplainScanType());
+    assertPlan(stmt.unwrap(PhoenixPreparedStatement.class)).scanType("RANGE SCAN");
   }
 
   protected void assertDegenerateScanIsGenerated(PreparedStatement stmt) throws SQLException {
-    QueryPlan queryPlan = stmt.unwrap(PhoenixPreparedStatement.class).optimizeQuery();
-    ExplainPlan explain = queryPlan.getExplainPlan();
-    ExplainPlanAttributes planAttributes = explain.getPlanStepsAsAttributes();
-    assertNull(planAttributes.getExplainScanType());
+    assertPlan(stmt.unwrap(PhoenixPreparedStatement.class)).scanType(null);
   }
 }
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/WhereOptimizerForArrayAnyNullablePKIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/WhereOptimizerForArrayAnyNullablePKIT.java
index c96a985cec..c30542b251 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/WhereOptimizerForArrayAnyNullablePKIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/WhereOptimizerForArrayAnyNullablePKIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotEquals;
@@ -33,9 +34,6 @@ import java.sql.SQLException;
 import java.sql.Types;
 import java.util.Arrays;
 import java.util.Collection;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
-import org.apache.phoenix.compile.QueryPlan;
 import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.junit.Assume;
 import org.junit.Test;
@@ -233,13 +231,7 @@ public class WhereOptimizerForArrayAnyNullablePKIT extends WhereOptimizerForArra
   }
 
   private void assertQueryUsesIndex(PreparedStatement stmt, String indexName) throws SQLException {
-    QueryPlan queryPlan = stmt.unwrap(PhoenixPreparedStatement.class).optimizeQuery();
-    ExplainPlan explain = queryPlan.getExplainPlan();
-    ExplainPlanAttributes planAttributes = explain.getPlanStepsAsAttributes();
-    String tableName = planAttributes.getTableName();
-    System.out.println("Explain plan: " + explain.toString());
-    assertTrue("Expected query to use index " + indexName + " but used table " + tableName,
-      tableName != null && tableName.contains(indexName));
+    assertPlan(stmt.unwrap(PhoenixPreparedStatement.class)).tableContains(indexName);
   }
 
   /**
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/BaseImmutableIndexIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/BaseImmutableIndexIT.java
index aaeeea6d07..bb0788f420 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/BaseImmutableIndexIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/BaseImmutableIndexIT.java
@@ -17,8 +17,8 @@
  */
 package org.apache.phoenix.end2end.index;
 
-import static org.apache.phoenix.end2end.IndexToolIT.assertExplainPlan;
 import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.IMMUTABLE_STORAGE_SCHEME;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.schema.PTable.ImmutableStorageScheme.SINGLE_CELL_ARRAY_WITH_OFFSETS;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.apache.phoenix.util.TestUtil.getRowCount;
@@ -71,7 +71,6 @@ import org.apache.phoenix.transaction.PhoenixTransactionProvider.Feature;
 import org.apache.phoenix.transaction.TransactionFactory;
 import org.apache.phoenix.util.PhoenixRuntime;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.TestUtil;
 import org.junit.Ignore;
@@ -465,9 +464,9 @@ public abstract class BaseImmutableIndexIT extends BaseTest {
       admin.truncateTable(TableName.valueOf(fullTableName), true);
       String selectFromIndex = "SELECT long_pk, varchar_pk, long_col1 FROM " + TABLE_NAME
         + " WHERE varchar_pk='varchar2' AND long_pk=2";
-      rs = conn.createStatement().executeQuery("EXPLAIN " + selectFromIndex);
-      String actualExplainPlan = QueryUtil.getExplainPlan(rs);
-      assertExplainPlan(false, actualExplainPlan, fullTableName, fullIndexName);
+      // Verify the query is served by a RANGE SCAN over the index table.
+      assertPlan(conn, selectFromIndex).scanType("RANGE SCAN")
+        .tableContains(SchemaUtil.normalizeIdentifier(fullIndexName));
 
       rs = conn.createStatement().executeQuery(selectFromIndex);
       assertFalse(rs.next());
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/BaseIndexIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/BaseIndexIT.java
index 4dca35db98..3a1ffdcc9e 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/BaseIndexIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/BaseIndexIT.java
@@ -18,6 +18,7 @@
 package org.apache.phoenix.end2end.index;
 
 import static org.apache.phoenix.query.QueryConstants.MILLIS_IN_DAY;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.ROW5;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
@@ -53,15 +54,12 @@ import org.apache.hadoop.hbase.client.Table;
 import org.apache.hadoop.hbase.util.Bytes;
 import org.apache.hadoop.hbase.util.Pair;
 import org.apache.phoenix.compile.ColumnResolver;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.compile.FromCompiler;
 import org.apache.phoenix.end2end.CreateTableIT;
 import org.apache.phoenix.end2end.IndexToolIT;
 import org.apache.phoenix.end2end.ParallelStatsDisabledIT;
 import org.apache.phoenix.exception.SQLExceptionCode;
 import org.apache.phoenix.jdbc.PhoenixConnection;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.jdbc.PhoenixResultSet;
 import org.apache.phoenix.jdbc.PhoenixStatement;
 import org.apache.phoenix.parse.NamedTableNode;
@@ -69,6 +67,7 @@ import org.apache.phoenix.parse.TableName;
 import org.apache.phoenix.query.BaseTest;
 import org.apache.phoenix.query.QueryConstants;
 import org.apache.phoenix.query.QueryServices;
+import org.apache.phoenix.query.explain.ExplainPlanTestUtil;
 import org.apache.phoenix.schema.PIndexState;
 import org.apache.phoenix.schema.PTable;
 import org.apache.phoenix.schema.PTableImpl;
@@ -80,7 +79,6 @@ import org.apache.phoenix.util.DateUtil;
 import org.apache.phoenix.util.EnvironmentEdgeManager;
 import org.apache.phoenix.util.PhoenixRuntime;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.TestUtil;
 import org.apache.phoenix.util.TransactionUtil;
@@ -152,30 +150,20 @@ public abstract class BaseIndexIT extends ParallelStatsDisabledIT {
 
       String query = "SELECT d.char_col1, int_col1 from " + fullTableName + " as d";
 
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan =
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY");
       if (!uncovered) {
         // Optimizer would not select the uncovered index for this query
-        assertEquals(
-          columnEncoded ? "SERVER FILTER BY FIRST KEY ONLY" : "SERVER FILTER BY EMPTY COLUMN ONLY",
-          explainPlanAttributes.getServerWhereFilter());
+        basePlan.serverWhereFilter(
+          columnEncoded ? "SERVER FILTER BY FIRST KEY ONLY" : "SERVER FILTER BY EMPTY COLUMN ONLY");
       }
-
       if (localIndex) {
-        assertEquals(fullIndexName + "(" + fullTableName + ")",
-          explainPlanAttributes.getTableName());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
+        basePlan.table(fullIndexName + "(" + fullTableName + ")").keyRanges(" [1]")
+          .clientSortAlgo("CLIENT MERGE SORT").scanType("RANGE SCAN");
       } else if (!uncovered) {
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
+        basePlan.table(fullIndexName).clientSortAlgo(null).scanType("FULL SCAN");
       }
-      assertFalse("Explain plan regionLocation attribute should not be empty",
-        explainPlanAttributes.getRegionLocations().isEmpty());
+      basePlan.regionLocationsNotEmpty();
 
       ResultSet rs = conn.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -584,26 +572,16 @@ public abstract class BaseIndexIT extends ParallelStatsDisabledIT {
       String query =
         "SELECT" + (uncovered ? " /*+ INDEX(" + fullTableName + " " + indexName + ")*/ " : " ")
           + "int_pk from " + fullTableName;
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals(
-        columnEncoded ? "SERVER FILTER BY FIRST KEY ONLY" : "SERVER FILTER BY EMPTY COLUMN ONLY",
-        explainPlanAttributes.getServerWhereFilter());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan =
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").serverWhereFilter(
+          columnEncoded ? "SERVER FILTER BY FIRST KEY ONLY" : "SERVER FILTER BY EMPTY COLUMN ONLY");
       if (localIndex) {
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName + "(" + fullTableName + ")",
-          explainPlanAttributes.getTableName());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
+        basePlan.scanType("RANGE SCAN").table(fullIndexName + "(" + fullTableName + ")")
+          .clientSortAlgo("CLIENT MERGE SORT").keyRanges(" [1]");
       } else {
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("FULL SCAN").table(fullIndexName).clientSortAlgo(null);
       }
-      assertFalse("Explain plan regionLocation attribute should not be empty",
-        explainPlanAttributes.getRegionLocations().isEmpty());
+      basePlan.regionLocationsNotEmpty();
 
       ResultSet rs = conn.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -615,23 +593,13 @@ public abstract class BaseIndexIT extends ParallelStatsDisabledIT {
       assertFalse(rs.next());
 
       query = "SELECT date_col from " + fullTableName + " order by date_col";
-      plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals(
-        columnEncoded ? "SERVER FILTER BY FIRST KEY ONLY" : "SERVER FILTER BY EMPTY COLUMN ONLY",
-        explainPlanAttributes.getServerWhereFilter());
+      basePlan = assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").serverWhereFilter(
+        columnEncoded ? "SERVER FILTER BY FIRST KEY ONLY" : "SERVER FILTER BY EMPTY COLUMN ONLY");
       if (localIndex) {
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName + "(" + fullTableName + ")",
-          explainPlanAttributes.getTableName());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
+        basePlan.scanType("RANGE SCAN").table(fullIndexName + "(" + fullTableName + ")")
+          .clientSortAlgo("CLIENT MERGE SORT").keyRanges(" [1]");
       } else {
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("FULL SCAN").table(fullIndexName).clientSortAlgo(null);
       }
 
       rs = conn.createStatement().executeQuery(query);
@@ -686,23 +654,15 @@ public abstract class BaseIndexIT extends ParallelStatsDisabledIT {
 
       query = "SELECT" + (uncovered ? " /*+ INDEX(" + fullTableName + " " + indexName + ")*/" : "")
         + " * FROM " + fullTableName;
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan =
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY");
       if (localIndex) {
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName + "(" + fullTableName + ")",
-          explainPlanAttributes.getTableName());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
+        basePlan.scanType("RANGE SCAN").table(fullIndexName + "(" + fullTableName + ")")
+          .clientSortAlgo("CLIENT MERGE SORT").keyRanges(" [1]");
       } else {
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("FULL SCAN").table(fullIndexName).clientSortAlgo(null);
       }
-      assertFalse("Explain plan regionLocation attribute should not be empty",
-        explainPlanAttributes.getRegionLocations().isEmpty());
+      basePlan.regionLocationsNotEmpty();
 
       rs = conn.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -722,19 +682,9 @@ public abstract class BaseIndexIT extends ParallelStatsDisabledIT {
       assertFalse(rs.next());
 
       query = "SELECT v1 as foo FROM " + fullTableName + " WHERE v2 = '1' ORDER BY foo";
-      plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals("[\"V1\"]", explainPlanAttributes.getServerSortedBy());
-      assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-      if (localIndex) {
-        assertEquals(fullIndexName + "(" + fullTableName + ")",
-          explainPlanAttributes.getTableName());
-      } else {
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
-      }
+      assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+        .serverSortedBy("[\"V1\"]").clientSortAlgo("CLIENT MERGE SORT")
+        .table(localIndex ? fullIndexName + "(" + fullTableName + ")" : fullIndexName);
 
       rs = conn.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -784,29 +734,19 @@ public abstract class BaseIndexIT extends ParallelStatsDisabledIT {
       conn.commit();
 
       query = "SELECT * FROM " + fullTableName;
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(fullTableName, explainPlanAttributes.getTableName());
+      assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+        .table(fullTableName);
 
       query =
         "SELECT" + (uncovered ? " /*+ INDEX(" + fullTableName + " " + indexName + ")*/ " : " ")
           + "a.* FROM " + fullTableName;
-      plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan =
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY");
       if (localIndex) {
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName + "(" + fullTableName + ")",
-          explainPlanAttributes.getTableName());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("RANGE SCAN").table(fullIndexName + "(" + fullTableName + ")")
+          .keyRanges(" [1]").clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
+        basePlan.scanType("FULL SCAN").table(fullIndexName);
       }
       rs = conn.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -970,23 +910,15 @@ public abstract class BaseIndexIT extends ParallelStatsDisabledIT {
       // make sure the index is working as expected
       query = "SELECT" + (uncovered ? " /*+ INDEX(" + testTable + " " + indexName + ")*/ " : " ")
         + "* FROM " + testTable;
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals(
-        columnEncoded ? "SERVER FILTER BY FIRST KEY ONLY" : "SERVER FILTER BY EMPTY COLUMN ONLY",
-        explainPlanAttributes.getServerWhereFilter());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan = assertPlan(conn, query).serverWhereFilter(
+        columnEncoded ? "SERVER FILTER BY FIRST KEY ONLY" : "SERVER FILTER BY EMPTY COLUMN ONLY");
       if (localIndex) {
-        assertEquals("PARALLEL 2-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName + "(" + testTable + ")", explainPlanAttributes.getTableName());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        basePlan.iteratorType("PARALLEL 2-WAY").scanType("RANGE SCAN")
+          .table(fullIndexName + "(" + testTable + ")").keyRanges(" [1]")
+          .clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").table(fullIndexName)
+          .clientSortAlgo(null);
       }
 
       // check that the data table matches as expected
@@ -1048,18 +980,12 @@ public abstract class BaseIndexIT extends ParallelStatsDisabledIT {
       }
 
       query = "SELECT * FROM " + fullTableName + " WHERE \"v2\" = '1'";
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan =
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN");
       if (localIndex) {
-        assertEquals(fullIndexName + "(" + fullTableName + ")",
-          explainPlanAttributes.getTableName());
-        assertEquals(" [1,'1']", explainPlanAttributes.getKeyRanges());
+        basePlan.table(fullIndexName + "(" + fullTableName + ")").keyRanges(" [1,'1']");
       } else {
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
-        assertEquals(" ['1']", explainPlanAttributes.getKeyRanges());
+        basePlan.table(fullIndexName).keyRanges(" ['1']");
       }
 
       rs = conn.createStatement().executeQuery(query);
@@ -1086,20 +1012,12 @@ public abstract class BaseIndexIT extends ParallelStatsDisabledIT {
 
       query = "SELECT \"V1\", \"V1\" as foo1, \"v2\" as foo, \"v2\" as \"Foo1\", \"v2\" FROM "
         + fullTableName + " ORDER BY foo";
-      plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
+      basePlan = assertPlan(conn, query).iteratorType("PARALLEL 1-WAY");
       if (localIndex) {
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName + "(" + fullTableName + ")",
-          explainPlanAttributes.getTableName());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("RANGE SCAN").table(fullIndexName + "(" + fullTableName + ")")
+          .keyRanges(" [1]").clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("FULL SCAN").table(fullIndexName).clientSortAlgo(null);
       }
 
       rs = conn.createStatement().executeQuery(query);
@@ -1220,20 +1138,13 @@ public abstract class BaseIndexIT extends ParallelStatsDisabledIT {
       query =
         "SELECT" + (uncovered ? " /*+ INDEX(" + fullTableName + " " + indexName + ")*/ " : " ")
           + "decimal_pk, decimal_col1, decimal_col2 from " + fullTableName;
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan =
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY");
       if (localIndex) {
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName + "(" + fullTableName + ")",
-          explainPlanAttributes.getTableName());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("RANGE SCAN").table(fullIndexName + "(" + fullTableName + ")")
+          .keyRanges(" [1]").clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("FULL SCAN").table(fullIndexName).clientSortAlgo(null);
       }
 
       rs = conn.createStatement().executeQuery(query);
@@ -1547,12 +1458,12 @@ public abstract class BaseIndexIT extends ParallelStatsDisabledIT {
 
         query = "SELECT /*+ INDEX(" + fullTableName + " " + indexName + ")*/ " + columns + " from "
           + fullTableName + " where int_col1=2 and long_col1=2";
-        rs = stmt.executeQuery("Explain " + query);
-        String explainPlan = QueryUtil.getExplainPlan(rs);
-        assertEquals("bad plan with columns:" + columns, "CLIENT PARALLEL 1-WAY RANGE SCAN OVER "
-          + fullIndexName + " [2]\n"
-          + "    SERVER MERGE [A.VARCHAR_COL1, A.CHAR_COL1, A.DECIMAL_COL1, A.DATE1, B.VARCHAR_COL2, B.CHAR_COL2, B.INT_COL2, B.DECIMAL_COL2, B.DATE2]\n"
-          + "    SERVER FILTER BY A.\"LONG_COL1\" = 2", explainPlan);
+        assertPlan(conn, query).scanType("RANGE SCAN").tableContains(fullIndexName)
+          .keyRanges(" [2]")
+          .serverMergeColumns(
+            "[A.VARCHAR_COL1, A.CHAR_COL1, A.DECIMAL_COL1, A.DATE1, B.VARCHAR_COL2, B.CHAR_COL2,"
+              + " B.INT_COL2, B.DECIMAL_COL2, B.DATE2]")
+          .serverWhereFilter("SERVER FILTER BY A.\"LONG_COL1\" = 2");
         rs = stmt.executeQuery(query);
         assertTrue(rs.next());
         // Test the projector thoroughly
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/BaseIndexWithRegionMovesIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/BaseIndexWithRegionMovesIT.java
index 329cb4df55..256e4ef8d2 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/BaseIndexWithRegionMovesIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/BaseIndexWithRegionMovesIT.java
@@ -18,6 +18,7 @@
 package org.apache.phoenix.end2end.index;
 
 import static org.apache.phoenix.query.QueryConstants.MILLIS_IN_DAY;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.ROW5;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
@@ -53,15 +54,12 @@ import org.apache.hadoop.hbase.client.Table;
 import org.apache.hadoop.hbase.util.Bytes;
 import org.apache.hadoop.hbase.util.Pair;
 import org.apache.phoenix.compile.ColumnResolver;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.compile.FromCompiler;
 import org.apache.phoenix.end2end.CreateTableIT;
 import org.apache.phoenix.end2end.IndexToolIT;
 import org.apache.phoenix.end2end.ParallelStatsDisabledWithRegionMovesIT;
 import org.apache.phoenix.exception.SQLExceptionCode;
 import org.apache.phoenix.jdbc.PhoenixConnection;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.jdbc.PhoenixResultSet;
 import org.apache.phoenix.jdbc.PhoenixStatement;
 import org.apache.phoenix.parse.NamedTableNode;
@@ -69,6 +67,7 @@ import org.apache.phoenix.parse.TableName;
 import org.apache.phoenix.query.BaseTest;
 import org.apache.phoenix.query.QueryConstants;
 import org.apache.phoenix.query.QueryServices;
+import org.apache.phoenix.query.explain.ExplainPlanTestUtil;
 import org.apache.phoenix.schema.PIndexState;
 import org.apache.phoenix.schema.PTable;
 import org.apache.phoenix.schema.PTableImpl;
@@ -80,7 +79,6 @@ import org.apache.phoenix.util.DateUtil;
 import org.apache.phoenix.util.EnvironmentEdgeManager;
 import org.apache.phoenix.util.PhoenixRuntime;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.TestUtil;
 import org.apache.phoenix.util.TransactionUtil;
@@ -168,26 +166,18 @@ public abstract class BaseIndexWithRegionMovesIT extends ParallelStatsDisabledWi
 
       String query = "SELECT d.char_col1, int_col1 from " + fullTableName + " as d";
 
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan =
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY");
       if (!uncovered) {
         // Optimizer would not select the uncovered index for this query
-        assertEquals(
-          columnEncoded ? "SERVER FILTER BY FIRST KEY ONLY" : "SERVER FILTER BY EMPTY COLUMN ONLY",
-          explainPlanAttributes.getServerWhereFilter());
+        basePlan.serverWhereFilter(
+          columnEncoded ? "SERVER FILTER BY FIRST KEY ONLY" : "SERVER FILTER BY EMPTY COLUMN ONLY");
       }
-
       if (localIndex) {
-        assertEquals(fullTableName, explainPlanAttributes.getTableName());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
+        basePlan.table(fullTableName).keyRanges(" [1]").clientSortAlgo("CLIENT MERGE SORT")
+          .scanType("RANGE SCAN");
       } else if (!uncovered) {
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
+        basePlan.table(fullIndexName).clientSortAlgo(null).scanType("FULL SCAN");
       }
 
       ResultSet rs = conn.createStatement().executeQuery(query);
@@ -642,22 +632,14 @@ public abstract class BaseIndexWithRegionMovesIT extends ParallelStatsDisabledWi
       String query =
         "SELECT" + (uncovered ? " /*+ INDEX(" + fullTableName + " " + indexName + ")*/ " : " ")
           + "int_pk from " + fullTableName;
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals(
-        columnEncoded ? "SERVER FILTER BY FIRST KEY ONLY" : "SERVER FILTER BY EMPTY COLUMN ONLY",
-        explainPlanAttributes.getServerWhereFilter());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan =
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").serverWhereFilter(
+          columnEncoded ? "SERVER FILTER BY FIRST KEY ONLY" : "SERVER FILTER BY EMPTY COLUMN ONLY");
       if (localIndex) {
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullTableName, explainPlanAttributes.getTableName());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
+        basePlan.scanType("RANGE SCAN").table(fullTableName).clientSortAlgo("CLIENT MERGE SORT")
+          .keyRanges(" [1]");
       } else {
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("FULL SCAN").table(fullIndexName).clientSortAlgo(null);
       }
 
       ResultSet rs = conn.createStatement().executeQuery(query);
@@ -674,22 +656,13 @@ public abstract class BaseIndexWithRegionMovesIT extends ParallelStatsDisabledWi
       assertFalse(rs.next());
 
       query = "SELECT date_col from " + fullTableName + " order by date_col";
-      plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals(
-        columnEncoded ? "SERVER FILTER BY FIRST KEY ONLY" : "SERVER FILTER BY EMPTY COLUMN ONLY",
-        explainPlanAttributes.getServerWhereFilter());
+      basePlan = assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").serverWhereFilter(
+        columnEncoded ? "SERVER FILTER BY FIRST KEY ONLY" : "SERVER FILTER BY EMPTY COLUMN ONLY");
       if (localIndex) {
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullTableName, explainPlanAttributes.getTableName());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
+        basePlan.scanType("RANGE SCAN").table(fullTableName).clientSortAlgo("CLIENT MERGE SORT")
+          .keyRanges(" [1]");
       } else {
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("FULL SCAN").table(fullIndexName).clientSortAlgo(null);
       }
 
       rs = conn.createStatement().executeQuery(query);
@@ -750,19 +723,13 @@ public abstract class BaseIndexWithRegionMovesIT extends ParallelStatsDisabledWi
 
       query = "SELECT" + (uncovered ? " /*+ INDEX(" + fullTableName + " " + indexName + ")*/" : "")
         + " * FROM " + fullTableName;
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan =
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY");
       if (localIndex) {
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullTableName, explainPlanAttributes.getTableName());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
+        basePlan.scanType("RANGE SCAN").table(fullTableName).clientSortAlgo("CLIENT MERGE SORT")
+          .keyRanges(" [1]");
       } else {
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("FULL SCAN").table(fullIndexName).clientSortAlgo(null);
       }
 
       rs = conn.createStatement().executeQuery(query);
@@ -787,18 +754,9 @@ public abstract class BaseIndexWithRegionMovesIT extends ParallelStatsDisabledWi
       assertFalse(rs.next());
 
       query = "SELECT v1 as foo FROM " + fullTableName + " WHERE v2 = '1' ORDER BY foo";
-      plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals("[\"V1\"]", explainPlanAttributes.getServerSortedBy());
-      assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-      if (localIndex) {
-        assertEquals(fullTableName, explainPlanAttributes.getTableName());
-      } else {
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
-      }
+      assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+        .serverSortedBy("[\"V1\"]").clientSortAlgo("CLIENT MERGE SORT")
+        .table(localIndex ? fullTableName : fullIndexName);
 
       rs = conn.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -852,28 +810,19 @@ public abstract class BaseIndexWithRegionMovesIT extends ParallelStatsDisabledWi
       conn.commit();
 
       query = "SELECT * FROM " + fullTableName;
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(fullTableName, explainPlanAttributes.getTableName());
+      assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+        .table(fullTableName);
 
       query =
         "SELECT" + (uncovered ? " /*+ INDEX(" + fullTableName + " " + indexName + ")*/ " : " ")
           + "a.* FROM " + fullTableName;
-      plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan =
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY");
       if (localIndex) {
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullTableName, explainPlanAttributes.getTableName());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("RANGE SCAN").table(fullTableName).keyRanges(" [1]")
+          .clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
+        basePlan.scanType("FULL SCAN").table(fullIndexName);
       }
       rs = conn.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -1055,23 +1004,14 @@ public abstract class BaseIndexWithRegionMovesIT extends ParallelStatsDisabledWi
       // make sure the index is working as expected
       query = "SELECT" + (uncovered ? " /*+ INDEX(" + testTable + " " + indexName + ")*/ " : " ")
         + "* FROM " + testTable;
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals(
-        columnEncoded ? "SERVER FILTER BY FIRST KEY ONLY" : "SERVER FILTER BY EMPTY COLUMN ONLY",
-        explainPlanAttributes.getServerWhereFilter());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan = assertPlan(conn, query).serverWhereFilter(
+        columnEncoded ? "SERVER FILTER BY FIRST KEY ONLY" : "SERVER FILTER BY EMPTY COLUMN ONLY");
       if (localIndex) {
-        assertEquals("PARALLEL 2-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(testTable, explainPlanAttributes.getTableName());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        basePlan.iteratorType("PARALLEL 2-WAY").scanType("RANGE SCAN").table(testTable)
+          .keyRanges(" [1]").clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").table(fullIndexName)
+          .clientSortAlgo(null);
       }
 
       // check that the data table matches as expected
@@ -1139,17 +1079,12 @@ public abstract class BaseIndexWithRegionMovesIT extends ParallelStatsDisabledWi
       }
 
       query = "SELECT * FROM " + fullTableName + " WHERE \"v2\" = '1'";
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan =
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN");
       if (localIndex) {
-        assertEquals(fullTableName, explainPlanAttributes.getTableName());
-        assertEquals(" [1,'1']", explainPlanAttributes.getKeyRanges());
+        basePlan.table(fullTableName).keyRanges(" [1,'1']");
       } else {
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
-        assertEquals(" ['1']", explainPlanAttributes.getKeyRanges());
+        basePlan.table(fullIndexName).keyRanges(" ['1']");
       }
 
       rs = conn.createStatement().executeQuery(query);
@@ -1178,19 +1113,12 @@ public abstract class BaseIndexWithRegionMovesIT extends ParallelStatsDisabledWi
 
       query = "SELECT \"V1\", \"V1\" as foo1, \"v2\" as foo, \"v2\" as \"Foo1\", \"v2\" FROM "
         + fullTableName + " ORDER BY foo";
-      plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
+      basePlan = assertPlan(conn, query).iteratorType("PARALLEL 1-WAY");
       if (localIndex) {
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullTableName, explainPlanAttributes.getTableName());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("RANGE SCAN").table(fullTableName).keyRanges(" [1]")
+          .clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("FULL SCAN").table(fullIndexName).clientSortAlgo(null);
       }
 
       rs = conn.createStatement().executeQuery(query);
@@ -1320,19 +1248,13 @@ public abstract class BaseIndexWithRegionMovesIT extends ParallelStatsDisabledWi
       query =
         "SELECT" + (uncovered ? " /*+ INDEX(" + fullTableName + " " + indexName + ")*/ " : " ")
           + "decimal_pk, decimal_col1, decimal_col2 from " + fullTableName;
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan =
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY");
       if (localIndex) {
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullTableName, explainPlanAttributes.getTableName());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("RANGE SCAN").table(fullTableName).keyRanges(" [1]")
+          .clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullIndexName, explainPlanAttributes.getTableName());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("FULL SCAN").table(fullIndexName).clientSortAlgo(null);
       }
 
       rs = conn.createStatement().executeQuery(query);
@@ -1673,14 +1595,12 @@ public abstract class BaseIndexWithRegionMovesIT extends ParallelStatsDisabledWi
 
         query = "SELECT /*+ INDEX(" + fullTableName + " " + indexName + ")*/ " + columns + " from "
           + fullTableName + " where int_col1=2 and long_col1=2";
-        rs = stmt.executeQuery("Explain " + query);
-        String explainPlan = QueryUtil.getExplainPlan(rs);
-        assertEquals("bad plan with columns:" + columns,
-          "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + fullIndexName + " [2]\n"
-            + "    SERVER MERGE [A.VARCHAR_COL1, A.CHAR_COL1, A.DECIMAL_COL1,"
-            + " A.DATE1, B.VARCHAR_COL2, B.CHAR_COL2, B.INT_COL2, " + "B.DECIMAL_COL2, B.DATE2]\n"
-            + "    SERVER FILTER BY A.\"LONG_COL1\" = 2",
-          explainPlan);
+        assertPlan(conn, query).scanType("RANGE SCAN").tableContains(fullIndexName)
+          .keyRanges(" [2]")
+          .serverMergeColumns(
+            "[A.VARCHAR_COL1, A.CHAR_COL1, A.DECIMAL_COL1, A.DATE1, B.VARCHAR_COL2, B.CHAR_COL2,"
+              + " B.INT_COL2, B.DECIMAL_COL2, B.DATE2]")
+          .serverWhereFilter("SERVER FILTER BY A.\"LONG_COL1\" = 2");
         rs = stmt.executeQuery(query);
         assertTrue(rs.next());
         moveRegionsOfTable(fullTableName);
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/ChildViewsUseParentViewIndexIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/ChildViewsUseParentViewIndexIT.java
index 9b84aad8f7..5a8c41b266 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/ChildViewsUseParentViewIndexIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/ChildViewsUseParentViewIndexIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end.index;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
@@ -28,12 +29,9 @@ import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.util.Properties;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.end2end.ParallelStatsDisabledIT;
 import org.apache.phoenix.end2end.ParallelStatsDisabledTest;
 import org.apache.phoenix.jdbc.PhoenixConnection;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.schema.PTable;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -165,16 +163,11 @@ public class ChildViewsUseParentViewIndexIT extends ParallelStatsDisabledIT {
     Connection conn, boolean isChildView) throws SQLException {
     String sql =
       "SELECT A0, A1, A2, A4 FROM " + viewName + " WHERE A4 IN ('1', '2', '3') ORDER BY A4, A2";
-    ExplainPlan plan = conn.prepareStatement(sql).unwrap(PhoenixPreparedStatement.class)
-      .optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals("SKIP SCAN ON 3 KEYS ", explainPlanAttributes.getExplainScanType());
-    assertEquals("_IDX_" + baseTableName, explainPlanAttributes.getTableName());
     String childViewScanKey = isChildView ? ",'Y'" : "";
-    assertEquals(" [" + Short.MIN_VALUE + ",'1'" + childViewScanKey + "] - [" + Short.MIN_VALUE
-      + ",'3'" + childViewScanKey + "]", explainPlanAttributes.getKeyRanges());
+    assertPlan(conn, sql).iteratorType("PARALLEL 1-WAY")
+      .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").scanType("SKIP SCAN ON 3 KEYS")
+      .table("_IDX_" + baseTableName).keyRanges(" [" + Short.MIN_VALUE + ",'1'" + childViewScanKey
+        + "] - [" + Short.MIN_VALUE + ",'3'" + childViewScanKey + "]");
 
     ResultSet rs = conn.createStatement().executeQuery(sql);
     assertTrue(rs.next());
@@ -193,15 +186,10 @@ public class ChildViewsUseParentViewIndexIT extends ParallelStatsDisabledIT {
   private void assertQueryUsesBaseTable(final String baseTableName, final String viewName,
     Connection conn) throws SQLException {
     String sql = "SELECT A0, A1, A2, A4 FROM " + viewName + " WHERE A4 IN ('1', '2', '3') ";
-    ExplainPlan plan = conn.prepareStatement(sql).unwrap(PhoenixPreparedStatement.class)
-      .optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals(
-      "SERVER FILTER BY (A4 IN ('1','2','3') AND ((A1 = 'X' AND A2 = 'Y') AND A3 = 'Z'))",
-      explainPlanAttributes.getServerWhereFilter());
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(baseTableName, explainPlanAttributes.getTableName());
+    assertPlan(conn, sql).iteratorType("PARALLEL 1-WAY")
+      .serverWhereFilter(
+        "SERVER FILTER BY (A4 IN ('1','2','3') AND ((A1 = 'X' AND A2 = 'Y') AND A3 = 'Z'))")
+      .scanType("FULL SCAN").table(baseTableName);
 
     ResultSet rs = conn.createStatement().executeQuery(sql);
     assertTrue(rs.next());
@@ -273,17 +261,11 @@ public class ChildViewsUseParentViewIndexIT extends ParallelStatsDisabledIT {
     String sql = "SELECT WO_ID FROM " + viewName
       + " WHERE WO_ID IN ('003xxxxxxxxxxx1', '003xxxxxxxxxxx2', '003xxxxxxxxxxx3', '003xxxxxxxxxxx4', '003xxxxxxxxxxx5') "
       + " AND (A_DATE > TO_DATE('2016-01-01 06:00:00.0')) " + " ORDER BY WO_ID, A_DATE DESC";
-    ExplainPlan plan = conn.prepareStatement(sql).unwrap(PhoenixPreparedStatement.class)
-      .optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals("SKIP SCAN ON 5 RANGES ", explainPlanAttributes.getExplainScanType());
-    assertEquals("_IDX_" + baseTableName, explainPlanAttributes.getTableName());
-    assertEquals(
-      " [" + Short.MIN_VALUE + ",'00Dxxxxxxxxxxx1','003xxxxxxxxxxx1',*] - [" + Short.MIN_VALUE
-        + ",'00Dxxxxxxxxxxx1','003xxxxxxxxxxx5',~'2016-01-01 06:00:00.000']",
-      explainPlanAttributes.getKeyRanges());
+    assertPlan(conn, sql).iteratorType("PARALLEL 1-WAY")
+      .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").scanType("SKIP SCAN ON 5 RANGES")
+      .table("_IDX_" + baseTableName)
+      .keyRanges(" [" + Short.MIN_VALUE + ",'00Dxxxxxxxxxxx1','003xxxxxxxxxxx1',*] - ["
+        + Short.MIN_VALUE + ",'00Dxxxxxxxxxxx1','003xxxxxxxxxxx5',~'2016-01-01 06:00:00.000']");
 
     ResultSet rs = conn.createStatement().executeQuery(sql);
     for (int i = 0; i < expectedRows; ++i) {
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/GlobalIndexCheckerIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/GlobalIndexCheckerIT.java
index 8d7d4c546a..e174c37c56 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/GlobalIndexCheckerIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/GlobalIndexCheckerIT.java
@@ -29,9 +29,12 @@ import static org.apache.phoenix.mapreduce.index.PhoenixIndexToolJobCounters.BEF
 import static org.apache.phoenix.mapreduce.index.PhoenixIndexToolJobCounters.BEFORE_REBUILD_VALID_INDEX_ROW_COUNT;
 import static org.apache.phoenix.mapreduce.index.PhoenixIndexToolJobCounters.REBUILT_INDEX_ROW_COUNT;
 import static org.apache.phoenix.mapreduce.index.PhoenixIndexToolJobCounters.SCANNED_DATA_ROW_COUNT;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.getExplainAttributes;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
@@ -52,10 +55,10 @@ import java.util.Map;
 import java.util.Properties;
 import org.apache.hadoop.hbase.TableName;
 import org.apache.hadoop.mapreduce.CounterGroup;
+import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.end2end.IndexToolIT;
 import org.apache.phoenix.end2end.NeedsOwnMiniClusterTest;
 import org.apache.phoenix.hbase.index.IndexRegionObserver;
-import org.apache.phoenix.jdbc.PhoenixResultSet;
 import org.apache.phoenix.mapreduce.index.IndexTool;
 import org.apache.phoenix.query.BaseTest;
 import org.apache.phoenix.query.QueryServices;
@@ -63,8 +66,8 @@ import org.apache.phoenix.schema.PTableImpl;
 import org.apache.phoenix.util.EnvironmentEdgeManager;
 import org.apache.phoenix.util.PhoenixRuntime;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.ReadOnlyProps;
+import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.TestUtil;
 import org.junit.After;
 import org.junit.Assume;
@@ -140,19 +143,25 @@ public class GlobalIndexCheckerIT extends BaseTest {
 
   public static void assertExplainPlan(Connection conn, String selectSql, String dataTableFullName,
     String indexTableFullName) throws SQLException {
-    ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql);
-    String actualExplainPlan = QueryUtil.getExplainPlan(rs);
-    IndexToolIT.assertExplainPlan(false, actualExplainPlan, dataTableFullName, indexTableFullName);
+    // Verify the query is served by a RANGE SCAN over the index table not the data table.
+    ExplainPlanAttributes attributes = getExplainAttributes(conn, selectSql);
+    assertPlan(attributes).scanType("RANGE SCAN");
+    String actualTable =
+      attributes.getTableName() == null ? null : attributes.getTableName().replaceAll(":", ".");
+    String expectedTable = SchemaUtil.normalizeIdentifier(indexTableFullName);
+    assertTrue("expected scanned table <" + actualTable + "> to use index <" + expectedTable + ">",
+      actualTable != null && actualTable.contains(expectedTable));
   }
 
   public static void assertExplainPlanWithLimit(Connection conn, String selectSql,
     String dataTableFullName, String indexTableFullName, int limit) throws SQLException {
-    ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql);
-    String actualExplainPlan = QueryUtil.getExplainPlan(rs);
-    IndexToolIT.assertExplainPlan(false, actualExplainPlan, dataTableFullName, indexTableFullName);
-    String expectedLimitPlan = String.format("SERVER %d ROW LIMIT", limit);
-    assertTrue(actualExplainPlan + "\n expected to contain \n" + expectedLimitPlan,
-      actualExplainPlan.contains(expectedLimitPlan));
+    ExplainPlanAttributes attributes = getExplainAttributes(conn, selectSql);
+    assertPlan(attributes).scanType("RANGE SCAN").serverRowLimit((long) limit);
+    String actualTable =
+      attributes.getTableName() == null ? null : attributes.getTableName().replaceAll(":", ".");
+    String expectedTable = SchemaUtil.normalizeIdentifier(indexTableFullName);
+    assertTrue("expected scanned table <" + actualTable + "> to use index <" + expectedTable + ">",
+      actualTable != null && actualTable.contains(expectedTable));
   }
 
   private void populateTable(String tableName) throws Exception {
@@ -278,9 +287,7 @@ public class GlobalIndexCheckerIT extends BaseTest {
         + dataTableName + " WHERE val1 = 'bc' AND " + "PHOENIX_ROW_TIMESTAMP() > TO_DATE('"
         + after.toString() + "','yyyy-MM-dd HH:mm:ss.SSS', '" + timeZoneID + "')";
       // Verify that we will read from the data table
-      rs = conn.createStatement().executeQuery("EXPLAIN " + noIndexQuery);
-      String explainPlan = QueryUtil.getExplainPlan(rs);
-      assertTrue(explainPlan.contains("FULL SCAN OVER " + dataTableName));
+      assertPlan(conn, noIndexQuery).scanType("FULL SCAN").table(dataTableName);
       rs = conn.createStatement().executeQuery(noIndexQuery);
       assertTrue(rs.next());
       assertEquals("bc", rs.getString(1));
@@ -739,10 +746,8 @@ public class GlobalIndexCheckerIT extends BaseTest {
 
       // now read the same row from data table
       selectSql = "SELECT * from " + dataTableName + " WHERE id  = 'a'";
+      assertPlan(conn, selectSql).table(dataTableName);
       try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
-        PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
-        String explainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
-        assertTrue(explainPlan.contains(dataTableName));
         assertTrue(rs.next());
         assertEquals("a", rs.getString(1));
         assertEquals("ab", rs.getString(2));
@@ -1264,11 +1269,7 @@ public class GlobalIndexCheckerIT extends BaseTest {
       String selectSql =
         "SELECT id, val1, val3 from " + dataTableName + " WHERE val1 IN ('ab', 'bcc') ";
       // Verify that we will read from the index table
-      try (ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql)) {
-        String actualExplainPlan = QueryUtil.getExplainPlan(rs);
-        String expectedExplainPlan = String.format("SKIP SCAN ON 2 KEYS OVER %s", indexName);
-        assertTrue(actualExplainPlan.contains(expectedExplainPlan));
-      }
+      assertPlan(conn, selectSql).scanType("SKIP SCAN ON 2 KEYS").table(indexName);
       try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
         assertTrue(rs.next());
         assertEquals("a", rs.getString("id"));
@@ -1289,16 +1290,11 @@ public class GlobalIndexCheckerIT extends BaseTest {
 
       selectSql = "SELECT id, val3 from " + dataTableName
         + " WHERE val1 IN ('bc') AND val2 IN ('bcd', 'xcdf') AND val3 = 'bcde' ";
-      // Verify that we will read from the index table
-      try (ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql)) {
-        String actualExplainPlan = QueryUtil.getExplainPlan(rs);
-        String expectedExplainPlan = String.format("SKIP SCAN ON 2 KEYS OVER %s", indexName);
-        String filter = "SERVER FILTER BY";
-        assertTrue(String.format("actual=%s", actualExplainPlan),
-          actualExplainPlan.contains(expectedExplainPlan));
-        assertTrue(String.format("actual=%s", actualExplainPlan),
-          actualExplainPlan.contains(filter));
-      }
+      // Verify that we will read from the index table with a server filter
+      ExplainPlanAttributes skipScanAttributes = getExplainAttributes(conn, selectSql);
+      assertPlan(skipScanAttributes).scanType("SKIP SCAN ON 2 KEYS").table(indexName);
+      assertNotNull("expected a server filter, plan=" + skipScanAttributes,
+        skipScanAttributes.getServerWhereFilter());
       try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
         assertTrue(rs.next());
         assertEquals("b", rs.getString("id"));
@@ -1351,9 +1347,7 @@ public class GlobalIndexCheckerIT extends BaseTest {
       List<String> expectedIDs = Lists.newArrayList("a", "d");
       List<String> actualIDs = Lists.newArrayList();
       try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
-        PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
-        String actualExplainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
-        assertTrue(actualExplainPlan.contains(indexName));
+        assertPlan(conn, selectSql).table(indexName);
         while (rs.next()) {
           actualIDs.add(rs.getString("id"));
         }
@@ -1367,9 +1361,7 @@ public class GlobalIndexCheckerIT extends BaseTest {
       expectedIDs = Lists.newArrayList("e", "g");
       actualIDs = Lists.newArrayList();
       try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
-        PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
-        String actualExplainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
-        assertTrue(actualExplainPlan.contains(indexName));
+        assertPlan(conn, selectSql).table(indexName);
         while (rs.next()) {
           actualIDs.add(rs.getString("id"));
         }
@@ -1532,10 +1524,10 @@ public class GlobalIndexCheckerIT extends BaseTest {
   private void verifyDistinctQueryOnIndex(Connection conn, String indexName, String query,
     List<String> expectedValues) throws SQLException, IOException {
     try (ResultSet rs = conn.createStatement().executeQuery(query)) {
-      PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
-      String actualExplainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
-      assertTrue(actualExplainPlan.contains(indexName));
-      assertTrue(actualExplainPlan, actualExplainPlan.contains("SERVER DISTINCT PREFIX FILTER"));
+      ExplainPlanAttributes attributes = getExplainAttributes(conn, query);
+      assertPlan(attributes).table(indexName);
+      assertNotNull("expected a server distinct prefix filter, plan=" + attributes,
+        attributes.getServerDistinctFilter());
       List actualValues = Lists.newArrayList();
       while (rs.next()) {
         actualValues.add(rs.getString(1));
@@ -1572,17 +1564,14 @@ public class GlobalIndexCheckerIT extends BaseTest {
 
       String selectSql =
         "SELECT id, val3 from " + dataTableName + " WHERE val1 = 'bc' and val2 = 'bcd' ";
-      // Verify that we will read from the index table
-      try (ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql)) {
-        String actualExplainPlan = QueryUtil.getExplainPlan(rs);
-        String expectedExplainPlan = String.format("RANGE SCAN OVER %s", indexName);
-        String filter =
-          String.format("SERVER FILTER BY %s ONLY AND", encoded ? "FIRST KEY" : "EMPTY COLUMN");
-        assertTrue(String.format("actual=%s", actualExplainPlan),
-          actualExplainPlan.contains(expectedExplainPlan));
-        assertTrue(String.format("actual=%s", actualExplainPlan),
-          actualExplainPlan.contains(filter));
-      }
+      // Verify that we will read from the index table with a first-key-only/empty-column filter
+      ExplainPlanAttributes attributes = getExplainAttributes(conn, selectSql);
+      assertPlan(attributes).scanType("RANGE SCAN").table(indexName);
+      String expectedFilter =
+        String.format("SERVER FILTER BY %s ONLY AND", encoded ? "FIRST KEY" : "EMPTY COLUMN");
+      assertTrue("serverWhereFilter=" + attributes.getServerWhereFilter(),
+        attributes.getServerWhereFilter() != null
+          && attributes.getServerWhereFilter().contains(expectedFilter));
       try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
         assertTrue(rs.next());
         assertEquals("b", rs.getString("id"));
@@ -1617,19 +1606,15 @@ public class GlobalIndexCheckerIT extends BaseTest {
 
       String dql =
         String.format("select id, val2 from %s where val1='ab' and val3='abcd'", dataTableName);
+      assertPlan(conn, dql).table(indexName);
       try (ResultSet rs = conn.createStatement().executeQuery(dql)) {
-        PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
-        String explainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
-        assertTrue(explainPlan.contains(indexName));
         assertFalse(rs.next());
       }
 
       dql =
         String.format("select id, val2 from %s where val1='ab' and val3 is null", dataTableName);
+      assertPlan(conn, dql).table(indexName);
       try (ResultSet rs = conn.createStatement().executeQuery(dql)) {
-        PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
-        String explainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
-        assertTrue(explainPlan.contains(indexName));
         assertTrue(rs.next());
         assertEquals("abc", rs.getString("val2"));
       }
@@ -1642,10 +1627,8 @@ public class GlobalIndexCheckerIT extends BaseTest {
 
       dql =
         String.format("select id, val2 from %s where val1='ac' and val3 is null", dataTableName);
+      assertPlan(conn, dql).table(indexName);
       try (ResultSet rs = conn.createStatement().executeQuery(dql)) {
-        PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
-        String explainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
-        assertTrue(explainPlan.contains(indexName));
         assertTrue(rs.next());
         assertNull(rs.getString("val2"));
       }
@@ -1730,10 +1713,8 @@ public class GlobalIndexCheckerIT extends BaseTest {
           // delete family marker on the unverified index row
           String dql =
             String.format("select id, val2, val3 from %s where val1='ab'", dataTableName);
+          assertPlan(conn, dql).table(indexName);
           try (ResultSet rs = conn.createStatement().executeQuery(dql)) {
-            PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
-            String explainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
-            assertTrue(explainPlan.contains(indexName));
             assertFalse(rs.next());
           }
         }
@@ -1884,10 +1865,10 @@ public class GlobalIndexCheckerIT extends BaseTest {
       waitForEventualConsistency();
       String distinctQuery = "SELECT DISTINCT val1 FROM " + dataTableName;
       try (ResultSet rs = conn.createStatement().executeQuery(distinctQuery)) {
-        PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
-        String explainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
-        assertTrue(explainPlan.contains(indexTableName));
-        assertTrue(explainPlan.contains("SERVER DISTINCT PREFIX FILTER OVER"));
+        ExplainPlanAttributes attributes = getExplainAttributes(conn, distinctQuery);
+        assertPlan(attributes).table(indexTableName);
+        assertNotNull("expected a server distinct prefix filter, plan=" + attributes,
+          attributes.getServerDistinctFilter());
         List actualValues = Lists.newArrayList();
         while (rs.next()) {
           actualValues.add(rs.getString(1));
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/GlobalIndexCheckerWithRegionMovesIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/GlobalIndexCheckerWithRegionMovesIT.java
index 6583df2d84..c5240d9ff0 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/GlobalIndexCheckerWithRegionMovesIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/GlobalIndexCheckerWithRegionMovesIT.java
@@ -30,9 +30,12 @@ import static org.apache.phoenix.mapreduce.index.PhoenixIndexToolJobCounters.BEF
 import static org.apache.phoenix.mapreduce.index.PhoenixIndexToolJobCounters.BEFORE_REBUILD_VALID_INDEX_ROW_COUNT;
 import static org.apache.phoenix.mapreduce.index.PhoenixIndexToolJobCounters.REBUILT_INDEX_ROW_COUNT;
 import static org.apache.phoenix.mapreduce.index.PhoenixIndexToolJobCounters.SCANNED_DATA_ROW_COUNT;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.getExplainAttributes;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
@@ -58,6 +61,7 @@ import org.apache.hadoop.hbase.TableName;
 import org.apache.hadoop.hbase.client.Admin;
 import org.apache.hadoop.hbase.client.RegionInfo;
 import org.apache.hadoop.hbase.client.RegionStatesCount;
+import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
 import org.apache.phoenix.end2end.IndexToolIT;
 import org.apache.phoenix.end2end.NeedsOwnMiniClusterTest;
@@ -70,8 +74,8 @@ import org.apache.phoenix.schema.PTableImpl;
 import org.apache.phoenix.util.EnvironmentEdgeManager;
 import org.apache.phoenix.util.PhoenixRuntime;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.ReadOnlyProps;
+import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.TestUtil;
 import org.junit.After;
 import org.junit.Before;
@@ -251,19 +255,25 @@ public class GlobalIndexCheckerWithRegionMovesIT extends BaseTest {
 
   public static void assertExplainPlan(Connection conn, String selectSql, String dataTableFullName,
     String indexTableFullName) throws SQLException {
-    ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql);
-    String actualExplainPlan = QueryUtil.getExplainPlan(rs);
-    IndexToolIT.assertExplainPlan(false, actualExplainPlan, dataTableFullName, indexTableFullName);
+    // Verify the query is served by a RANGE SCAN over the index table and not the data table.
+    ExplainPlanAttributes attributes = getExplainAttributes(conn, selectSql);
+    assertPlan(attributes).scanType("RANGE SCAN");
+    String actualTable =
+      attributes.getTableName() == null ? null : attributes.getTableName().replaceAll(":", ".");
+    String expectedTable = SchemaUtil.normalizeIdentifier(indexTableFullName);
+    assertTrue("expected scanned table <" + actualTable + "> to use index <" + expectedTable + ">",
+      actualTable != null && actualTable.contains(expectedTable));
   }
 
   public static void assertExplainPlanWithLimit(Connection conn, String selectSql,
     String dataTableFullName, String indexTableFullName, int limit) throws SQLException {
-    ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql);
-    String actualExplainPlan = QueryUtil.getExplainPlan(rs);
-    IndexToolIT.assertExplainPlan(false, actualExplainPlan, dataTableFullName, indexTableFullName);
-    String expectedLimitPlan = String.format("SERVER %d ROW LIMIT", limit);
-    assertTrue(actualExplainPlan + "\n expected to contain \n" + expectedLimitPlan,
-      actualExplainPlan.contains(expectedLimitPlan));
+    ExplainPlanAttributes attributes = getExplainAttributes(conn, selectSql);
+    assertPlan(attributes).scanType("RANGE SCAN").serverRowLimit((long) limit);
+    String actualTable =
+      attributes.getTableName() == null ? null : attributes.getTableName().replaceAll(":", ".");
+    String expectedTable = SchemaUtil.normalizeIdentifier(indexTableFullName);
+    assertTrue("expected scanned table <" + actualTable + "> to use index <" + expectedTable + ">",
+      actualTable != null && actualTable.contains(expectedTable));
   }
 
   private void populateTable(String tableName) throws Exception {
@@ -398,9 +408,7 @@ public class GlobalIndexCheckerWithRegionMovesIT extends BaseTest {
         + dataTableName + " WHERE val1 = 'bc' AND " + "PHOENIX_ROW_TIMESTAMP() > TO_DATE('"
         + after.toString() + "','yyyy-MM-dd HH:mm:ss.SSS', '" + timeZoneID + "')";
       // Verify that we will read from the data table
-      rs = conn.createStatement().executeQuery("EXPLAIN " + noIndexQuery);
-      String explainPlan = QueryUtil.getExplainPlan(rs);
-      assertTrue(explainPlan.contains("FULL SCAN OVER " + dataTableName));
+      assertPlan(conn, noIndexQuery).scanType("FULL SCAN").table(dataTableName);
       rs = conn.createStatement().executeQuery(noIndexQuery);
       assertTrue(rs.next());
       moveRegionsOfTable(dataTableName);
@@ -1447,11 +1455,7 @@ public class GlobalIndexCheckerWithRegionMovesIT extends BaseTest {
       String selectSql =
         "SELECT id, val1, val3 from " + dataTableName + " WHERE val1 IN ('ab', 'bcc') ";
       // Verify that we will read from the index table
-      try (ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql)) {
-        String actualExplainPlan = QueryUtil.getExplainPlan(rs);
-        String expectedExplainPlan = String.format("SKIP SCAN ON 2 KEYS OVER %s", indexName);
-        assertTrue(actualExplainPlan.contains(expectedExplainPlan));
-      }
+      assertPlan(conn, selectSql).scanType("SKIP SCAN ON 2 KEYS").table(indexName);
       try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
         assertTrue(rs.next());
         assertEquals("a", rs.getString("id"));
@@ -1474,16 +1478,11 @@ public class GlobalIndexCheckerWithRegionMovesIT extends BaseTest {
 
       selectSql = "SELECT id, val3 from " + dataTableName
         + " WHERE val1 IN ('bc') AND val2 IN ('bcd', 'xcdf') AND val3 = 'bcde' ";
-      // Verify that we will read from the index table
-      try (ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql)) {
-        String actualExplainPlan = QueryUtil.getExplainPlan(rs);
-        String expectedExplainPlan = String.format("SKIP SCAN ON 2 KEYS OVER %s", indexName);
-        String filter = "SERVER FILTER BY";
-        assertTrue(String.format("actual=%s", actualExplainPlan),
-          actualExplainPlan.contains(expectedExplainPlan));
-        assertTrue(String.format("actual=%s", actualExplainPlan),
-          actualExplainPlan.contains(filter));
-      }
+      // Verify that we will read from the index table with a server filter
+      ExplainPlanAttributes skipScanAttributes = getExplainAttributes(conn, selectSql);
+      assertPlan(skipScanAttributes).scanType("SKIP SCAN ON 2 KEYS").table(indexName);
+      assertNotNull("expected a server filter, plan=" + skipScanAttributes,
+        skipScanAttributes.getServerWhereFilter());
       try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
         assertTrue(rs.next());
         moveRegionsOfTable(dataTableName);
@@ -1525,17 +1524,14 @@ public class GlobalIndexCheckerWithRegionMovesIT extends BaseTest {
 
       String selectSql =
         "SELECT id, val3 from " + dataTableName + " WHERE val1 = 'bc' and val2 = 'bcd' ";
-      // Verify that we will read from the index table
-      try (ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql)) {
-        String actualExplainPlan = QueryUtil.getExplainPlan(rs);
-        String expectedExplainPlan = String.format("RANGE SCAN OVER %s", indexName);
-        String filter =
-          String.format("SERVER FILTER BY %s ONLY AND", encoded ? "FIRST KEY" : "EMPTY COLUMN");
-        assertTrue(String.format("actual=%s", actualExplainPlan),
-          actualExplainPlan.contains(expectedExplainPlan));
-        assertTrue(String.format("actual=%s", actualExplainPlan),
-          actualExplainPlan.contains(filter));
-      }
+      // Verify that we will read from the index table with a first-key-only/empty-column filter
+      ExplainPlanAttributes attributes = getExplainAttributes(conn, selectSql);
+      assertPlan(attributes).scanType("RANGE SCAN").table(indexName);
+      String expectedFilter =
+        String.format("SERVER FILTER BY %s ONLY AND", encoded ? "FIRST KEY" : "EMPTY COLUMN");
+      assertTrue("serverWhereFilter=" + attributes.getServerWhereFilter(),
+        attributes.getServerWhereFilter() != null
+          && attributes.getServerWhereFilter().contains(expectedFilter));
       try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
         assertTrue(rs.next());
         moveRegionsOfTable(dataTableName);
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/GlobalIndexOptimizationIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/GlobalIndexOptimizationIT.java
index fe7a1e8e4b..a9a43e3204 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/GlobalIndexOptimizationIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/GlobalIndexOptimizationIT.java
@@ -17,6 +17,8 @@
  */
 package org.apache.phoenix.end2end.index;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertMutationPlan;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
@@ -28,8 +30,8 @@ import java.sql.SQLException;
 import java.util.regex.Pattern;
 import org.apache.phoenix.end2end.NeedsOwnMiniClusterTest;
 import org.apache.phoenix.end2end.ParallelStatsDisabledIT;
+import org.apache.phoenix.query.explain.ExplainPlanTestUtil.ExplainPlanAssert;
 import org.apache.phoenix.util.PhoenixRuntime;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.SchemaUtil;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -78,13 +80,11 @@ public class GlobalIndexOptimizationIT extends ParallelStatsDisabledIT {
           + " SELECT TO_CHAR(rand()*100),rand()*10000,rand()*10000,rand()*10000,TO_CHAR(rand()*100) FROM "
           + dataTableName);
       }
-      ResultSet rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-      String expected = "DELETE ROWS CLIENT SELECT\n" + "CLIENT PARALLEL 1-WAY RANGE SCAN OVER "
-        + indexTableName + "L" + "(" + dataTableName + ") [1,*] - [1,100]\n"
-        + "    SERVER FILTER BY FIRST KEY ONLY\n" + "CLIENT MERGE SORT";
-      String actual = QueryUtil.getExplainPlan(rs);
-      assertEquals(expected, actual);
-      rs = conn1.createStatement().executeQuery("SELECT COUNT(*) FROM " + dataTableName);
+      assertMutationPlan(conn1, query).abstractExplainPlan("DELETE ROWS CLIENT SELECT")
+        .scanType("RANGE SCAN").table(indexTableName + "L(" + dataTableName + ")")
+        .keyRanges(" [1,*] - [1,100]").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .clientSortAlgo("CLIENT MERGE SORT");
+      ResultSet rs = conn1.createStatement().executeQuery("SELECT COUNT(*) FROM " + dataTableName);
       rs.next();
       int count = rs.getInt(1);
       int deleted = conn1.createStatement().executeUpdate(query);
@@ -153,14 +153,10 @@ public class GlobalIndexOptimizationIT extends ParallelStatsDisabledIT {
 
       String query = "SELECT /*+ INDEX(" + dataTableName + " " + indexTableName + ")*/ * FROM "
         + dataTableName + " where v1='a'";
-      ResultSet rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-
-      String expected = "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexTableName + " ['a']\n"
-        + "    SERVER MERGE [0.K3]\n" + "    SERVER FILTER BY FIRST KEY ONLY";
-      String actual = QueryUtil.getExplainPlan(rs);
-      assertTrue("Expected:\n" + expected + "\nbut got\n" + actual, actual.equals(expected));
+      assertPlan(conn1, query).scanType("RANGE SCAN").table(indexTableName).keyRanges(" ['a']")
+        .serverMergeColumns("[0.K3]").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY");
 
-      rs = conn1.createStatement().executeQuery(query);
+      ResultSet rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
       assertEquals("f", rs.getString("t_id"));
       assertEquals(1, rs.getInt("k1"));
@@ -175,12 +171,8 @@ public class GlobalIndexOptimizationIT extends ParallelStatsDisabledIT {
 
       query = "SELECT /*+ INDEX(" + dataTableName + " " + indexTableName + ")*/ * FROM "
         + dataTableName + " where v1='a'";
-      rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-
-      expected = "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexTableName + " ['a']\n"
-        + "    SERVER MERGE [0.K3]\n" + "    SERVER FILTER BY FIRST KEY ONLY";
-      actual = QueryUtil.getExplainPlan(rs);
-      assertTrue("Expected:\n" + expected + "\nbut got\n" + actual, actual.equals(expected));
+      assertPlan(conn1, query).scanType("RANGE SCAN").table(indexTableName).keyRanges(" ['a']")
+        .serverMergeColumns("[0.K3]").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY");
 
       rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -199,13 +191,9 @@ public class GlobalIndexOptimizationIT extends ParallelStatsDisabledIT {
 
       query = "SELECT /*+ INDEX(" + dataTableName + " " + indexTableName + ")*/ * FROM "
         + dataTableName + " where v1='a' limit 1";
-      rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-
-      expected = "CLIENT SERIAL 1-WAY RANGE SCAN OVER " + indexTableName + " ['a']\n"
-        + "    SERVER MERGE [0.K3]\n" + "    SERVER FILTER BY FIRST KEY ONLY\n"
-        + "    SERVER 1 ROW LIMIT\n" + "CLIENT 1 ROW LIMIT";
-      actual = QueryUtil.getExplainPlan(rs);
-      assertTrue("Expected:\n" + expected + "\nbut got\n" + actual, actual.equals(expected));
+      assertPlan(conn1, query).iteratorType("SERIAL").scanType("RANGE SCAN").table(indexTableName)
+        .keyRanges(" ['a']").serverMergeColumns("[0.K3]")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").serverRowLimit(1L).clientRowLimit(1);
 
       rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -219,12 +207,9 @@ public class GlobalIndexOptimizationIT extends ParallelStatsDisabledIT {
       query = "SELECT /*+ INDEX(" + dataTableName + " " + indexTableName
         + ")*/ t_id, k1, k2, k3, V1 from " + dataTableFullName
         + "  where v1<='z' and k3 > 1 order by V1,t_id";
-      rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-
-      expected = "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexTableName + " [*] - ['z']\n"
-        + "    SERVER MERGE [0.K3]\n" + "    SERVER FILTER BY FIRST KEY ONLY AND \"K3\" > 1";
-      actual = QueryUtil.getExplainPlan(rs);
-      assertTrue("Expected:\n" + expected + "\nbut got\n" + actual, actual.equals(expected));
+      assertPlan(conn1, query).scanType("RANGE SCAN").table(indexTableName)
+        .keyRanges(" [*] - ['z']").serverMergeColumns("[0.K3]")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY AND \"K3\" > 1");
 
       rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -251,18 +236,24 @@ public class GlobalIndexOptimizationIT extends ParallelStatsDisabledIT {
       query = "SELECT /*+ INDEX(" + dataTableName + " " + indexTableName
         + "), NO_INDEX_SERVER_MERGE */ t_id, k1, k2, k3, V1 from " + dataTableFullName
         + "  where v1<='z' and k3 > 1 order by V1,t_id";
-      rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-      expected = "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + dataTableName + "\n"
-        + "    SERVER FILTER BY K3 > 1\n" + "    SERVER SORTED BY \\[" + dataTableName + "\\.V1, "
-        + dataTableName + "\\.T_ID\\]\n" + "CLIENT MERGE SORT\n" + "    SKIP-SCAN-JOIN TABLE 0\n"
-        + "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexTableName
-        + " \\[\\*\\] - \\['z'\\]\n" + "            SERVER FILTER BY FIRST KEY ONLY\n"
-        + "    DYNAMIC SERVER FILTER BY \\(\"" + dataTableName + "\\.T_ID\", \"" + dataTableName
-        + "\\.K1\", \"" + dataTableName
+      ExplainPlanAssert skipScanJoinPlan = assertPlan(conn1, query).scanType("FULL SCAN")
+        .table(dataTableName).serverWhereFilter("SERVER FILTER BY K3 > 1")
+        .serverSortedBy("[" + dataTableName + ".V1, " + dataTableName + ".T_ID]")
+        .clientSortAlgo("CLIENT MERGE SORT");
+      skipScanJoinPlan.subPlanCount(1).subPlan(0).abstractExplainPlan("SKIP-SCAN-JOIN TABLE 0")
+        .scanType("RANGE SCAN").table(indexTableName).keyRanges(" [*] - ['z']")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").end();
+      // The dynamic server filter references compiler-generated positional aliases ($N.$N) whose
+      // numbers are not stable, so match the structural shape of the attribute with a regex.
+      String dynamicServerFilter = skipScanJoinPlan.attributes().getDynamicServerFilter();
+      String dynamicServerFilterPattern = "DYNAMIC SERVER FILTER BY \\(\"" + dataTableName
+        + "\\.T_ID\", \"" + dataTableName + "\\.K1\", \"" + dataTableName
         + "\\.K2\"\\) IN \\(\\(\\$\\d+\\.\\$\\d+, \\$\\d+\\.\\$\\d+, \\$\\d+\\.\\$\\d+\\)\\)";
-      actual = QueryUtil.getExplainPlan(rs);
-      assertTrue("Expected:\n" + expected + "\nbut got\n" + actual,
-        Pattern.matches(expected, actual));
+      assertTrue(
+        "Expected dynamic server filter to match:\n" + dynamicServerFilterPattern + "\nbut got\n"
+          + dynamicServerFilter,
+        dynamicServerFilter != null
+          && Pattern.matches(dynamicServerFilterPattern, dynamicServerFilter));
 
       rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -287,14 +278,11 @@ public class GlobalIndexOptimizationIT extends ParallelStatsDisabledIT {
 
       query = "SELECT /*+ INDEX(" + dataTableName + " " + indexTableName + ")*/ t_id, V1, k3 from "
         + dataTableFullName + "  where v1 <='z' group by v1,t_id, k3";
-      rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-      expected = "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexTableName + " [*] - ['z']\n"
-        + "    SERVER MERGE [0.K3]\n" + "    SERVER FILTER BY FIRST KEY ONLY\n"
-        + "    SERVER AGGREGATE INTO DISTINCT ROWS BY [\"V1\", \"T_ID\", \"K3\"]\n"
-        + "CLIENT MERGE SORT";
-
-      actual = QueryUtil.getExplainPlan(rs);
-      assertTrue("Expected:\n" + expected + "\nbut got\n" + actual, actual.equals(expected));
+      assertPlan(conn1, query).scanType("RANGE SCAN").table(indexTableName)
+        .keyRanges(" [*] - ['z']").serverMergeColumns("[0.K3]")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .serverAggregate("SERVER AGGREGATE INTO DISTINCT ROWS BY [\"V1\", \"T_ID\", \"K3\"]")
+        .clientSortAlgo("CLIENT MERGE SORT");
 
       rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -319,12 +307,10 @@ public class GlobalIndexOptimizationIT extends ParallelStatsDisabledIT {
       query = "SELECT /*+ INDEX(" + dataTableName + " " + indexTableName + ")*/ v1,sum(k3) from "
         + dataTableFullName + " where v1 <='z'  group by v1 order by v1";
 
-      rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-      expected = "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexTableName + " [*] - ['z']\n"
-        + "    SERVER MERGE [0.K3]\n" + "    SERVER FILTER BY FIRST KEY ONLY\n"
-        + "    SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [\"V1\"]";
-      actual = QueryUtil.getExplainPlan(rs);
-      assertTrue("Expected:\n" + expected + "\nbut got\n" + actual, actual.equals(expected));
+      assertPlan(conn1, query).scanType("RANGE SCAN").table(indexTableName)
+        .keyRanges(" [*] - ['z']").serverMergeColumns("[0.K3]")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .serverAggregate("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [\"V1\"]");
 
       rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -356,14 +342,11 @@ public class GlobalIndexOptimizationIT extends ParallelStatsDisabledIT {
 
       String query = "SELECT /*+ INDEX(" + dataTableName + " " + indexTableName
         + ")*/ k1,k2,k3,v1 FROM " + dataTableName + " where v1='a'";
-      ResultSet rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-
-      String actual = QueryUtil.getExplainPlan(rs);
-      String expected = "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexTableName
-        + " ['tid1','a']\n" + "    SERVER MERGE [0.K3]\n" + "    SERVER FILTER BY FIRST KEY ONLY";
-      assertTrue("Expected:\n" + expected + "\nbut got\n" + actual, actual.equals(expected));
+      assertPlan(conn1, query).scanType("RANGE SCAN").table(indexTableName)
+        .keyRanges(" ['tid1','a']").serverMergeColumns("[0.K3]")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY");
 
-      rs = conn1.createStatement().executeQuery(query);
+      ResultSet rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
       assertEquals(1, rs.getInt("k1"));
       assertEquals(2, rs.getInt("k2"));
@@ -406,19 +389,15 @@ public class GlobalIndexOptimizationIT extends ParallelStatsDisabledIT {
 
       String query = "SELECT /*+ INDEX(" + viewName + " " + viewIndex + ")*/ t_id,k1,k2,k3,v1 FROM "
         + viewName + " where k1 IN (1,2) and k2 IN (3,4)";
-      rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
 
       /**
        * This inner "_IDX_" + dataTableName use skipScan, and all the whereExpressions are already
        * in SkipScanFilter, so there is no other RowKeyComparisonFilter needed.
        */
 
-      String actual = QueryUtil.getExplainPlan(rs);
-      String expected = "CLIENT PARALLEL 1-WAY SKIP SCAN ON 2 KEYS OVER _IDX_" + dataTableName
-        + " [" + Short.MIN_VALUE + ",1] - [" + Short.MIN_VALUE + ",2]\n"
-        + "    SERVER MERGE [0.K3]\n" + "    SERVER FILTER BY FIRST KEY ONLY";
-
-      assertEquals(expected, actual);
+      assertPlan(conn1, query).scanType("SKIP SCAN ON 2 KEYS").table("_IDX_" + dataTableName)
+        .keyRanges(" [" + Short.MIN_VALUE + ",1] - [" + Short.MIN_VALUE + ",2]")
+        .serverMergeColumns("[0.K3]").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY");
 
       rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -455,12 +434,10 @@ public class GlobalIndexOptimizationIT extends ParallelStatsDisabledIT {
       // All columns available in index
       String query = "SELECT /*+ INDEX(" + dataTableName + " " + indexTableName
         + ")*/ t_id, k1, k2, V1 FROM " + dataTableName + " where v1='a'";
-      ResultSet rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
+      assertPlan(conn1, query).scanType("RANGE SCAN").table(indexTableName).keyRanges(" ['a']")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY");
 
-      assertEquals("CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexTableName + " ['a']\n"
-        + "    SERVER FILTER BY FIRST KEY ONLY", QueryUtil.getExplainPlan(rs));
-
-      rs = conn1.createStatement().executeQuery(query);
+      ResultSet rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
       assertEquals("f", rs.getString("t_id"));
       assertEquals(1, rs.getInt("k1"));
@@ -473,10 +450,8 @@ public class GlobalIndexOptimizationIT extends ParallelStatsDisabledIT {
 
       // No INDEX hint specified
       query = "SELECT t_id, k1, k2, k3, V1 FROM " + dataTableName + " where v1='a'";
-      rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-
-      assertEquals("CLIENT PARALLEL 1-WAY FULL SCAN OVER " + dataTableName + "\n"
-        + "    SERVER FILTER BY V1 = 'a'", QueryUtil.getExplainPlan(rs));
+      assertPlan(conn1, query).scanType("FULL SCAN").table(dataTableName)
+        .serverWhereFilter("SERVER FILTER BY V1 = 'a'");
 
       rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -493,12 +468,8 @@ public class GlobalIndexOptimizationIT extends ParallelStatsDisabledIT {
 
       // No where clause
       query = "SELECT  t_id, k1, k2, k3, V1 from " + dataTableFullName + " order by V1,t_id";
-      rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-
-      assertEquals(
-        "CLIENT PARALLEL 4-WAY FULL SCAN OVER " + dataTableName + "\n"
-          + "    SERVER SORTED BY [V1, T_ID]\n" + "CLIENT MERGE SORT",
-        QueryUtil.getExplainPlan(rs));
+      assertPlan(conn1, query).scanType("FULL SCAN").table(dataTableName)
+        .serverSortedBy("[V1, T_ID]").clientSortAlgo("CLIENT MERGE SORT");
 
       rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -530,11 +501,9 @@ public class GlobalIndexOptimizationIT extends ParallelStatsDisabledIT {
       // No where clause in index scan
       query =
         "SELECT t_id, k1, k2, k3, V1 from " + dataTableFullName + "  where k3 > 1 order by V1,t_id";
-      rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-
-      assertEquals("CLIENT PARALLEL 4-WAY FULL SCAN OVER " + dataTableName + "\n"
-        + "    SERVER FILTER BY K3 > 1\n" + "    SERVER SORTED BY [V1, T_ID]\n"
-        + "CLIENT MERGE SORT", QueryUtil.getExplainPlan(rs));
+      assertPlan(conn1, query).scanType("FULL SCAN").table(dataTableName)
+        .serverWhereFilter("SERVER FILTER BY K3 > 1").serverSortedBy("[V1, T_ID]")
+        .clientSortAlgo("CLIENT MERGE SORT");
 
       rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/ImmutableIndexWithStatsIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/ImmutableIndexWithStatsIT.java
index 575ba7be4d..d998dd60a7 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/ImmutableIndexWithStatsIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/ImmutableIndexWithStatsIT.java
@@ -17,8 +17,8 @@
  */
 package org.apache.phoenix.end2end.index;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
-import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 
@@ -27,11 +27,8 @@ import java.sql.DriverManager;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.util.Properties;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.end2end.ParallelStatsEnabledIT;
 import org.apache.phoenix.end2end.ParallelStatsEnabledTest;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.util.PropertiesUtil;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -64,12 +61,7 @@ public class ImmutableIndexWithStatsIT extends ParallelStatsEnabledIT {
 
     conn.createStatement().execute("UPDATE STATISTICS " + tableName);
     query = "SELECT COUNT(*) FROM " + tableName;
-
-    ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-      .optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
+    assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN");
 
     String indexName = "I_" + generateUniqueName();
     conn.createStatement().execute("CREATE INDEX " + indexName + " ON " + tableName + " (v)");
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/IndexMaintenanceIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/IndexMaintenanceIT.java
index 0995ced87b..e8b5500325 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/IndexMaintenanceIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/IndexMaintenanceIT.java
@@ -18,6 +18,7 @@
 package org.apache.phoenix.end2end.index;
 
 import static org.apache.phoenix.query.QueryConstants.MILLIS_IN_DAY;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.INDEX_DATA_SCHEMA;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
@@ -35,10 +36,10 @@ import java.util.Properties;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.phoenix.end2end.ParallelStatsDisabledIT;
 import org.apache.phoenix.end2end.ParallelStatsDisabledTest;
+import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.QueryConstants;
 import org.apache.phoenix.util.DateUtil;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.TestUtil;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -157,17 +158,20 @@ public class IndexMaintenanceIT extends ParallelStatsDisabledIT {
       stmt.setDate(5, date);
 
       // verify that the query does a range scan on the index table
-      ResultSet rs = stmt.executeQuery("EXPLAIN " + whereSql);
-      assertEquals(localIndex
-        ? "CLIENT PARALLEL 1-WAY RANGE SCAN OVER INDEX_TEST." + indexName + "(" + fullDataTableName
-          + ")"
-          + " [1,'VARCHAR1_CHAR1     _A.VARCHAR1_B.CHAR1   ',3,'2015-01-02 00:00:00.000',1,420,156,800,000,1,420,156,800,000]\nCLIENT MERGE SORT"
-        : "CLIENT PARALLEL 1-WAY RANGE SCAN OVER INDEX_TEST." + indexName
-          + " ['VARCHAR1_CHAR1     _A.VARCHAR1_B.CHAR1   ',3,'2015-01-02 00:00:00.000',1,420,156,800,000,1,420,156,800,000]",
-        QueryUtil.getExplainPlan(rs));
+      if (localIndex) {
+        assertPlan(stmt.unwrap(PhoenixPreparedStatement.class)).scanType("RANGE SCAN")
+          .tableContains("INDEX_TEST." + indexName + "(" + fullDataTableName + ")")
+          .keyRanges(
+            " [1,'VARCHAR1_CHAR1     _A.VARCHAR1_B.CHAR1   ',3,'2015-01-02 00:00:00.000',1,420,156,800,000,1,420,156,800,000]")
+          .clientSortAlgo("CLIENT MERGE SORT");
+      } else {
+        assertPlan(stmt.unwrap(PhoenixPreparedStatement.class)).scanType("RANGE SCAN")
+          .tableContains("INDEX_TEST." + indexName).keyRanges(
+            " ['VARCHAR1_CHAR1     _A.VARCHAR1_B.CHAR1   ',3,'2015-01-02 00:00:00.000',1,420,156,800,000,1,420,156,800,000]");
+      }
 
       // verify that the correct results are returned
-      rs = stmt.executeQuery();
+      ResultSet rs = stmt.executeQuery();
       assertTrue(rs.next());
       assertEquals(1, rs.getInt(1));
       assertEquals(1, rs.getInt(2));
@@ -179,13 +183,14 @@ public class IndexMaintenanceIT extends ParallelStatsDisabledIT {
           + "decimal_pk+int_pk+decimal_col2+int_col1, " + "date_pk+1, date1+1, date2+1, "
           + "varchar_pk, char_pk, int_pk, long_pk, decimal_pk, " + "long_col1, long_col2 " + "from "
           + fullDataTableName;
-      rs = conn.createStatement().executeQuery("EXPLAIN " + indexSelectSql);
-      assertEquals(
-        localIndex
-          ? "CLIENT PARALLEL 1-WAY RANGE SCAN OVER INDEX_TEST." + indexName + "("
-            + fullDataTableName + ") [1]\nCLIENT MERGE SORT"
-          : "CLIENT PARALLEL 1-WAY FULL SCAN OVER INDEX_TEST." + indexName,
-        QueryUtil.getExplainPlan(rs));
+      if (localIndex) {
+        assertPlan(conn, indexSelectSql).scanType("RANGE SCAN")
+          .tableContains("INDEX_TEST." + indexName + "(" + fullDataTableName + ")")
+          .keyRanges(" [1]").clientSortAlgo("CLIENT MERGE SORT");
+      } else {
+        assertPlan(conn, indexSelectSql).scanType("FULL SCAN")
+          .tableContains("INDEX_TEST." + indexName);
+      }
       rs = conn.createStatement().executeQuery(indexSelectSql);
       verifyResult(rs, 1);
       verifyResult(rs, 2);
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/IndexUsageIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/IndexUsageIT.java
index c75d1107d7..0abd7ca913 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/IndexUsageIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/IndexUsageIT.java
@@ -18,11 +18,11 @@
 package org.apache.phoenix.end2end.index;
 
 import static org.apache.phoenix.query.QueryConstants.MILLIS_IN_DAY;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.INDEX_DATA_SCHEMA;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
@@ -34,17 +34,14 @@ import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.util.Properties;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.end2end.ParallelStatsDisabledIT;
 import org.apache.phoenix.end2end.ParallelStatsDisabledTest;
 import org.apache.phoenix.exception.SQLExceptionCode;
 import org.apache.phoenix.execute.CommitException;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.QueryConstants;
+import org.apache.phoenix.query.explain.ExplainPlanTestUtil;
 import org.apache.phoenix.util.DateUtil;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.TestUtil;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -133,24 +130,16 @@ public class IndexUsageIT extends ParallelStatsDisabledIT {
       String groupBySql = "SELECT (int_col1+int_col2), COUNT(*) FROM " + fullDataTableName
         + " GROUP BY (int_col1+int_col2)";
 
-      ExplainPlan plan = conn.prepareStatement(groupBySql).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-      assertEquals(
-        "SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY "
-          + "[TO_BIGINT(\"(A.INT_COL1 + B.INT_COL2)\")]",
-        explainPlanAttributes.getServerAggregate());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan = assertPlan(conn, groupBySql)
+        .iteratorType("PARALLEL 1-WAY").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .serverAggregate("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY "
+          + "[TO_BIGINT(\"(A.INT_COL1 + B.INT_COL2)\")]");
       if (localIndex) {
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals("INDEX_TEST." + indexName + "(" + fullDataTableName + ")",
-          explainPlanAttributes.getTableName());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("RANGE SCAN")
+          .table("INDEX_TEST." + indexName + "(" + fullDataTableName + ")")
+          .clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals("INDEX_TEST." + indexName, explainPlanAttributes.getTableName());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("FULL SCAN").table("INDEX_TEST." + indexName).clientSortAlgo(null);
       }
       ResultSet rs = conn.createStatement().executeQuery(groupBySql);
       assertTrue(rs.next());
@@ -195,26 +184,18 @@ public class IndexUsageIT extends ParallelStatsDisabledIT {
       conn.createStatement().execute(ddl);
       String sql = "SELECT distinct int_col1+1 FROM " + fullDataTableName + " where int_col1+1 > 0";
 
-      ExplainPlan plan = conn.prepareStatement(sql).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-      assertEquals("SERVER DISTINCT PREFIX FILTER OVER [TO_BIGINT(\"(A.INT_COL1 + 1)\")]",
-        explainPlanAttributes.getServerDistinctFilter());
-      assertEquals(
-        "SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [TO_BIGINT(\"(A.INT_COL1 + 1)\")]",
-        explainPlanAttributes.getServerAggregate());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan = assertPlan(conn, sql)
+        .iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .serverDistinctFilter(
+          "SERVER DISTINCT PREFIX FILTER OVER " + "[TO_BIGINT(\"(A.INT_COL1 + 1)\")]")
+        .serverAggregate(
+          "SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY " + "[TO_BIGINT(\"(A.INT_COL1 + 1)\")]");
       if (localIndex) {
-        assertEquals("INDEX_TEST." + indexName + "(" + fullDataTableName + ")",
-          explainPlanAttributes.getTableName());
-        assertEquals(" [1,0] - [1,*]", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        basePlan.table("INDEX_TEST." + indexName + "(" + fullDataTableName + ")")
+          .keyRanges(" [1,0] - [1,*]").clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("INDEX_TEST." + indexName, explainPlanAttributes.getTableName());
-        assertEquals(" [0] - [*]", explainPlanAttributes.getKeyRanges());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.table("INDEX_TEST." + indexName).keyRanges(" [0] - [*]").clientSortAlgo(null);
       }
 
       ResultSet rs = conn.createStatement().executeQuery(sql);
@@ -262,21 +243,14 @@ public class IndexUsageIT extends ParallelStatsDisabledIT {
       conn.createStatement().execute(ddl);
       String sql = "SELECT int_col1+1 FROM " + fullDataTableName + " where int_col1+1 IN (2)";
 
-      ExplainPlan plan = conn.prepareStatement(sql).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan =
+        assertPlan(conn, sql).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+          .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY");
       if (localIndex) {
-        assertEquals("INDEX_TEST." + indexName + "(" + fullDataTableName + ")",
-          explainPlanAttributes.getTableName());
-        assertEquals(" [1,2]", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        basePlan.table("INDEX_TEST." + indexName + "(" + fullDataTableName + ")")
+          .keyRanges(" [1,2]").clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("INDEX_TEST." + indexName, explainPlanAttributes.getTableName());
-        assertEquals(" [2]", explainPlanAttributes.getKeyRanges());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.table("INDEX_TEST." + indexName).keyRanges(" [2]").clientSortAlgo(null);
       }
 
       ResultSet rs = conn.createStatement().executeQuery(sql);
@@ -323,21 +297,14 @@ public class IndexUsageIT extends ParallelStatsDisabledIT {
       conn.createStatement().execute(ddl);
       String sql = "SELECT int_col1+1 AS foo FROM " + fullDataTableName + " ORDER BY foo";
 
-      ExplainPlan plan = conn.prepareStatement(sql).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan = assertPlan(conn, sql)
+        .iteratorType("PARALLEL 1-WAY").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY");
       if (localIndex) {
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals("INDEX_TEST." + indexName + "(" + fullDataTableName + ")",
-          explainPlanAttributes.getTableName());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("RANGE SCAN")
+          .table("INDEX_TEST." + indexName + "(" + fullDataTableName + ")").keyRanges(" [1]")
+          .clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals("INDEX_TEST." + indexName, explainPlanAttributes.getTableName());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("FULL SCAN").table("INDEX_TEST." + indexName).clientSortAlgo(null);
       }
 
       ResultSet rs = conn.createStatement().executeQuery(sql);
@@ -404,19 +371,13 @@ public class IndexUsageIT extends ParallelStatsDisabledIT {
 
       query = "SELECT (\"V1\" || '_' || \"v2\"), k, \"V1\", \"v2\"  FROM " + dataTableName
         + " WHERE (\"V1\" || '_' || \"v2\") = 'x_1'";
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan =
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN");
       if (localIndex) {
-        assertEquals(indexName + "(" + dataTableName + ")", explainPlanAttributes.getTableName());
-        assertEquals(" [1,'x_1']", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        basePlan.table(indexName + "(" + dataTableName + ")").keyRanges(" [1,'x_1']")
+          .clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals(indexName, explainPlanAttributes.getTableName());
-        assertEquals(" ['x_1']", explainPlanAttributes.getKeyRanges());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.table(indexName).keyRanges(" ['x_1']").clientSortAlgo(null);
       }
 
       rs = conn.createStatement().executeQuery(query);
@@ -435,19 +396,12 @@ public class IndexUsageIT extends ParallelStatsDisabledIT {
       query =
         "SELECT \"V1\", \"V1\" as foo1, (\"V1\" || '_' || \"v2\") as foo, (\"V1\" || '_' || \"v2\") as \"Foo1\", (\"V1\" || '_' || \"v2\") FROM "
           + dataTableName + " ORDER BY foo";
-      plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
+      basePlan = assertPlan(conn, query).iteratorType("PARALLEL 1-WAY");
       if (localIndex) {
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(indexName + "(" + dataTableName + ")", explainPlanAttributes.getTableName());
-        assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("RANGE SCAN").table(indexName + "(" + dataTableName + ")")
+          .keyRanges(" [1]").clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(indexName, explainPlanAttributes.getTableName());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.scanType("FULL SCAN").table(indexName).clientSortAlgo(null);
       }
 
       rs = conn.createStatement().executeQuery(query);
@@ -517,24 +471,15 @@ public class IndexUsageIT extends ParallelStatsDisabledIT {
       conn.createStatement().execute(ddl);
       String sql = "SELECT int_col1+1, int_col2 FROM " + fullDataTableName + " WHERE int_col1+1=2";
 
-      ExplainPlan plan = conn.prepareStatement(sql).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan =
+        assertPlan(conn, sql).iteratorType("PARALLEL 1-WAY");
       if (localIndex) {
-        assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals("INDEX_TEST." + indexName + "(" + fullDataTableName + ")",
-          explainPlanAttributes.getTableName());
-        assertEquals(" [1,2]", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
-        assertEquals("SERVER FILTER BY FIRST KEY ONLY",
-          explainPlanAttributes.getServerWhereFilter());
+        basePlan.scanType("RANGE SCAN")
+          .table("INDEX_TEST." + indexName + "(" + fullDataTableName + ")").keyRanges(" [1,2]")
+          .clientSortAlgo("CLIENT MERGE SORT").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY");
       } else {
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(fullDataTableName, explainPlanAttributes.getTableName());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
-        assertEquals("SERVER FILTER BY (A.INT_COL1 + 1) = 2",
-          explainPlanAttributes.getServerWhereFilter());
+        basePlan.scanType("FULL SCAN").table(fullDataTableName).clientSortAlgo(null)
+          .serverWhereFilter("SERVER FILTER BY (A.INT_COL1 + 1) = 2");
       }
 
       ResultSet rs = conn.createStatement().executeQuery(sql);
@@ -582,19 +527,14 @@ public class IndexUsageIT extends ParallelStatsDisabledIT {
       conn.commit();
 
       String query = "SELECT k1, k2, k3, s1, s2 FROM " + viewName + " WHERE k1+k2+k3 = 173.0";
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan =
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN");
       if (local) {
-        assertEquals(indexName1 + "(" + dataTableName + ")", explainPlanAttributes.getTableName());
-        assertEquals(" [1,173]", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        basePlan.table(indexName1 + "(" + dataTableName + ")").keyRanges(" [1,173]")
+          .clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("_IDX_" + dataTableName, explainPlanAttributes.getTableName());
-        assertEquals(" [" + Short.MIN_VALUE + ",173]", explainPlanAttributes.getKeyRanges());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.table("_IDX_" + dataTableName).keyRanges(" [" + Short.MIN_VALUE + ",173]")
+          .clientSortAlgo(null);
       }
 
       rs = conn.createStatement().executeQuery(query);
@@ -610,21 +550,14 @@ public class IndexUsageIT extends ParallelStatsDisabledIT {
         + " on " + viewName + "(s1||'_'||s2)");
 
       query = "SELECT k1, k2, s1||'_'||s2 FROM " + viewName + " WHERE (s1||'_'||s2)='foo2_bar2'";
-      plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-        .getExplainPlan();
-      explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
+      basePlan = assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY");
       if (local) {
-        assertEquals(indexName2 + "(" + dataTableName + ")", explainPlanAttributes.getTableName());
-        assertEquals(" [" + (2) + ",'foo2_bar2']", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        basePlan.table(indexName2 + "(" + dataTableName + ")")
+          .keyRanges(" [" + (2) + ",'foo2_bar2']").clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("_IDX_" + dataTableName, explainPlanAttributes.getTableName());
-        assertEquals(" [" + (Short.MIN_VALUE + 1) + ",'foo2_bar2']",
-          explainPlanAttributes.getKeyRanges());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.table("_IDX_" + dataTableName)
+          .keyRanges(" [" + (Short.MIN_VALUE + 1) + ",'foo2_bar2']").clientSortAlgo(null);
       }
 
       rs = conn.createStatement().executeQuery(query);
@@ -680,14 +613,9 @@ public class IndexUsageIT extends ParallelStatsDisabledIT {
       String query =
         "SELECT s2||'_'||s3 FROM " + viewName + " WHERE k2=1 AND (s2||'_'||s3)='abc_cab'";
 
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(indexName2, explainPlanAttributes.getTableName());
-      assertEquals(" [1,'abc_cab','foo']", explainPlanAttributes.getKeyRanges());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
+      assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+        .table(indexName2).keyRanges(" [1,'abc_cab','foo']")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY");
 
       rs = conn.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -696,11 +624,9 @@ public class IndexUsageIT extends ParallelStatsDisabledIT {
 
       conn.createStatement().execute("ALTER VIEW " + viewName + " DROP COLUMN s4");
       // i2 cannot be used since s4 has been dropped from the view, so i1 will be used
-      rs = conn.createStatement().executeQuery("EXPLAIN " + query);
-      String queryPlan = QueryUtil.getExplainPlan(rs);
-      assertEquals("CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexName1 + " [1]\n"
-        + "    SERVER FILTER BY FIRST KEY ONLY AND ((\"S2\" || '_' || \"S3\") = 'abc_cab' AND \"S1\" = 'foo')",
-        queryPlan);
+      assertPlan(conn, query).scanType("RANGE SCAN").tableContains(indexName1).keyRanges(" [1]")
+        .serverWhereFilter(
+          "SERVER FILTER BY FIRST KEY ONLY AND ((\"S2\" || '_' || \"S3\") = 'abc_cab' AND \"S1\" = 'foo')");
       rs = conn.createStatement().executeQuery(query);
       assertTrue(rs.next());
       assertEquals("abc_cab", rs.getString(1));
@@ -784,20 +710,14 @@ public class IndexUsageIT extends ParallelStatsDisabledIT {
 
       query = "SELECT k FROM " + dataTableName + " WHERE REGEXP_SUBSTR(v,'id:\\\\w+') = 'id:id1'";
 
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
+      ExplainPlanTestUtil.ExplainPlanAssert basePlan =
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+          .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY");
       if (localIndex) {
-        assertEquals(indexName + "(" + dataTableName + ")", explainPlanAttributes.getTableName());
-        assertEquals(" [1,'id:id1']", explainPlanAttributes.getKeyRanges());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        basePlan.table(indexName + "(" + dataTableName + ")").keyRanges(" [1,'id:id1']")
+          .clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals(indexName, explainPlanAttributes.getTableName());
-        assertEquals(" ['id:id1']", explainPlanAttributes.getKeyRanges());
-        assertNull(explainPlanAttributes.getClientSortAlgo());
+        basePlan.table(indexName).keyRanges(" ['id:id1']").clientSortAlgo(null);
       }
 
       rs = conn.createStatement().executeQuery(query);
@@ -860,21 +780,20 @@ public class IndexUsageIT extends ParallelStatsDisabledIT {
       query = "select c.c_customer_sk from  " + tableName + " c " + "left outer join " + tableName
         + " c2 on c.c_customer_sk = c2.c_customer_sk "
         + "where c.c_customer_sk || c.c_first_name = '1David'";
-      rs = conn.createStatement().executeQuery("EXPLAIN " + query);
-      String explainPlan = QueryUtil.getExplainPlan(rs);
       if (localIndex) {
-        assertEquals("CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexName + "(" + tableName
-          + ") [1,'1David']\n" + "    SERVER FILTER BY FIRST KEY ONLY\n" + "CLIENT MERGE SORT\n"
-          + "    PARALLEL LEFT-JOIN TABLE 0 (SKIP MERGE)\n"
-          + "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexName + "(" + tableName
-          + ") [1]\n" + "            SERVER FILTER BY FIRST KEY ONLY\n"
-          + "        CLIENT MERGE SORT", explainPlan);
+        assertPlan(conn, query).scanType("RANGE SCAN")
+          .tableContains(indexName + "(" + tableName + ")").keyRanges(" [1,'1David']")
+          .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").clientSortAlgo("CLIENT MERGE SORT")
+          .subPlanCount(1).subPlan(0).scanType("RANGE SCAN")
+          .tableContains(indexName + "(" + tableName + ")").keyRanges(" [1]")
+          .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").clientSortAlgo("CLIENT MERGE SORT")
+          .abstractExplainPlan("PARALLEL LEFT-JOIN TABLE 0 (SKIP MERGE)").end();
       } else {
-        assertEquals("CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexName + " ['1David']\n"
-          + "    SERVER FILTER BY FIRST KEY ONLY\n"
-          + "    PARALLEL LEFT-JOIN TABLE 0 (SKIP MERGE)\n"
-          + "        CLIENT PARALLEL 1-WAY FULL SCAN OVER " + indexName + "\n"
-          + "            SERVER FILTER BY FIRST KEY ONLY", explainPlan);
+        assertPlan(conn, query).scanType("RANGE SCAN").tableContains(indexName)
+          .keyRanges(" ['1David']").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+          .subPlanCount(1).subPlan(0).scanType("FULL SCAN").tableContains(indexName)
+          .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+          .abstractExplainPlan("PARALLEL LEFT-JOIN TABLE 0 (SKIP MERGE)").end();
       }
 
       rs = conn.createStatement().executeQuery(query);
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/LocalIndexIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/LocalIndexIT.java
index ea8f752afd..fffacd4fc3 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/LocalIndexIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/LocalIndexIT.java
@@ -18,6 +18,7 @@
 package org.apache.phoenix.end2end.index;
 
 import static org.apache.phoenix.end2end.ExplainPlanWithStatsEnabledIT.getByteRowEstimates;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.MetaDataUtil.getViewIndexSequenceName;
 import static org.apache.phoenix.util.MetaDataUtil.getViewIndexSequenceSchemaName;
 import static org.junit.Assert.assertArrayEquals;
@@ -56,14 +57,11 @@ import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
 import org.apache.hadoop.hbase.util.Bytes;
 import org.apache.hadoop.hbase.util.CommonFSUtils;
 import org.apache.hadoop.hbase.util.Pair;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.compile.QueryPlan;
 import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
 import org.apache.phoenix.end2end.ExplainPlanWithStatsEnabledIT.Estimate;
 import org.apache.phoenix.hbase.index.IndexRegionSplitPolicy;
 import org.apache.phoenix.jdbc.PhoenixConnection;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.jdbc.PhoenixResultSet;
 import org.apache.phoenix.jdbc.PhoenixStatement;
 import org.apache.phoenix.query.QueryConstants;
@@ -73,7 +71,6 @@ import org.apache.phoenix.schema.PTable.IndexType;
 import org.apache.phoenix.schema.PTableKey;
 import org.apache.phoenix.schema.TableNotFoundException;
 import org.apache.phoenix.util.EnvironmentEdgeManager;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.TestUtil;
 import org.junit.Test;
@@ -438,54 +435,29 @@ public class LocalIndexIT extends BaseLocalIndexIT {
       .execute("CREATE LOCAL INDEX " + indexName + " ON " + tableName + "(pk1,pk2,v1,v2)");
 
     // 1. same prefix length, no other restrictions, but v3 is in the SELECT. Use the main table.
-    ExplainPlan explainPlan =
-      conn.prepareStatement("SELECT * FROM " + tableName + " WHERE pk1 = 3 AND pk2 = 4")
-        .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    ExplainPlanAttributes explainPlanAttributes = explainPlan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(physicalTableName.toString(), explainPlanAttributes.getTableName());
-    assertEquals(" [3,4]", explainPlanAttributes.getKeyRanges());
+    assertPlan(conn, "SELECT * FROM " + tableName + " WHERE pk1 = 3 AND pk2 = 4")
+      .iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN").table(physicalTableName.toString())
+      .keyRanges(" [3,4]");
 
     // 2. same prefix length, no other restrictions. Only index columns used. Use the index.
-    explainPlan =
-      conn.prepareStatement("SELECT v2 FROM " + tableName + " WHERE pk1 = 3 AND pk2 = 4")
-        .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    explainPlanAttributes = explainPlan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(fullIndexName + "(" + indexPhysicalTableName + ")",
-      explainPlanAttributes.getTableName());
-    assertEquals(" [1,3,4]", explainPlanAttributes.getKeyRanges());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY", explainPlanAttributes.getServerWhereFilter());
-    assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+    assertPlan(conn, "SELECT v2 FROM " + tableName + " WHERE pk1 = 3 AND pk2 = 4")
+      .iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+      .table(fullIndexName + "(" + indexPhysicalTableName + ")").keyRanges(" [1,3,4]")
+      .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").clientSortAlgo("CLIENT MERGE SORT");
 
     // 3. same prefix length, but there's a column not on the index
-    explainPlan =
-      conn.prepareStatement("SELECT v2 FROM " + tableName + " WHERE pk1 = 3 AND pk2 = 4 AND v3 = 1")
-        .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    explainPlanAttributes = explainPlan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(physicalTableName.toString(), explainPlanAttributes.getTableName());
-    assertEquals(" [3,4]", explainPlanAttributes.getKeyRanges());
-    assertEquals("SERVER FILTER BY V3 = 1", explainPlanAttributes.getServerWhereFilter());
+    assertPlan(conn, "SELECT v2 FROM " + tableName + " WHERE pk1 = 3 AND pk2 = 4 AND v3 = 1")
+      .iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN").table(physicalTableName.toString())
+      .keyRanges(" [3,4]").serverWhereFilter("SERVER FILTER BY V3 = 1");
 
     // 4. Longer prefix on the index, use it.
-    explainPlan = conn
-      .prepareStatement(
-        "SELECT v2 FROM " + tableName + " WHERE pk1 = 3 AND pk2 = 4 AND v1 = 3 AND v3 = 1")
-      .unwrap(PhoenixPreparedStatement.class).optimizeQuery().getExplainPlan();
-    explainPlanAttributes = explainPlan.getPlanStepsAsAttributes();
-    assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-    assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
-    assertEquals(fullIndexName + "(" + indexPhysicalTableName + ")",
-      explainPlanAttributes.getTableName());
-    assertEquals(" [1,3,4,3]", explainPlanAttributes.getKeyRanges());
-    assertEquals("[0.V3]", explainPlanAttributes.getServerMergeColumns().toString());
-    assertEquals("SERVER FILTER BY FIRST KEY ONLY AND \"V3\" = 1",
-      explainPlanAttributes.getServerWhereFilter());
-    assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+    assertPlan(conn,
+      "SELECT v2 FROM " + tableName + " WHERE pk1 = 3 AND pk2 = 4 AND v1 = 3 AND v3 = 1")
+        .iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+        .table(fullIndexName + "(" + indexPhysicalTableName + ")").keyRanges(" [1,3,4,3]")
+        .serverMergeColumns("[0.V3]")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY AND \"V3\" = 1")
+        .clientSortAlgo("CLIENT MERGE SORT");
   }
 
   @Test
@@ -511,13 +483,11 @@ public class LocalIndexIT extends BaseLocalIndexIT {
       .execute("CREATE LOCAL INDEX " + indexName + " ON " + tableName + "(pk1,pk3)");
 
     // 1. Still use the index
-    ResultSet rs = conn.createStatement().executeQuery(
-      "EXPLAIN SELECT pk1, pk2, pk3, v1 FROM " + tableName + " WHERE pk1 = 2 AND pk3 = 3");
-    assertEquals("CLIENT PARALLEL 16-WAY RANGE SCAN OVER " + fullIndexName + "("
-      + indexPhysicalTableName + ") [1,2,3]\n" + "    SERVER MERGE [0.V1]\n"
-      + "    SERVER FILTER BY FIRST KEY ONLY\n" + "CLIENT MERGE SORT",
-      QueryUtil.getExplainPlan(rs));
-    rs.close();
+    assertPlan(conn, "SELECT pk1, pk2, pk3, v1 FROM " + tableName + " WHERE pk1 = 2 AND pk3 = 3")
+      .iteratorType("PARALLEL").scanType("RANGE SCAN")
+      .table(fullIndexName + "(" + indexPhysicalTableName + ")").keyRanges(" [1,2,3]")
+      .serverMergeColumns("[0.V1]").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+      .clientSortAlgo("CLIENT MERGE SORT");
   }
 
   @Test
@@ -541,90 +511,69 @@ public class LocalIndexIT extends BaseLocalIndexIT {
       .execute("CREATE LOCAL INDEX " + indexName + " ON " + tableName + "(v2, v3, v4)");
 
     // 1. COUNT(*) should still use the index - fewer bytes to scan
-    ResultSet rs = conn.createStatement().executeQuery("EXPLAIN SELECT COUNT(*) FROM " + tableName);
-    assertEquals("CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + fullIndexName + "("
-      + indexPhysicalTableName + ") [1]\n" + "    SERVER FILTER BY FIRST KEY ONLY\n"
-      + "    SERVER AGGREGATE INTO SINGLE ROW", QueryUtil.getExplainPlan(rs));
-    rs.close();
+    assertPlan(conn, "SELECT COUNT(*) FROM " + tableName).iteratorType("PARALLEL 1-WAY")
+      .scanType("RANGE SCAN").table(fullIndexName + "(" + indexPhysicalTableName + ")")
+      .keyRanges(" [1]").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+      .serverAggregate("SERVER AGGREGATE INTO SINGLE ROW");
 
     // 2. All column projected, no filtering by indexed column, not using the index
-    rs = conn.createStatement().executeQuery("EXPLAIN SELECT * FROM " + tableName);
-    assertEquals("CLIENT PARALLEL 1-WAY FULL SCAN OVER " + physicalTableName,
-      QueryUtil.getExplainPlan(rs));
-    rs.close();
+    assertPlan(conn, "SELECT * FROM " + tableName).iteratorType("PARALLEL 1-WAY")
+      .scanType("FULL SCAN").table(physicalTableName.toString());
 
     // 3. if the index can avoid a sort operation, use it
-    rs = conn.createStatement().executeQuery("EXPLAIN SELECT * FROM " + tableName + " ORDER BY v2");
-    assertEquals("CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + fullIndexName + "("
-      + indexPhysicalTableName + ") [1]\n" + "    SERVER MERGE [0.V1]\n"
-      + "    SERVER FILTER BY FIRST KEY ONLY\n" + "CLIENT MERGE SORT",
-      QueryUtil.getExplainPlan(rs));
-    rs.close();
+    assertPlan(conn, "SELECT * FROM " + tableName + " ORDER BY v2").iteratorType("PARALLEL 1-WAY")
+      .scanType("RANGE SCAN").table(fullIndexName + "(" + indexPhysicalTableName + ")")
+      .keyRanges(" [1]").serverMergeColumns("[0.V1]")
+      .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").clientSortAlgo("CLIENT MERGE SORT");
 
     // 4. but can't use the index if not ORDERing by a prefix of the index key.
-    rs = conn.createStatement().executeQuery("EXPLAIN SELECT * FROM " + tableName + " ORDER BY v3");
-    assertEquals("CLIENT PARALLEL 1-WAY FULL SCAN OVER " + physicalTableName + "\n"
-      + "    SERVER SORTED BY [V3]\n" + "CLIENT MERGE SORT", QueryUtil.getExplainPlan(rs));
-    rs.close();
+    assertPlan(conn, "SELECT * FROM " + tableName + " ORDER BY v3").iteratorType("PARALLEL 1-WAY")
+      .scanType("FULL SCAN").table(physicalTableName.toString()).serverSortedBy("[V3]")
+      .clientSortAlgo("CLIENT MERGE SORT");
 
     // 5. If we pin the prefix of the index key we use the index avoiding sorting on the postfix
-    rs = conn.createStatement()
-      .executeQuery("EXPLAIN SELECT * FROM " + tableName + " WHERE v2 = 2 ORDER BY v3");
-    assertEquals("CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + fullIndexName + "("
-      + indexPhysicalTableName + ") [1,2]\n" + "    SERVER MERGE [0.V1]\n"
-      + "    SERVER FILTER BY FIRST KEY ONLY\n" + "CLIENT MERGE SORT",
-      QueryUtil.getExplainPlan(rs));
-    rs.close();
+    assertPlan(conn, "SELECT * FROM " + tableName + " WHERE v2 = 2 ORDER BY v3")
+      .iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+      .table(fullIndexName + "(" + indexPhysicalTableName + ")").keyRanges(" [1,2]")
+      .serverMergeColumns("[0.V1]").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+      .clientSortAlgo("CLIENT MERGE SORT");
 
     // 6. Filtering by a non-indexed column will not use the index
-    rs =
-      conn.createStatement().executeQuery("EXPLAIN SELECT * FROM " + tableName + " WHERE v1 = 3");
-    assertEquals("CLIENT PARALLEL 1-WAY FULL SCAN OVER " + physicalTableName + "\n"
-      + "    SERVER FILTER BY V1 = 3.0", QueryUtil.getExplainPlan(rs));
-    rs.close();
+    assertPlan(conn, "SELECT * FROM " + tableName + " WHERE v1 = 3").iteratorType("PARALLEL 1-WAY")
+      .scanType("FULL SCAN").table(physicalTableName.toString())
+      .serverWhereFilter("SERVER FILTER BY V1 = 3.0");
 
     // 7. Also don't use an index if not filtering on a prefix of the key
-    rs =
-      conn.createStatement().executeQuery("EXPLAIN SELECT * FROM " + tableName + " WHERE v3 = 1");
-    assertEquals("CLIENT PARALLEL 1-WAY FULL SCAN OVER " + physicalTableName + "\n"
-      + "    SERVER FILTER BY V3 = 1", QueryUtil.getExplainPlan(rs));
-    rs.close();
+    assertPlan(conn, "SELECT * FROM " + tableName + " WHERE v3 = 1").iteratorType("PARALLEL 1-WAY")
+      .scanType("FULL SCAN").table(physicalTableName.toString())
+      .serverWhereFilter("SERVER FILTER BY V3 = 1");
 
     // 8. Filtering along a prefix of the index key can use the index
-    rs =
-      conn.createStatement().executeQuery("EXPLAIN SELECT * FROM " + tableName + " WHERE v2 = 2");
-    assertEquals("CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + fullIndexName + "("
-      + indexPhysicalTableName + ") [1,2]\n" + "    SERVER MERGE [0.V1]\n"
-      + "    SERVER FILTER BY FIRST KEY ONLY\n" + "CLIENT MERGE SORT",
-      QueryUtil.getExplainPlan(rs));
-    rs.close();
+    assertPlan(conn, "SELECT * FROM " + tableName + " WHERE v2 = 2").iteratorType("PARALLEL 1-WAY")
+      .scanType("RANGE SCAN").table(fullIndexName + "(" + indexPhysicalTableName + ")")
+      .keyRanges(" [1,2]").serverMergeColumns("[0.V1]")
+      .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").clientSortAlgo("CLIENT MERGE SORT");
 
     // 9. Make sure a gap in the index columns still uses the index as long as a prefix is specified
-    rs = conn.createStatement()
-      .executeQuery("EXPLAIN SELECT * FROM " + tableName + " WHERE v2 = 2 AND v4 = 4");
-    assertEquals(
-      "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + fullIndexName + "(" + indexPhysicalTableName
-        + ") [1,2]\n" + "    SERVER MERGE [0.V1]\n"
-        + "    SERVER FILTER BY FIRST KEY ONLY AND TO_INTEGER(\"V4\") = 4\n" + "CLIENT MERGE SORT",
-      QueryUtil.getExplainPlan(rs));
-    rs.close();
+    assertPlan(conn, "SELECT * FROM " + tableName + " WHERE v2 = 2 AND v4 = 4")
+      .iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+      .table(fullIndexName + "(" + indexPhysicalTableName + ")").keyRanges(" [1,2]")
+      .serverMergeColumns("[0.V1]")
+      .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY AND TO_INTEGER(\"V4\") = 4")
+      .clientSortAlgo("CLIENT MERGE SORT");
 
     // 10. Use index even when also filtering on non-indexed column
-    rs = conn.createStatement()
-      .executeQuery("EXPLAIN SELECT * FROM " + tableName + " WHERE v2 = 2 AND v1 = 3");
-    assertEquals(
-      "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + fullIndexName + "(" + indexPhysicalTableName
-        + ") [1,2]\n" + "    SERVER MERGE [0.V1]\n"
-        + "    SERVER FILTER BY FIRST KEY ONLY AND \"V1\" = 3.0\n" + "CLIENT MERGE SORT",
-      QueryUtil.getExplainPlan(rs));
-    rs.close();
+    assertPlan(conn, "SELECT * FROM " + tableName + " WHERE v2 = 2 AND v1 = 3")
+      .iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+      .table(fullIndexName + "(" + indexPhysicalTableName + ")").keyRanges(" [1,2]")
+      .serverMergeColumns("[0.V1]")
+      .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY AND \"V1\" = 3.0")
+      .clientSortAlgo("CLIENT MERGE SORT");
 
     // 11. Another case of not using a prefix of the index key
-    rs = conn.createStatement()
-      .executeQuery("EXPLAIN SELECT * FROM " + tableName + " WHERE v1 = 3 AND v3 = 1 AND v4 = 1");
-    assertEquals("CLIENT PARALLEL 1-WAY FULL SCAN OVER " + physicalTableName + "\n"
-      + "    SERVER FILTER BY (V1 = 3.0 AND V3 = 1 AND V4 = 1)", QueryUtil.getExplainPlan(rs));
-    rs.close();
+    assertPlan(conn, "SELECT * FROM " + tableName + " WHERE v1 = 3 AND v3 = 1 AND v4 = 1")
+      .iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN").table(physicalTableName.toString())
+      .serverWhereFilter("SERVER FILTER BY (V1 = 3.0 AND V3 = 1 AND V4 = 1)");
   }
 
   @Test
@@ -829,19 +778,12 @@ public class LocalIndexIT extends BaseLocalIndexIT {
         .execute("CREATE LOCAL INDEX " + indexName + " ON " + tableName + "(v1)");
 
       String query = "SELECT * FROM " + tableName + " ORDER BY V1";
-      ResultSet rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-
-      Admin admin =
-        driver.getConnectionQueryServices(getUrl(), TestUtil.TEST_PROPERTIES).getAdmin();
-      int numRegions = admin.getRegions(physicalTableName).size();
-
-      assertEquals(
-        "CLIENT PARALLEL " + numRegions + "-WAY RANGE SCAN OVER " + fullIndexName + "("
-          + indexPhysicalTableName + ") [1]\n" + "    SERVER MERGE [0.K3]\n"
-          + "    SERVER FILTER BY FIRST KEY ONLY\n" + "CLIENT MERGE SORT",
-        QueryUtil.getExplainPlan(rs));
+      assertPlan(conn1, query).scanType("RANGE SCAN")
+        .table(fullIndexName + "(" + indexPhysicalTableName + ")").keyRanges(" [1]")
+        .serverMergeColumns("[0.K3]").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .clientSortAlgo("CLIENT MERGE SORT");
 
-      rs = conn1.createStatement().executeQuery(query);
+      ResultSet rs = conn1.createStatement().executeQuery(query);
       String v = "";
       int i = 0;
       while (rs.next()) {
@@ -855,12 +797,10 @@ public class LocalIndexIT extends BaseLocalIndexIT {
       rs.close();
 
       query = "SELECT * FROM " + tableName + " ORDER BY V1 DESC NULLS LAST";
-      rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-      assertEquals(
-        "CLIENT PARALLEL " + numRegions + "-WAY REVERSE RANGE SCAN OVER " + fullIndexName + "("
-          + indexPhysicalTableName + ") [1]\n" + "    SERVER MERGE [0.K3]\n"
-          + "    SERVER FILTER BY FIRST KEY ONLY\n" + "CLIENT MERGE SORT",
-        QueryUtil.getExplainPlan(rs));
+      assertPlan(conn1, query).scanType("RANGE SCAN").clientSortedBy("REVERSE")
+        .table(fullIndexName + "(" + indexPhysicalTableName + ")").keyRanges(" [1]")
+        .serverMergeColumns("[0.K3]").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .clientSortAlgo("CLIENT MERGE SORT");
 
       rs = conn1.createStatement().executeQuery(query);
       v = "zz";
@@ -898,17 +838,11 @@ public class LocalIndexIT extends BaseLocalIndexIT {
         .execute("CREATE LOCAL INDEX " + indexName + " ON " + tableName + "(v1)");
 
       String query = "SELECT V1 FROM " + tableName + " ORDER BY V1 DESC NULLS LAST";
-      ResultSet rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-
-      Admin admin =
-        driver.getConnectionQueryServices(getUrl(), TestUtil.TEST_PROPERTIES).getAdmin();
-      int numRegions = admin.getRegions(physicalTableName).size();
+      assertPlan(conn1, query).scanType("RANGE SCAN").clientSortedBy("REVERSE")
+        .table(fullIndexName + "(" + indexPhysicalTableName + ")").keyRanges(" [1]")
+        .serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY").clientSortAlgo("CLIENT MERGE SORT");
 
-      assertEquals("CLIENT PARALLEL " + numRegions + "-WAY REVERSE RANGE SCAN OVER " + fullIndexName
-        + "(" + indexPhysicalTableName + ") [1]\n" + "    SERVER FILTER BY FIRST KEY ONLY\n"
-        + "CLIENT MERGE SORT", QueryUtil.getExplainPlan(rs));
-
-      rs = conn1.createStatement().executeQuery(query);
+      ResultSet rs = conn1.createStatement().executeQuery(query);
       String v = "zz";
       int i = 0;
       while (rs.next()) {
@@ -948,18 +882,11 @@ public class LocalIndexIT extends BaseLocalIndexIT {
       ResultSet rs = conn1.createStatement().executeQuery("SELECT COUNT(*) FROM " + indexTableName);
       assertTrue(rs.next());
 
-      Admin admin =
-        driver.getConnectionQueryServices(getUrl(), TestUtil.TEST_PROPERTIES).getAdmin();
-      int numRegions = admin.getRegions(physicalTableName).size();
-
       String query = "SELECT t_id, k1, k2, k3, V1 FROM " + tableName + " where v1='a'";
-      rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-
-      assertEquals(
-        "CLIENT PARALLEL " + numRegions + "-WAY RANGE SCAN OVER " + fullIndexName + "("
-          + indexPhysicalTableName + ") [1,'a']\n" + "    SERVER MERGE [0.K3]\n"
-          + "    SERVER FILTER BY FIRST KEY ONLY\n" + "CLIENT MERGE SORT",
-        QueryUtil.getExplainPlan(rs));
+      assertPlan(conn1, query).scanType("RANGE SCAN")
+        .table(fullIndexName + "(" + indexPhysicalTableName + ")").keyRanges(" [1,'a']")
+        .serverMergeColumns("[0.K3]").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .clientSortAlgo("CLIENT MERGE SORT");
 
       rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -975,13 +902,10 @@ public class LocalIndexIT extends BaseLocalIndexIT {
       assertFalse(rs.next());
 
       query = "SELECT t_id, k1, k2, k3, V1 from " + tableName + "  where v1<='z' order by V1,t_id";
-      rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-
-      assertEquals(
-        "CLIENT PARALLEL " + numRegions + "-WAY RANGE SCAN OVER " + fullIndexName + "("
-          + indexPhysicalTableName + ") [1,*] - [1,'z']\n" + "    SERVER MERGE [0.K3]\n"
-          + "    SERVER FILTER BY FIRST KEY ONLY\n" + "CLIENT MERGE SORT",
-        QueryUtil.getExplainPlan(rs));
+      assertPlan(conn1, query).scanType("RANGE SCAN")
+        .table(fullIndexName + "(" + indexPhysicalTableName + ")").keyRanges(" [1,*] - [1,'z']")
+        .serverMergeColumns("[0.K3]").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .clientSortAlgo("CLIENT MERGE SORT");
 
       rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -1010,13 +934,11 @@ public class LocalIndexIT extends BaseLocalIndexIT {
       assertEquals("z", rs.getString("V1"));
 
       query = "SELECT t_id, V1, k3 from " + tableName + "  where v1 <='z' group by v1,t_id, k3";
-      rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-
-      assertEquals("CLIENT PARALLEL " + numRegions + "-WAY RANGE SCAN OVER " + fullIndexName + "("
-        + indexPhysicalTableName + ") [1,*] - [1,'z']\n" + "    SERVER MERGE [0.K3]\n"
-        + "    SERVER FILTER BY FIRST KEY ONLY\n"
-        + "    SERVER AGGREGATE INTO DISTINCT ROWS BY [\"V1\", \"T_ID\", \"K3\"]\nCLIENT MERGE SORT",
-        QueryUtil.getExplainPlan(rs));
+      assertPlan(conn1, query).scanType("RANGE SCAN")
+        .table(fullIndexName + "(" + indexPhysicalTableName + ")").keyRanges(" [1,*] - [1,'z']")
+        .serverMergeColumns("[0.K3]").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .serverAggregate("SERVER AGGREGATE INTO DISTINCT ROWS BY [\"V1\", \"T_ID\", \"K3\"]")
+        .clientSortAlgo("CLIENT MERGE SORT");
 
       rs = conn1.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -1038,13 +960,11 @@ public class LocalIndexIT extends BaseLocalIndexIT {
 
       query = "SELECT v1,sum(k3) from " + tableName + " where v1 <='z'  group by v1 order by v1";
 
-      rs = conn1.createStatement().executeQuery("EXPLAIN " + query);
-      assertEquals(
-        "CLIENT PARALLEL " + numRegions + "-WAY RANGE SCAN OVER " + fullIndexName + "("
-          + indexPhysicalTableName + ") [1,*] - [1,'z']\n" + "    SERVER MERGE [0.K3]\n"
-          + "    SERVER FILTER BY FIRST KEY ONLY\n"
-          + "    SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [\"V1\"]\nCLIENT MERGE SORT",
-        QueryUtil.getExplainPlan(rs));
+      assertPlan(conn1, query).scanType("RANGE SCAN")
+        .table(fullIndexName + "(" + indexPhysicalTableName + ")").keyRanges(" [1,*] - [1,'z']")
+        .serverMergeColumns("[0.K3]").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY")
+        .serverAggregate("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [\"V1\"]")
+        .clientSortAlgo("CLIENT MERGE SORT");
 
       PhoenixStatement stmt = conn1.createStatement().unwrap(PhoenixStatement.class);
       rs = stmt.executeQuery(query);
@@ -1086,10 +1006,10 @@ public class LocalIndexIT extends BaseLocalIndexIT {
     conn1.createStatement()
       .execute("CREATE INDEX " + indexName + "2" + " ON " + tableName + "(v1)");
     String query = "SELECT t_id, k1, k2,V1 FROM " + tableName + " where v1='a'";
-    ResultSet rs1 = conn1.createStatement().executeQuery("EXPLAIN " + query);
-    assertEquals("CLIENT PARALLEL 1-WAY RANGE SCAN OVER "
-      + SchemaUtil.getPhysicalTableName(Bytes.toBytes(indexTableName), isNamespaceMapped) + "2"
-      + " ['a']\n" + "    SERVER FILTER BY FIRST KEY ONLY", QueryUtil.getExplainPlan(rs1));
+    assertPlan(conn1, query).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+      .table(
+        SchemaUtil.getPhysicalTableName(Bytes.toBytes(indexTableName), isNamespaceMapped) + "2")
+      .keyRanges(" ['a']").serverWhereFilter("SERVER FILTER BY FIRST KEY ONLY");
     conn1.close();
   }
 
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/MutableIndexFailureIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/MutableIndexFailureIT.java
index 80eca6a4c9..dfc36536e0 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/MutableIndexFailureIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/MutableIndexFailureIT.java
@@ -18,6 +18,7 @@
 package org.apache.phoenix.end2end.index;
 
 import static org.apache.hadoop.hbase.coprocessor.CoprocessorHost.REGIONSERVER_COPROCESSOR_CONF_KEY;
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -49,8 +50,6 @@ import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
 import org.apache.hadoop.hbase.coprocessor.SimpleRegionObserver;
 import org.apache.hadoop.hbase.regionserver.MiniBatchOperationInProgress;
 import org.apache.hadoop.hbase.util.Bytes;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.coprocessor.MetaDataRegionObserver;
 import org.apache.phoenix.coprocessor.MetaDataRegionObserver.BuildIndexScheduleTask;
 import org.apache.phoenix.end2end.NeedsOwnMiniClusterTest;
@@ -60,7 +59,6 @@ import org.apache.phoenix.hbase.index.write.IndexWriterUtils;
 import org.apache.phoenix.index.PhoenixIndexFailurePolicy;
 import org.apache.phoenix.jdbc.PhoenixConnection;
 import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData;
-import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
 import org.apache.phoenix.query.BaseTest;
 import org.apache.phoenix.query.QueryConstants;
 import org.apache.phoenix.query.QueryServices;
@@ -302,15 +300,10 @@ public class MutableIndexFailureIT extends BaseTest {
       addRowToTable(conn, fullTableName);
 
       query = "SELECT /*+ NO_INDEX */ k,v1 FROM " + fullTableName;
-      ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
-        .optimizeQuery().getExplainPlan();
-      ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
-      assertEquals("PARALLEL 2-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-      assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-      assertEquals(
-        SchemaUtil.getPhysicalTableName(fullTableName.getBytes(), isNamespaceMapped).toString(),
-        explainPlanAttributes.getTableName());
-      assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+      assertPlan(conn, query).iteratorType("PARALLEL 2-WAY").scanType("FULL SCAN")
+        .table(
+          SchemaUtil.getPhysicalTableName(fullTableName.getBytes(), isNamespaceMapped).toString())
+        .clientSortAlgo("CLIENT MERGE SORT");
 
       rs = conn.createStatement().executeQuery(query);
       assertTrue(rs.next());
@@ -352,15 +345,10 @@ public class MutableIndexFailureIT extends BaseTest {
         updateTableAgain(conn, false);
         // Verify previous writes succeeded to data table
         query = "SELECT /*+ NO_INDEX */ k,v1 FROM " + fullTableName;
-        plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
-          .getExplainPlan();
-        explainPlanAttributes = plan.getPlanStepsAsAttributes();
-        assertEquals("PARALLEL 2-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
-        assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
-        assertEquals(
-          SchemaUtil.getPhysicalTableName(fullTableName.getBytes(), isNamespaceMapped).toString(),
-          explainPlanAttributes.getTableName());
-        assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
+        assertPlan(conn, query).iteratorType("PARALLEL 2-WAY").scanType("FULL SCAN")
+          .table(
+            SchemaUtil.getPhysicalTableName(fullTableName.getBytes(), isNamespaceMapped).toString())
+          .clientSortAlgo("CLIENT MERGE SORT");
 
         rs = conn.createStatement().executeQuery(query);
         assertTrue(rs.next());
@@ -457,17 +445,14 @@ public class MutableIndexFailureIT extends BaseTest {
     boolean wasFailWrite = FailingRegionObserver.FAIL_WRITE;
     boolean wasToggleFailWriteForRetry = FailingRegionObserver.TOGGLE_FAIL_WRITE_FOR_RETRY;
     try {
-      Callable callable = new Callable() {
-
+      Callable<Boolean> callable = new Callable<Boolean>() {
         @Override
         public Boolean call() {
           Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
           props.put(QueryServices.IS_NAMESPACE_MAPPING_ENABLED, String.valueOf(isNamespaceMapped));
           try (Connection conn = driver.connect(url, props)) {
             // In case of disable index on failure policy, INDEX will be in PENDING_DISABLE on first
-            // retry
-            // but will
-            // become active if retry is successfull
+            // retry but will become active if retry is successfull
             PreparedStatement stmt =
               conn.prepareStatement("UPSERT INTO " + tableName + " VALUES(?,?,?)");
             stmt.setString(1, "b");
@@ -510,18 +495,15 @@ public class MutableIndexFailureIT extends BaseTest {
     String query = "SELECT /*+ INDEX(" + fullTableName + " "
       + SchemaUtil.getTableNameFromFullName(fullIndexName) + ")  */ k,v1 FROM " + fullTableName;
     ResultSet rs = conn.createStatement().executeQuery(query);
-    String expectedPlan =
-      " OVER "
-        + (localIndex
-          ? fullIndexName + "("
-            + Bytes.toString(SchemaUtil
-              .getPhysicalTableName(fullTableName.getBytes(), isNamespaceMapped).getName())
-            + ")"
-          : SchemaUtil.getPhysicalTableName(fullIndexName.getBytes(), isNamespaceMapped)
-            .getNameAsString());
-    String explainPlan =
-      QueryUtil.getExplainPlan(conn.createStatement().executeQuery("EXPLAIN " + query));
-    assertTrue(explainPlan, explainPlan.contains(expectedPlan));
+    String expectedTable = localIndex
+      ? fullIndexName + "("
+        + Bytes.toString(
+          SchemaUtil.getPhysicalTableName(fullTableName.getBytes(), isNamespaceMapped).getName())
+        + ")"
+      : SchemaUtil.getPhysicalTableName(fullIndexName.getBytes(), isNamespaceMapped)
+        .getNameAsString();
+    assertPlan(conn, query).scanType(localIndex ? "RANGE SCAN" : "FULL SCAN")
+      .tableContains(expectedTable);
     if (transactional) { // failed commit does not get retried
       assertTrue(rs.next());
       assertEquals("a", rs.getString(1));
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/MutableIndexIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/MutableIndexIT.java
index 116cc574db..450eafbce8 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/MutableIndexIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/MutableIndexIT.java
@@ -17,6 +17,7 @@
  */
 package org.apache.phoenix.end2end.index;
 
+import static org.apache.phoenix.query.explain.ExplainPlanTestUtil.assertPlan;
 import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -44,7 +45,6 @@ import org.apache.phoenix.schema.PTableKey;
 import org.apache.phoenix.util.IndexScrutiny;
 import org.apache.phoenix.util.PhoenixRuntime;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.TestUtil;
 import org.junit.Test;
@@ -115,16 +115,16 @@ public class MutableIndexIT extends ParallelStatsDisabledIT {
           + fullTableName + " (char_col1 ASC, int_col1 ASC) INCLUDE (long_col1, long_col2)");
 
       String query = "SELECT char_col1, int_col1, long_col2 from " + fullTableName;
-      ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + query);
       if (localIndex) {
-        assertEquals("CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + fullIndexName + "(" + fullTableName
-          + ") [1]\nCLIENT MERGE SORT", QueryUtil.getExplainPlan(rs));
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+          .table(fullIndexName + "(" + fullTableName + ")").keyRanges(" [1]")
+          .clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("CLIENT PARALLEL 1-WAY FULL SCAN OVER " + fullIndexName,
-          QueryUtil.getExplainPlan(rs));
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+          .table(fullIndexName);
       }
 
-      rs = conn.createStatement().executeQuery(query);
+      ResultSet rs = conn.createStatement().executeQuery(query);
       assertTrue(rs.next());
       assertEquals("chara", rs.getString(1));
       assertEquals(2, rs.getInt(2));
@@ -185,11 +185,11 @@ public class MutableIndexIT extends ParallelStatsDisabledIT {
       assertFalse(rs.next());
       if (localIndex) {
         query = "SELECT b.* from " + fullTableName + " where int_col1 = 4 AND char_col1 = 'chara'";
-        rs = conn.createStatement().executeQuery("EXPLAIN " + query);
-        assertEquals("CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + fullIndexName + "(" + fullTableName
-          + ") [1,'chara',4]\n"
-          + "    SERVER MERGE [B.VARCHAR_COL2, B.CHAR_COL2, B.INT_COL2, B.DECIMAL_COL2, B.DATE_COL]\n"
-          + "CLIENT MERGE SORT", QueryUtil.getExplainPlan(rs));
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+          .table(fullIndexName + "(" + fullTableName + ")").keyRanges(" [1,'chara',4]")
+          .serverMergeColumns(
+            "[B.VARCHAR_COL2, B.CHAR_COL2, B.INT_COL2, B.DECIMAL_COL2, B.DATE_COL]")
+          .clientSortAlgo("CLIENT MERGE SORT");
         rs = conn.createStatement().executeQuery(query);
         assertTrue(rs.next());
         assertEquals("varchar_b", rs.getString(1));
@@ -286,13 +286,13 @@ public class MutableIndexIT extends ParallelStatsDisabledIT {
       assertFalse(rs.next());
 
       query = "SELECT * FROM " + fullTableName;
-      rs = conn.createStatement().executeQuery("EXPLAIN " + query);
       if (localIndex) {
-        assertEquals("CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + fullIndexName + "(" + fullTableName
-          + ") [1]\nCLIENT MERGE SORT", QueryUtil.getExplainPlan(rs));
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+          .table(fullIndexName + "(" + fullTableName + ")").keyRanges(" [1]")
+          .clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("CLIENT PARALLEL 1-WAY FULL SCAN OVER " + fullIndexName,
-          QueryUtil.getExplainPlan(rs));
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+          .table(fullIndexName);
       }
 
       rs = conn.createStatement().executeQuery(query);
@@ -309,13 +309,13 @@ public class MutableIndexIT extends ParallelStatsDisabledIT {
       conn.commit();
 
       query = "SELECT * FROM " + fullTableName;
-      rs = conn.createStatement().executeQuery("EXPLAIN " + query);
       if (localIndex) {
-        assertEquals("CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + fullIndexName + "(" + fullTableName
-          + ") [1]\nCLIENT MERGE SORT", QueryUtil.getExplainPlan(rs));
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+          .table(fullIndexName + "(" + fullTableName + ")").keyRanges(" [1]")
+          .clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("CLIENT PARALLEL 1-WAY FULL SCAN OVER " + fullIndexName,
-          QueryUtil.getExplainPlan(rs));
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+          .table(fullIndexName);
       }
 
       rs = conn.createStatement().executeQuery(query);
@@ -332,13 +332,13 @@ public class MutableIndexIT extends ParallelStatsDisabledIT {
       conn.commit();
 
       query = "SELECT * FROM " + fullTableName;
-      rs = conn.createStatement().executeQuery("EXPLAIN " + query);
       if (localIndex) {
-        assertEquals("CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + fullIndexName + "(" + fullTableName
-          + ") [1]\nCLIENT MERGE SORT", QueryUtil.getExplainPlan(rs));
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+          .table(fullIndexName + "(" + fullTableName + ")").keyRanges(" [1]")
+          .clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals("CLIENT PARALLEL 1-WAY FULL SCAN OVER " + fullIndexName,
-          QueryUtil.getExplainPlan(rs));
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+          .table(fullIndexName);
       }
 
       rs = conn.createStatement().executeQuery(query);
@@ -405,16 +405,16 @@ public class MutableIndexIT extends ParallelStatsDisabledIT {
       assertFalse(rs.next());
 
       query = "SELECT * FROM " + fullTableName;
-      rs = conn.createStatement().executeQuery("EXPLAIN " + query);
       if (localIndex) {
-        assertEquals("CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + fullIndexName + "(" + fullTableName
-          + ") [1]\n" + "    SERVER FILTER BY " + (columnEncoded ? "FIRST KEY" : "EMPTY COLUMN")
-          + " ONLY\n" + "CLIENT MERGE SORT", QueryUtil.getExplainPlan(rs));
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+          .table(fullIndexName + "(" + fullTableName + ")").keyRanges(" [1]")
+          .serverWhereFilter(
+            "SERVER FILTER BY " + (columnEncoded ? "FIRST KEY" : "EMPTY COLUMN") + " ONLY")
+          .clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals(
-          "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + fullIndexName + "\n" + "    SERVER FILTER BY "
-            + (columnEncoded ? "FIRST KEY" : "EMPTY COLUMN") + " ONLY",
-          QueryUtil.getExplainPlan(rs));
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+          .table(fullIndexName).serverWhereFilter(
+            "SERVER FILTER BY " + (columnEncoded ? "FIRST KEY" : "EMPTY COLUMN") + " ONLY");
       }
       // make sure the data table looks like what we expect
       rs = conn.createStatement().executeQuery(query);
@@ -534,16 +534,16 @@ public class MutableIndexIT extends ParallelStatsDisabledIT {
       assertFalse(rs.next());
 
       query = "SELECT * FROM " + fullTableName;
-      rs = conn.createStatement().executeQuery("EXPLAIN " + query);
       if (localIndex) {
-        assertEquals("CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + fullIndexName + "(" + fullTableName
-          + ") [1]\n" + "    SERVER FILTER BY " + (columnEncoded ? "FIRST KEY" : "EMPTY COLUMN")
-          + " ONLY\n" + "CLIENT MERGE SORT", QueryUtil.getExplainPlan(rs));
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("RANGE SCAN")
+          .table(fullIndexName + "(" + fullTableName + ")").keyRanges(" [1]")
+          .serverWhereFilter(
+            "SERVER FILTER BY " + (columnEncoded ? "FIRST KEY" : "EMPTY COLUMN") + " ONLY")
+          .clientSortAlgo("CLIENT MERGE SORT");
       } else {
-        assertEquals(
-          "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + fullIndexName + "\n" + "    SERVER FILTER BY "
-            + (columnEncoded ? "FIRST KEY" : "EMPTY COLUMN") + " ONLY",
-          QueryUtil.getExplainPlan(rs));
+        assertPlan(conn, query).iteratorType("PARALLEL 1-WAY").scanType("FULL SCAN")
+          .table(fullIndexName).serverWhereFilter(
+            "SERVER FILTER BY " + (columnEncoded ? "FIRST KEY" : "EMPTY COLUMN") + " ONLY");
       }
 
       // check that the data table matches as expected
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/PartialIndexIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/PartialIndexIT.java
index aef493217b..efa8528f0d 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/PartialIndexIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/PartialIndexIT.java
@@ -47,8 +47,6 @@ import java.util.Properties;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.hadoop.hbase.util.Bytes;
 import org.apache.hadoop.mapreduce.CounterGroup;
-import org.apache.phoenix.compile.ExplainPlan;
-import org.apache.phoenix.compile.ExplainPlanAttributes;
 import org.apache.phoenix.end2end.IndexToolIT;
 import org.apache.phoenix.end2end.NeedsOwnMiniClusterTest;
 import org.apache.phoenix.exception.PhoenixParserException;
@@ -59,12 +57,12 @@ import org.apache.phoenix.jdbc.PhoenixStatement;
 import org.apache.phoenix.mapreduce.index.IndexTool;
 import org.apache.phoenix.query.BaseTest;
 import org.apache.phoenix.query.QueryServices;
+import org.apache.phoenix.query.explain.ExplainPlanTestUtil;
 import org.apache.phoenix.schema.ColumnNotFoundException;
 import org.apache.phoenix.schema.PTable;
 import org.apache.phoenix.util.EnvironmentEdgeManager;
 import org.apache.phoenix.util.PhoenixRuntime;
 import org.apache.phoenix.util.PropertiesUtil;
-import org.apache.phoenix.util.QueryUtil;
 import org.apache.phoenix.util.ReadOnlyProps;
 import org.junit.After;
 import org.junit.Assert;
@@ -110,7 +108,7 @@ public class PartialIndexIT extends BaseTest {
       { false, true, true } });
   }
 
-  public static void assertPlan(PhoenixResultSet rs, String schemaName, String tableName) {
+  public static void assertCurrentTable(PhoenixResultSet rs, String schemaName, String tableName) {
     PTable table = rs.getContext().getCurrentTable().getTable();
     assertTrue(table.getSchemaName().getString().equals(schemaName)
       && table.getTableName().getString().equals(tableName));
@@ -239,7 +237,7 @@ public class PartialIndexIT extends BaseTest {
       String selectSql = "SELECT  D from " + dataTableName + " WHERE A > 60";
       ResultSet rs = conn.createStatement().executeQuery(selectSql);
       // Verify that the index table is used
-      assertPlan((PhoenixResultSet) rs, "", indexTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", indexTableName);
       assertTrue(rs.next());
       assertEquals("b", rs.getString(1));
       assertFalse(rs.next());
@@ -251,7 +249,7 @@ public class PartialIndexIT extends BaseTest {
       selectSql = "SELECT  D from " + dataTableName + " WHERE A = 50";
       rs = conn.createStatement().executeQuery(selectSql);
       // Verify that the index table is not used
-      assertPlan((PhoenixResultSet) rs, "", dataTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", dataTableName);
       // explain plan verify to check if partial index is not used
       rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql);
       assertTrue(rs.next());
@@ -289,7 +287,7 @@ public class PartialIndexIT extends BaseTest {
       // Retrieve update row from the data table and verify that the index table is not used
       selectSql = "SELECT  ID from " + dataTableName + " WHERE A = 0";
       rs = conn.createStatement().executeQuery(selectSql);
-      assertPlan((PhoenixResultSet) rs, "", dataTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", dataTableName);
       assertTrue(rs.next());
       assertEquals("id2", rs.getString(1));
       // explain plan verify to check if partial index is not used
@@ -336,7 +334,7 @@ public class PartialIndexIT extends BaseTest {
 
       ResultSet rs = conn.createStatement().executeQuery(selectSql);
       // Verify that the index table is used
-      assertPlan((PhoenixResultSet) rs, "", indexTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", indexTableName);
       assertTrue(rs.next());
       assertEquals("a", rs.getString(1));
       assertFalse(rs.next());
@@ -348,7 +346,7 @@ public class PartialIndexIT extends BaseTest {
       selectSql = "SELECT  D from " + dataTableName + " WHERE A > 100";
       rs = conn.createStatement().executeQuery(selectSql);
       // Verify that the index table is not used
-      assertPlan((PhoenixResultSet) rs, "", dataTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", dataTableName);
       // explain plan verify to check if partial index is not used
       rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql);
       assertTrue(rs.next());
@@ -424,7 +422,7 @@ public class PartialIndexIT extends BaseTest {
 
       ResultSet rs = conn.createStatement().executeQuery(selectSql);
       // Verify that the index table is used
-      assertPlan((PhoenixResultSet) rs, "", indexTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", indexTableName);
       assertTrue(rs.next());
       assertEquals(70, rs.getInt(1));
       assertEquals("a", rs.getString(2));
@@ -457,7 +455,7 @@ public class PartialIndexIT extends BaseTest {
 
       rs = conn.createStatement().executeQuery("SELECT Count(*) from " + dataTableName);
       // Verify that the index table is not used
-      assertPlan((PhoenixResultSet) rs, "", dataTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", dataTableName);
       assertTrue(rs.next());
       assertEquals(5, rs.getInt(1));
       // explain plan verify to check if partial index is not used
@@ -515,7 +513,7 @@ public class PartialIndexIT extends BaseTest {
         "SELECT D from " + dataTableName + " WHERE B is not NULL AND D like '%cde_'";
       ResultSet rs = conn.createStatement().executeQuery(selectSql);
       // Verify that the index table is used
-      assertPlan((PhoenixResultSet) rs, "", indexTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", indexTableName);
       assertTrue(rs.next());
       assertEquals("abcdef", rs.getString(1));
       assertFalse(rs.next());
@@ -545,7 +543,7 @@ public class PartialIndexIT extends BaseTest {
       selectSql = "SELECT Count(*) from " + dataTableName;
       rs = conn.createStatement().executeQuery(selectSql);
       // Verify that the index table is not used
-      assertPlan((PhoenixResultSet) rs, "", dataTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", dataTableName);
       assertTrue(rs.next());
       assertEquals(5, rs.getInt(1));
       // explain plan verify to check if partial index is not used
@@ -605,7 +603,7 @@ public class PartialIndexIT extends BaseTest {
           + "', 'yyyy-MM-dd HH:mm:ss.SSS', '" + timeZoneID + "')";
       ResultSet rs = conn.createStatement().executeQuery(selectSql);
       // Verify that the index table is used
-      assertPlan((PhoenixResultSet) rs, "", indexTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", indexTableName);
       assertTrue(rs.next());
       assertEquals(0, rs.getInt(1));
       assertTrue(rs.next());
@@ -624,7 +622,7 @@ public class PartialIndexIT extends BaseTest {
 
       rs = conn.createStatement().executeQuery("SELECT Count(*) from " + dataTableName);
       // Verify that the index table is not used
-      assertPlan((PhoenixResultSet) rs, "", dataTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", dataTableName);
       assertTrue(rs.next());
       assertEquals(4, rs.getInt(1));
       // explain plan verify to check if partial index is not used
@@ -645,7 +643,7 @@ public class PartialIndexIT extends BaseTest {
 
       rs = conn.createStatement().executeQuery(selectSql);
       // Verify that the index table is used
-      assertPlan((PhoenixResultSet) rs, "", indexTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", indexTableName);
       assertTrue(rs.next());
       assertEquals(0, rs.getInt(1));
       assertFalse(rs.next());
@@ -723,7 +721,7 @@ public class PartialIndexIT extends BaseTest {
         // Verify that query uses the tenant view index
         ResultSet rs = tenantConn.createStatement()
           .executeQuery("SELECT KV1 FROM  " + tenantViewName + " WHERE PK3 = 5");
-        assertPlan((PhoenixResultSet) rs, "", tenantViewIndexName);
+        assertCurrentTable((PhoenixResultSet) rs, "", tenantViewIndexName);
         assertTrue(rs.next());
         assertEquals("KV10", rs.getString(1));
         assertFalse(rs.next());
@@ -732,7 +730,7 @@ public class PartialIndexIT extends BaseTest {
         // where clause does not contain the query where clause
         rs = tenantConn.createStatement()
           .executeQuery("SELECT KV1 FROM  " + tenantViewName + " WHERE PK3 = 4");
-        assertPlan((PhoenixResultSet) rs, "", tenantViewName);
+        assertCurrentTable((PhoenixResultSet) rs, "", tenantViewName);
         assertTrue(rs.next());
         assertEquals("KV8", rs.getString(1));
         assertFalse(rs.next());
@@ -740,7 +738,7 @@ public class PartialIndexIT extends BaseTest {
         // Verify that the tenant view index has only one row
         rs =
           tenantConn.createStatement().executeQuery("SELECT Count(*) FROM  " + tenantViewIndexName);
-        assertPlan((PhoenixResultSet) rs, "", tenantViewIndexName);
+        assertCurrentTable((PhoenixResultSet) rs, "", tenantViewIndexName);
         assertTrue(rs.next());
         assertEquals(1, rs.getInt(1));
       }
@@ -751,7 +749,7 @@ public class PartialIndexIT extends BaseTest {
         // Verify that the query uses the global view index
         ResultSet rs = tenantConn.createStatement()
           .executeQuery("SELECT KV1 FROM  " + tenantViewName + " WHERE PK3 = 1 AND KV3 = 'KV3'");
-        assertPlan((PhoenixResultSet) rs, "", tenantViewName + "#" + globalViewIndexName);
+        assertCurrentTable((PhoenixResultSet) rs, "", tenantViewName + "#" + globalViewIndexName);
         assertTrue(rs.next());
         assertEquals("KV1", rs.getString(1));
         assertFalse(rs.next());
@@ -760,14 +758,14 @@ public class PartialIndexIT extends BaseTest {
       // Verify that the query uses the global view index
       ResultSet rs = conn.createStatement()
         .executeQuery("SELECT KV1 FROM  " + globalViewName + " WHERE PK3 = 1 AND KV3 = 'KV3'");
-      assertPlan((PhoenixResultSet) rs, "", globalViewIndexName);
+      assertCurrentTable((PhoenixResultSet) rs, "", globalViewIndexName);
       assertTrue(rs.next());
       assertEquals("KV1", rs.getString(1));
       assertFalse(rs.next());
 
       // Verify that the global view index has five rows
       rs = conn.createStatement().executeQuery("SELECT Count(*) FROM  " + globalViewIndexName);
-      assertPlan((PhoenixResultSet) rs, "", globalViewIndexName);
+      assertCurrentTable((PhoenixResultSet) rs, "", globalViewIndexName);
       assertTrue(rs.next());
       assertEquals(5, rs.getInt(1));
     }
@@ -801,7 +799,7 @@ public class PartialIndexIT extends BaseTest {
       String selectSql = "SELECT  D from " + dataTableName + " WHERE A > 60";
       // Verify that the partial index table is used
       ResultSet rs = conn.createStatement().executeQuery(selectSql);
-      assertPlan((PhoenixResultSet) rs, "", partialIndexTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", partialIndexTableName);
       assertTrue(rs.next());
       assertEquals("b", rs.getString(1));
       assertFalse(rs.next());
@@ -813,7 +811,7 @@ public class PartialIndexIT extends BaseTest {
       selectSql = "SELECT  D from " + dataTableName + " WHERE A < 50";
       // Verify that the full index table is used
       rs = conn.createStatement().executeQuery(selectSql);
-      assertPlan((PhoenixResultSet) rs, "", fullIndexTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", fullIndexTableName);
       assertTrue(rs.next());
       assertEquals("a", rs.getString(1));
       assertFalse(rs.next());
@@ -855,7 +853,7 @@ public class PartialIndexIT extends BaseTest {
         + " WHERE (CAST(TO_NUMBER(JSON_VALUE(jsoncol, '$.info.age')) AS INTEGER)) > 60";
       ResultSet rs = conn.createStatement().executeQuery(selectSql);
       // Verify that the index table is used
-      assertPlan((PhoenixResultSet) rs, "", indexTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", indexTableName);
       assertTrue(rs.next());
       assertEquals("b", rs.getString(1));
       assertFalse(rs.next());
@@ -864,7 +862,7 @@ public class PartialIndexIT extends BaseTest {
         + " WHERE (CAST(TO_NUMBER(JSON_VALUE(jsoncol, '$.info.age')) AS INTEGER)) = 50";
       rs = conn.createStatement().executeQuery(selectSql);
       // Verify that the index table is not used
-      assertPlan((PhoenixResultSet) rs, "", dataTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", dataTableName);
 
       // Add more rows to test the index write path
       conn.createStatement().execute("upsert into " + dataTableName
@@ -896,7 +894,7 @@ public class PartialIndexIT extends BaseTest {
       selectSql = "SELECT  ID from " + dataTableName
         + " WHERE (CAST(TO_NUMBER(JSON_VALUE(jsoncol, '$.info.age')) AS INTEGER)) = 0";
       rs = conn.createStatement().executeQuery(selectSql);
-      assertPlan((PhoenixResultSet) rs, "", dataTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", dataTableName);
       assertTrue(rs.next());
       assertEquals("id2", rs.getString(1));
 
@@ -943,7 +941,7 @@ public class PartialIndexIT extends BaseTest {
           + " WHERE A > 60 AND JSON_EXISTS(jsoncol, '$.info.address.exists')";
       ResultSet rs = conn.createStatement().executeQuery(selectSql);
       // Verify that the index table is used
-      assertPlan((PhoenixResultSet) rs, "", indexTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", indexTableName);
       assertTrue(rs.next());
       assertEquals(70, rs.getInt(1));
       assertEquals("a", rs.getString(2));
@@ -969,7 +967,7 @@ public class PartialIndexIT extends BaseTest {
 
       rs = conn.createStatement().executeQuery("SELECT Count(*) from " + dataTableName);
       // Verify that the index table is not used
-      assertPlan((PhoenixResultSet) rs, "", dataTableName);
+      assertCurrentTable((PhoenixResultSet) rs, "", dataTableName);
       assertTrue(rs.next());
       assertEquals(5, rs.getInt(1));
 
@@ -1014,26 +1012,23 @@ public class PartialIndexIT extends BaseTest {
       // Index hint provided and query plan using partial index is usable
       String selectSql = "SELECT  /*+ INDEX(" + dataTableName + " " + indexTableName + ")*/ "
         + "A from " + dataTableName + " WHERE id2 = 100 AND id1 = 'id12'";
-      ResultSet rs = stmt.executeQuery("EXPLAIN " + selectSql);
-      String actualQueryPlan = QueryUtil.getExplainPlan(rs);
-      assertTrue(actualQueryPlan.contains("POINT LOOKUP ON 1 KEY OVER " + indexTableName));
-      rs = stmt.executeQuery(selectSql);
+      ExplainPlanTestUtil.assertPlan(conn, selectSql).scanType("POINT LOOKUP ON 1 KEY")
+        .table(indexTableName);
+      ResultSet rs = stmt.executeQuery(selectSql);
       assertTrue(rs.next());
       assertEquals(2, rs.getInt(1));
       assertFalse(rs.next());
       // Index hint provided but query plan using partial index is not usable so, no data
       selectSql = "SELECT  /*+ INDEX(" + dataTableName + " " + indexTableName + ")*/ " + "A from "
         + dataTableName + " WHERE id2 = 10 AND id1 = 'id11'";
... 7262 lines suppressed ...