[ASTERIXDB-2170][SQL] Fix resolution order of implicit field access

- user model changes: yes
- storage format changes: no
- interface changes: no

Details:
- Improved name resolution rules
- Resolve field access to the nearest variable in scope
  instead of raising compile-time error
- Do not rely on type information when resolving names
- Cleanup group variable handling in GroupBy clause,
  no longer use ‘with’ map for it
- Fix ByNameToByIndexFieldAccessRule to use type environment
  of its input operator when analyzing its expression
- Fix ExternalGroupByPOperator to use input schema of its
  aggregate function when generating runtime for that function
- Fix invalid free variable computation for GroupBy clause

Change-Id: I50bc823ff53da06507a5454b30f4f500b862d4bf
Reviewed-on: https://asterix-gerrit.ics.uci.edu/2207
Integration-Tests: Jenkins <jenkins@fulliautomatix.ics.uci.edu>
Tested-by: Jenkins <jenkins@fulliautomatix.ics.uci.edu>
Reviewed-by: Dmitry Lychagin <dmitry.lychagin@couchbase.com>
diff --git a/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/base/RuleCollections.java b/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/base/RuleCollections.java
index 5146993..bd67ed4 100644
--- a/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/base/RuleCollections.java
+++ b/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/base/RuleCollections.java
@@ -70,7 +70,6 @@
 import org.apache.asterix.optimizer.rules.RemoveRedundantSelectRule;
 import org.apache.asterix.optimizer.rules.RemoveSortInFeedIngestionRule;
 import org.apache.asterix.optimizer.rules.RemoveUnusedOneToOneEquiJoinRule;
-import org.apache.asterix.optimizer.rules.ResolveVariableRule;
 import org.apache.asterix.optimizer.rules.SetAsterixPhysicalOperatorsRule;
 import org.apache.asterix.optimizer.rules.SetClosedRecordConstructorsRule;
 import org.apache.asterix.optimizer.rules.SetupCommitExtensionOpRule;
@@ -166,7 +165,6 @@
 
     public static final List<IAlgebraicRewriteRule> buildNormalizationRuleCollection(ICcApplicationContext appCtx) {
         List<IAlgebraicRewriteRule> normalization = new LinkedList<>();
-        normalization.add(new ResolveVariableRule());
         normalization.add(new CheckInsertUpsertReturningRule());
         normalization.add(new IntroduceUnnestForCollectionToSequenceRule());
         normalization.add(new EliminateSubplanRule());
diff --git a/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/ByNameToByIndexFieldAccessRule.java b/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/ByNameToByIndexFieldAccessRule.java
index b3b0ad7..1ace6fa 100644
--- a/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/ByNameToByIndexFieldAccessRule.java
+++ b/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/ByNameToByIndexFieldAccessRule.java
@@ -87,7 +87,7 @@
             return changed;
         }
         changed |= extractFirstArg(fce, op, context);
-        IVariableTypeEnvironment env = context.getOutputTypeEnvironment(op);
+        IVariableTypeEnvironment env = context.getOutputTypeEnvironment(op.getInputs().get(0).getValue());
         IAType t = (IAType) env.getType(fce.getArguments().get(0).getValue());
         changed |= rewriteFieldAccess(exprRef, fce, getActualType(t));
         return changed;
diff --git a/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/PushAggregateIntoNestedSubplanRule.java b/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/PushAggregateIntoNestedSubplanRule.java
index 2b98762..d69dd3b 100644
--- a/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/PushAggregateIntoNestedSubplanRule.java
+++ b/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/PushAggregateIntoNestedSubplanRule.java
@@ -421,47 +421,47 @@
             AggregateOperator nspAgg = (AggregateOperator) nspAggRef.getValue();
             Mutable<ILogicalOperator> nspAggChildRef = nspAgg.getInputs().get(0);
             LogicalVariable listifyVar = findListifiedVariable(nspAgg, varFromNestedAgg);
-            if (listifyVar == null) {
-                    continue;
-            }
-            OperatorManipulationUtil.substituteVarRec(aggInSubplanOp, unnestVar, listifyVar, true, context);
-            nspAgg.getVariables().addAll(aggInSubplanOp.getVariables());
-            nspAgg.getExpressions().addAll(aggInSubplanOp.getExpressions());
-            for (LogicalVariable v : aggInSubplanOp.getVariables()) {
-                nspWithAgg.put(v, nspOp);
-                nspAggVars.put(v, 0);
-                nspAggVarToPlanIndex.put(v, i);
-            }
+            if (listifyVar != null) {
+                OperatorManipulationUtil.substituteVarRec(aggInSubplanOp, unnestVar, listifyVar, true, context);
+                nspAgg.getVariables().addAll(aggInSubplanOp.getVariables());
+                nspAgg.getExpressions().addAll(aggInSubplanOp.getExpressions());
+                for (LogicalVariable v : aggInSubplanOp.getVariables()) {
+                    nspWithAgg.put(v, nspOp);
+                    nspAggVars.put(v, 0);
+                    nspAggVarToPlanIndex.put(v, i);
+                }
 
-            Mutable<ILogicalOperator> opRef1InSubplan = aggInSubplanOp.getInputs().get(0);
-            if (!opRef1InSubplan.getValue().getInputs().isEmpty()) {
-                Mutable<ILogicalOperator> opRef2InSubplan = opRef1InSubplan.getValue().getInputs().get(0);
-                AbstractLogicalOperator op2InSubplan = (AbstractLogicalOperator) opRef2InSubplan.getValue();
-                if (op2InSubplan.getOperatorTag() != LogicalOperatorTag.NESTEDTUPLESOURCE) {
-                    List<Mutable<ILogicalOperator>> nspInpList = nspAgg.getInputs();
-                    nspInpList.clear();
-                    nspInpList.add(opRef1InSubplan);
-                    while (true) {
-                        opRef2InSubplan = opRef1InSubplan.getValue().getInputs().get(0);
-                        op2InSubplan = (AbstractLogicalOperator) opRef2InSubplan.getValue();
-                        if (op2InSubplan.getOperatorTag() == LogicalOperatorTag.UNNEST) {
-                            List<Mutable<ILogicalOperator>> opInpList = opRef1InSubplan.getValue().getInputs();
-                            opInpList.clear();
-                            opInpList.add(nspAggChildRef);
-                            break;
-                        }
-                        opRef1InSubplan = opRef2InSubplan;
-                        if (opRef1InSubplan.getValue().getInputs().isEmpty()) {
-                            throw new IllegalStateException(
+                Mutable<ILogicalOperator> opRef1InSubplan = aggInSubplanOp.getInputs().get(0);
+                if (!opRef1InSubplan.getValue().getInputs().isEmpty()) {
+                    Mutable<ILogicalOperator> opRef2InSubplan = opRef1InSubplan.getValue().getInputs().get(0);
+                    AbstractLogicalOperator op2InSubplan = (AbstractLogicalOperator) opRef2InSubplan.getValue();
+                    if (op2InSubplan.getOperatorTag() != LogicalOperatorTag.NESTEDTUPLESOURCE) {
+                        List<Mutable<ILogicalOperator>> nspInpList = nspAgg.getInputs();
+                        nspInpList.clear();
+                        nspInpList.add(opRef1InSubplan);
+                        while (true) {
+                            opRef2InSubplan = opRef1InSubplan.getValue().getInputs().get(0);
+                            op2InSubplan = (AbstractLogicalOperator) opRef2InSubplan.getValue();
+                            if (op2InSubplan.getOperatorTag() == LogicalOperatorTag.UNNEST) {
+                                List<Mutable<ILogicalOperator>> opInpList = opRef1InSubplan.getValue().getInputs();
+                                opInpList.clear();
+                                opInpList.add(nspAggChildRef);
+                                break;
+                            }
+                            opRef1InSubplan = opRef2InSubplan;
+                            if (opRef1InSubplan.getValue().getInputs().isEmpty()) {
+                                throw new IllegalStateException(
                                         "PushAggregateIntoNestedSubplanRule: could not find UNNEST.");
+                            }
                         }
                     }
                 }
+                subplanOpRef.setValue(subplan.getInputs().get(0).getValue());
+                OperatorPropertiesUtil.typeOpRec(nspAggRef, context);
+                return true;
             }
-            subplanOpRef.setValue(subplan.getInputs().get(0).getValue());
-            OperatorPropertiesUtil.typeOpRec(nspAggRef, context);
         }
-        return true;
+        return false;
     }
 
     private LogicalVariable findListifiedVariable(AggregateOperator nspAgg, LogicalVariable varFromNestedAgg) {
diff --git a/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/ResolveVariableRule.java b/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/ResolveVariableRule.java
deleted file mode 100644
index 2d7695f..0000000
--- a/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/ResolveVariableRule.java
+++ /dev/null
@@ -1,335 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.asterix.optimizer.rules;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.asterix.lang.common.util.FunctionUtil;
-import org.apache.asterix.metadata.declared.MetadataProvider;
-import org.apache.asterix.om.base.AString;
-import org.apache.asterix.om.constants.AsterixConstantValue;
-import org.apache.asterix.om.functions.BuiltinFunctions;
-import org.apache.asterix.om.types.ARecordType;
-import org.apache.asterix.om.types.ATypeTag;
-import org.apache.asterix.om.types.AUnionType;
-import org.apache.asterix.om.types.IAType;
-import org.apache.asterix.om.utils.ConstantExpressionUtil;
-import org.apache.commons.lang3.mutable.Mutable;
-import org.apache.commons.lang3.mutable.MutableObject;
-import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
-import org.apache.hyracks.algebricks.common.utils.Pair;
-import org.apache.hyracks.algebricks.common.utils.Triple;
-import org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression;
-import org.apache.hyracks.algebricks.core.algebra.base.ILogicalOperator;
-import org.apache.hyracks.algebricks.core.algebra.base.IOptimizationContext;
-import org.apache.hyracks.algebricks.core.algebra.base.LogicalExpressionTag;
-import org.apache.hyracks.algebricks.core.algebra.expressions.AbstractFunctionCallExpression;
-import org.apache.hyracks.algebricks.core.algebra.expressions.ConstantExpression;
-import org.apache.hyracks.algebricks.core.algebra.expressions.IVariableTypeEnvironment;
-import org.apache.hyracks.algebricks.core.algebra.expressions.ScalarFunctionCallExpression;
-import org.apache.hyracks.algebricks.core.rewriter.base.IAlgebraicRewriteRule;
-
-/**
- * This rule resolves references to undefined identifiers with the following priority:
- * 1. field-access
- * 2. datasets
- * based on the available type and metadata information.
- *
- *
- * Note that undefined variable references that are FROM/JOIN/UNNEST/Quantifier binding expressions
- * are resolved to dataset only, which has been done in
- *
- * @see org.apache.asterix.lang.sqlpp.rewrites.visitor.VariableCheckAndRewriteVisitor
- *
- */
-public class ResolveVariableRule implements IAlgebraicRewriteRule {
-
-    @Override
-    public boolean rewritePre(Mutable<ILogicalOperator> opRef, IOptimizationContext context)
-            throws AlgebricksException {
-        return false;
-    }
-
-    @Override
-    public boolean rewritePost(Mutable<ILogicalOperator> opRef, IOptimizationContext context)
-            throws AlgebricksException {
-        ILogicalOperator op = opRef.getValue();
-        if (op.getInputs().isEmpty()) {
-            return false;
-        }
-        // Populates the latest type information, e.g., resolved path sugars.
-        context.computeAndSetTypeEnvironmentForOperator(op);
-        if (op.acceptExpressionTransform(
-                exprRef -> rewriteExpressionReference(op, exprRef, new Triple<>(false, null, null), null, context))) {
-            // Generates the up-to-date type information.
-            context.computeAndSetTypeEnvironmentForOperator(op);
-            return true;
-        }
-        return false;
-    }
-
-    // Recursively rewrites for an expression within an operator.
-    private boolean rewriteExpressionReference(ILogicalOperator op, Mutable<ILogicalExpression> exprRef,
-            Triple<Boolean, String, String> fullyQualifiedDatasetPathCandidateFromParent,
-            Mutable<ILogicalExpression> parentFuncRef, IOptimizationContext context) throws AlgebricksException {
-        ILogicalExpression expr = exprRef.getValue();
-        if (expr.getExpressionTag() != LogicalExpressionTag.FUNCTION_CALL) {
-            return false;
-        }
-        boolean changed = false;
-        AbstractFunctionCallExpression funcExpr = (AbstractFunctionCallExpression) expr;
-        Triple<Boolean, String, String> fullyQualifiedDatasetPathCandidate = resolveFullyQualifiedPath(funcExpr,
-                context);
-        for (Mutable<ILogicalExpression> funcArgRef : funcExpr.getArguments()) {
-            if (rewriteExpressionReference(op, funcArgRef, fullyQualifiedDatasetPathCandidate, exprRef, context)) {
-                changed = true;
-            }
-        }
-
-        // Cleans up extra scan-collections if there is.
-        if (changed) {
-            cleanupScanCollectionForDataset(funcExpr);
-        }
-
-        // Does the actual resolution.
-        return changed || resolve(op, context, exprRef, fullyQualifiedDatasetPathCandidateFromParent, parentFuncRef);
-    }
-
-    // Resolves a "resolve" function call expression to a fully qualified variable/field-access path or
-    // a dataset.
-    private boolean resolve(ILogicalOperator op, IOptimizationContext context, Mutable<ILogicalExpression> exprRef,
-            Triple<Boolean, String, String> fullyQualifiedDatasetPathCandidateFromParent,
-            Mutable<ILogicalExpression> parentFuncRef) throws AlgebricksException {
-        AbstractFunctionCallExpression funcExpr = (AbstractFunctionCallExpression) exprRef.getValue();
-        if (funcExpr.getFunctionIdentifier() != BuiltinFunctions.RESOLVE) {
-            return false;
-        }
-        ILogicalExpression arg = funcExpr.getArguments().get(0).getValue();
-        String unresolvedVarName = extractConstantString(arg);
-        return resolveInternal(exprRef, hasMatchedDatasetForVariableName(unresolvedVarName, context),
-                findCandidatePaths(op, extractExprs(funcExpr.getArguments()), unresolvedVarName, context),
-                unresolvedVarName, fullyQualifiedDatasetPathCandidateFromParent, parentFuncRef, context);
-    }
-
-    // Extracts all possible expressions from the arguments of the "resolve" function.
-    private List<ILogicalExpression> extractExprs(List<Mutable<ILogicalExpression>> args) throws AlgebricksException {
-        List<ILogicalExpression> exprs = new ArrayList<>();
-        // The first arg is is the name of the undefined variable.
-        for (int index = 1; index < args.size(); ++index) {
-            ILogicalExpression argExpr = args.get(index).getValue();
-            exprs.add(argExpr);
-        }
-        return exprs;
-    }
-
-    // Resolves an undefined name to a dataset or a fully qualified variable/field-access path
-    // based on the given information of dataset matches and candidate paths.
-    private boolean resolveInternal(Mutable<ILogicalExpression> funcRef, boolean hasMatchedDataset,
-            Collection<Pair<ILogicalExpression, List<String>>> varAccessCandidates, String unresolvedVarName,
-            Triple<Boolean, String, String> fullyQualifiedDatasetPathCandidateFromParent,
-            Mutable<ILogicalExpression> parentFuncRef, IOptimizationContext context) throws AlgebricksException {
-        AbstractFunctionCallExpression func = (AbstractFunctionCallExpression) funcRef.getValue();
-        int numVarCandidates = varAccessCandidates.size();
-
-        // The resolution order: 1. field-access 2. datasets (standalone-name or fully-qualified)
-        if (numVarCandidates > 0) {
-            if (numVarCandidates == 1) {
-                resolveAsFieldAccess(funcRef, varAccessCandidates.iterator().next());
-            } else {
-                // More than one possibilities.
-                throw new AlgebricksException(
-                        "Cannot resolve ambiguous alias reference for undefined identifier " + unresolvedVarName);
-            }
-        } else if (hasMatchedDataset) {
-            // Rewrites the "resolve" function to a "dataset" function and only keep the dataset name argument.
-            func.setFunctionInfo(FunctionUtil.getFunctionInfo(BuiltinFunctions.DATASET));
-            Mutable<ILogicalExpression> datasetNameExpression = func.getArguments().get(0);
-            func.getArguments().clear();
-            func.getArguments().add(datasetNameExpression);
-        } else if (fullyQualifiedDatasetPathCandidateFromParent.first) {
-            // Rewrites the parent "field-access" function to a "dataset" function.
-            AbstractFunctionCallExpression parentFunc = (AbstractFunctionCallExpression) parentFuncRef.getValue();
-            parentFunc.setFunctionInfo(FunctionUtil.getFunctionInfo(BuiltinFunctions.DATASET));
-            parentFunc.getArguments().clear();
-            parentFunc.getArguments().add(
-                    new MutableObject<>(new ConstantExpression(
-                            new AsterixConstantValue(new AString(fullyQualifiedDatasetPathCandidateFromParent.second
-                                    + "." + fullyQualifiedDatasetPathCandidateFromParent.third)))));
-        } else {
-            MetadataProvider metadataProvider = (MetadataProvider) context.getMetadataProvider();
-            // Cannot find any resolution.
-            throw new AlgebricksException("Cannot find dataset " + unresolvedVarName + " in dataverse "
-                    + metadataProvider.getDefaultDataverseName() + " nor an alias with name " + unresolvedVarName);
-        }
-        return true;
-    }
-
-    // Resolves a "resolve" function call as a field access.
-    private void resolveAsFieldAccess(Mutable<ILogicalExpression> funcRef,
-            Pair<ILogicalExpression, List<String>> varAndPath) {
-        // Rewrites to field-access-by-names.
-        ILogicalExpression expr = varAndPath.first;
-        List<String> path = varAndPath.second;
-        Mutable<ILogicalExpression> firstArgRef = new MutableObject<>(expr);
-        ILogicalExpression newFunc = null;
-        for (String fieldName : path) {
-            List<Mutable<ILogicalExpression>> args = new ArrayList<>();
-            args.add(firstArgRef);
-            args.add(new MutableObject<>(new ConstantExpression(new AsterixConstantValue(new AString(fieldName)))));
-            newFunc = new ScalarFunctionCallExpression(
-                    FunctionUtil.getFunctionInfo(BuiltinFunctions.FIELD_ACCESS_BY_NAME), args);
-            firstArgRef = new MutableObject<>(newFunc);
-        }
-        funcRef.setValue(newFunc);
-    }
-
-    // Finds all candidate fully qualified expression/field-access paths.
-    private Set<Pair<ILogicalExpression, List<String>>> findCandidatePaths(ILogicalOperator op,
-            Collection<ILogicalExpression> referenceExprs, String unresolvedVarName, IOptimizationContext context)
-            throws AlgebricksException {
-        Set<Pair<ILogicalExpression, List<String>>> candidates = new HashSet<>();
-        IVariableTypeEnvironment env = context.getOutputTypeEnvironment(op.getInputs().get(0).getValue());
-        for (ILogicalExpression referenceExpr : referenceExprs) {
-            IAType type = (IAType) env.getType(referenceExpr);
-            candidates.addAll(findCandidatePathsForExpr(unresolvedVarName, type, referenceExpr, new ArrayList<>()));
-        }
-        return candidates;
-    }
-
-    // Recursively finds candidate paths under an expression.
-    private Set<Pair<ILogicalExpression, List<String>>> findCandidatePathsForExpr(String unresolvedVarName,
-            IAType pathType, ILogicalExpression expr, List<String> parentPath) throws AlgebricksException {
-        Set<Pair<ILogicalExpression, List<String>>> varAccessCandidates = new HashSet<>();
-        IAType type = pathType;
-        if (type.getTypeTag() == ATypeTag.UNION) {
-            type = ((AUnionType) type).getActualType();
-        }
-        ATypeTag tag = type.getTypeTag();
-        if (tag == ATypeTag.ANY) {
-            List<String> path = new ArrayList<>(parentPath);
-            path.add(unresolvedVarName);
-            varAccessCandidates.add(new Pair<>(expr, path));
-        }
-        if (tag == ATypeTag.OBJECT) {
-            ARecordType recordType = (ARecordType) type;
-            if (recordType.canContainField(unresolvedVarName)) {
-                // If the field name is possible.
-                List<String> path = new ArrayList<>(parentPath);
-                path.add(unresolvedVarName);
-                varAccessCandidates.add(new Pair<>(expr, path));
-            } else {
-                // Recursively identified possible paths.
-                String[] fieldNames = recordType.getFieldNames();
-                IAType[] fieldTypes = recordType.getFieldTypes();
-                for (int index = 0; index < fieldNames.length; ++index) {
-                    List<String> path = new ArrayList<>(parentPath);
-                    path.add(fieldNames[index]);
-                    varAccessCandidates.addAll(findCandidatePathsForExpr(unresolvedVarName, fieldTypes[index], expr,
-                            path));
-                }
-            }
-        }
-        return varAccessCandidates;
-    }
-
-    // Try to resolve the expression like resolve("x").foo as x.foo.
-    private Triple<Boolean, String, String> resolveFullyQualifiedPath(AbstractFunctionCallExpression funcExpr,
-            IOptimizationContext context) throws AlgebricksException {
-        if (!funcExpr.getFunctionIdentifier().equals(BuiltinFunctions.FIELD_ACCESS_BY_NAME)) {
-            return new Triple<>(false, null, null);
-        }
-        List<Mutable<ILogicalExpression>> args = funcExpr.getArguments();
-        ILogicalExpression firstExpr = args.get(0).getValue();
-        ILogicalExpression secondExpr = args.get(1).getValue();
-        if (firstExpr.getExpressionTag() != LogicalExpressionTag.FUNCTION_CALL) {
-            return new Triple<>(false, null, null);
-        }
-        if (secondExpr.getExpressionTag() != LogicalExpressionTag.CONSTANT) {
-            return new Triple<>(false, null, null);
-        }
-        AbstractFunctionCallExpression firstFuncExpr = (AbstractFunctionCallExpression) firstExpr;
-        if (!firstFuncExpr.getFunctionIdentifier().equals(BuiltinFunctions.RESOLVE)) {
-            return new Triple<>(false, null, null);
-        }
-        ILogicalExpression dataverseNameExpr = firstFuncExpr.getArguments().get(0).getValue();
-        String dataverseName = extractConstantString(dataverseNameExpr);
-        String datasetName = extractConstantString(secondExpr);
-        return new Triple<>(hasMatchedDataverseDataset(dataverseName, datasetName, context), dataverseName,
-                datasetName);
-    }
-
-    // Checks whether the dataverse name and dataset name matche a dataset.
-    private boolean hasMatchedDataverseDataset(String dataverseName, String datasetName, IOptimizationContext context)
-            throws AlgebricksException {
-        MetadataProvider mdp = (MetadataProvider) context.getMetadataProvider();
-        return mdp.findDataset(dataverseName, datasetName) != null;
-    }
-
-    // Checks whether the name matches a dataset.
-    private boolean hasMatchedDatasetForVariableName(String varName, IOptimizationContext context)
-            throws AlgebricksException {
-        MetadataProvider mdp = (MetadataProvider) context.getMetadataProvider();
-        if (mdp.findDataset(mdp.getDefaultDataverseName(), varName) != null) {
-            return true;
-        }
-        if (varName.contains(".")) {
-            String[] path = varName.split("\\.");
-            if (path.length != 2) {
-                return false;
-            }
-            if (mdp.findDataset(path[0], path[1]) != null) {
-                return true;
-            }
-        }
-        return false;
-    }
-
-    // Cleans up scan collections on top of a "dataset" function call since "dataset"
-    // is an unnest function.
-    private void cleanupScanCollectionForDataset(AbstractFunctionCallExpression funcExpr) {
-        if (funcExpr.getFunctionIdentifier() != BuiltinFunctions.SCAN_COLLECTION) {
-            return;
-        }
-        ILogicalExpression arg = funcExpr.getArguments().get(0).getValue();
-        if (arg.getExpressionTag() != LogicalExpressionTag.FUNCTION_CALL) {
-            return;
-        }
-        AbstractFunctionCallExpression argFuncExpr = (AbstractFunctionCallExpression) arg;
-        if (argFuncExpr.getFunctionIdentifier() != BuiltinFunctions.DATASET) {
-            return;
-        }
-        funcExpr.setFunctionInfo(argFuncExpr.getFunctionInfo());
-        funcExpr.getArguments().clear();
-        funcExpr.getArguments().addAll(argFuncExpr.getArguments());
-    }
-
-    // Extracts the name of an undefined variable.
-    private String extractConstantString(ILogicalExpression arg) throws AlgebricksException {
-        final String str = ConstantExpressionUtil.getStringConstant(arg);
-        if (str == null) {
-            throw new AlgebricksException("The argument is expected to be a string constant value.");
-        }
-        return str;
-    }
-}
diff --git a/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/translator/LangExpressionToPlanTranslator.java b/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/translator/LangExpressionToPlanTranslator.java
index 719824b..2b83158 100644
--- a/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/translator/LangExpressionToPlanTranslator.java
+++ b/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/translator/LangExpressionToPlanTranslator.java
@@ -173,8 +173,7 @@
 
     public LangExpressionToPlanTranslator(MetadataProvider metadataProvider, int currentVarCounterValue)
             throws AlgebricksException {
-        this.context = new TranslationContext(new Counter(currentVarCounterValue));
-        this.metadataProvider = metadataProvider;
+        this(metadataProvider, new Counter(currentVarCounterValue));
     }
 
     // Keeps the given Counter if one is provided instead of a value.
@@ -794,6 +793,8 @@
     public Pair<ILogicalOperator, LogicalVariable> visit(GroupbyClause gc, Mutable<ILogicalOperator> tupSource)
             throws CompilationException {
         Mutable<ILogicalOperator> topOp = tupSource;
+
+        LogicalVariable groupRecordVar = null;
         if (gc.hasGroupVar()) {
             List<Pair<Expression, Identifier>> groupFieldList = gc.getGroupFieldList();
             List<Mutable<ILogicalExpression>> groupRecordConstructorArgList = new ArrayList<>();
@@ -805,13 +806,14 @@
                 ILogicalExpression groupFieldExpr = langExprToAlgExpression(groupField.first, topOp).first;
                 groupRecordConstructorArgList.add(new MutableObject<>(groupFieldExpr));
             }
-            LogicalVariable groupVar = context.newVarFromExpression(gc.getGroupVar());
-            AssignOperator groupVarAssignOp = new AssignOperator(groupVar,
-                    new MutableObject<>(new ScalarFunctionCallExpression(
-                            FunctionUtil.getFunctionInfo(BuiltinFunctions.OPEN_RECORD_CONSTRUCTOR),
-                            groupRecordConstructorArgList)));
-            groupVarAssignOp.getInputs().add(topOp);
-            topOp = new MutableObject<>(groupVarAssignOp);
+            MutableObject<ILogicalExpression> groupRecordConstr = new MutableObject<>(new ScalarFunctionCallExpression(
+                    FunctionUtil.getFunctionInfo(BuiltinFunctions.OPEN_RECORD_CONSTRUCTOR),
+                    groupRecordConstructorArgList));
+
+            groupRecordVar = context.newVar();
+            AssignOperator groupRecordVarAssignOp = new AssignOperator(groupRecordVar, groupRecordConstr);
+            groupRecordVarAssignOp.getInputs().add(topOp);
+            topOp = new MutableObject<>(groupRecordVarAssignOp);
         }
 
         GroupByOperator gOp = new GroupByOperator();
@@ -831,30 +833,46 @@
         }
 
         gOp.getInputs().add(topOp);
-        for (Entry<Expression, VariableExpr> entry : gc.getWithVarMap().entrySet()) {
-            Pair<ILogicalExpression, Mutable<ILogicalOperator>> listifyInput = langExprToAlgExpression(entry.getKey(),
+
+        if (gc.hasGroupVar()) {
+            VariableExpr groupVar = gc.getGroupVar();
+            LogicalVariable groupLogicalVar = context.newVar();
+            ILogicalPlan nestedPlan = createNestedPlanWithAggregate(groupLogicalVar,
+                    BuiltinFunctions.LISTIFY, new VariableReferenceExpression(groupRecordVar),
                     new MutableObject<>(new NestedTupleSourceOperator(new MutableObject<>(gOp))));
-            List<Mutable<ILogicalExpression>> flArgs = new ArrayList<>(1);
-            flArgs.add(new MutableObject<>(listifyInput.first));
-            AggregateFunctionCallExpression fListify =
-                    BuiltinFunctions.makeAggregateFunctionExpression(BuiltinFunctions.LISTIFY, flArgs);
-            LogicalVariable aggVar = context.newVar();
-            AggregateOperator agg = new AggregateOperator(mkSingletonArrayList(aggVar),
-                    mkSingletonArrayList(new MutableObject<>(fListify)));
-
-            agg.getInputs().add(listifyInput.second);
-
-            ILogicalPlan plan = new ALogicalPlanImpl(new MutableObject<>(agg));
-            gOp.getNestedPlans().add(plan);
-            // Hide the variable that was part of the "with", replacing it with
-            // the one bound by the aggregation op.
-            context.setVar(entry.getValue(), aggVar);
+            gOp.getNestedPlans().add(nestedPlan);
+            context.setVar(groupVar, groupLogicalVar);
         }
+
+        if (gc.hasWithMap()) {
+            for (Entry<Expression, VariableExpr> entry : gc.getWithVarMap().entrySet()) {
+                VariableExpr withVar = entry.getValue();
+                Expression withExpr = entry.getKey();
+                Pair<ILogicalExpression, Mutable<ILogicalOperator>> listifyInput = langExprToAlgExpression(withExpr,
+                        new MutableObject<>(new NestedTupleSourceOperator(new MutableObject<>(gOp))));
+                LogicalVariable withLogicalVar = context.newVar();
+                ILogicalPlan nestedPlan = createNestedPlanWithAggregate(withLogicalVar,
+                        BuiltinFunctions.LISTIFY, listifyInput.first, listifyInput.second);
+                gOp.getNestedPlans().add(nestedPlan);
+                context.setVar(withVar, withLogicalVar);
+            }
+        }
+
         gOp.setGroupAll(gc.isGroupAll());
         gOp.getAnnotations().put(OperatorAnnotations.USE_HASH_GROUP_BY, gc.hasHashGroupByHint());
         return new Pair<>(gOp, null);
     }
 
+    private ILogicalPlan createNestedPlanWithAggregate(LogicalVariable aggOutputVar, FunctionIdentifier aggFunc,
+            ILogicalExpression aggFnInput, Mutable<ILogicalOperator> aggOpInput) {
+        AggregateFunctionCallExpression aggFnCall = BuiltinFunctions.makeAggregateFunctionExpression(aggFunc,
+                mkSingletonArrayList(new MutableObject<>(aggFnInput)));
+        AggregateOperator aggOp = new AggregateOperator(mkSingletonArrayList(aggOutputVar),
+                mkSingletonArrayList(new MutableObject<>(aggFnCall)));
+        aggOp.getInputs().add(aggOpInput);
+        return new ALogicalPlanImpl(new MutableObject<>(aggOp));
+    }
+
     @Override
     public Pair<ILogicalOperator, LogicalVariable> visit(IfExpr ifexpr, Mutable<ILogicalOperator> tupSource)
             throws CompilationException {
@@ -1270,8 +1288,11 @@
             Mutable<ILogicalOperator> topOpRef) throws CompilationException {
         switch (expr.getKind()) {
             case VARIABLE_EXPRESSION:
-                VariableReferenceExpression ve =
-                        new VariableReferenceExpression(context.getVar(((VariableExpr) expr).getVar().getId()));
+                LogicalVariable var = context.getVar(((VariableExpr) expr).getVar().getId());
+                if (var == null) {
+                    throw new IllegalStateException(String.valueOf(expr));
+                }
+                VariableReferenceExpression ve = new VariableReferenceExpression(var);
                 return new Pair<>(ve, topOpRef);
             case LITERAL_EXPRESSION:
                 LiteralExpr val = (LiteralExpr) expr;
diff --git a/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/translator/SqlppExpressionToPlanTranslator.java b/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/translator/SqlppExpressionToPlanTranslator.java
index c17b55b..36183c6 100644
--- a/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/translator/SqlppExpressionToPlanTranslator.java
+++ b/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/translator/SqlppExpressionToPlanTranslator.java
@@ -662,9 +662,11 @@
         for (GbyVariableExpressionPair pair : groupbyClause.getGbyPairList()) {
             fieldBindings.add(getFieldBinding(pair.getVar()));
         }
-        if (groupbyClause.hasWithMap() && groupbyClause.hasGroupVar()) {
-            // Makes sure that we add the re-mapped group variable which refers to a collection.
-            fieldBindings.add(getFieldBinding(groupbyClause.getWithVarMap().get(groupbyClause.getGroupVar())));
+        if (groupbyClause.hasGroupVar()) {
+            fieldBindings.add(getFieldBinding(groupbyClause.getGroupVar()));
+        }
+        if (groupbyClause.hasWithMap()) {
+            throw new IllegalStateException(groupbyClause.getWithVarMap().values().toString()); // no WITH in SQLPP
         }
         return fieldBindings;
     }
diff --git a/asterixdb/asterix-app/src/test/java/org/apache/asterix/test/sqlpp/ParserTestExecutor.java b/asterixdb/asterix-app/src/test/java/org/apache/asterix/test/sqlpp/ParserTestExecutor.java
index d78cd94..85b8c8a 100644
--- a/asterixdb/asterix-app/src/test/java/org/apache/asterix/test/sqlpp/ParserTestExecutor.java
+++ b/asterixdb/asterix-app/src/test/java/org/apache/asterix/test/sqlpp/ParserTestExecutor.java
@@ -192,9 +192,13 @@
                         + "org.apache.asterix.lang.common.rewrites.LangRewritingContext)",
                 declaredFunctions, topExpr, metadataProvider, context);
         PA.invokeMethod(rewriter, "inlineColumnAlias()");
-        PA.invokeMethod(rewriter, "rewriteGlobalAggregations()");
+        PA.invokeMethod(rewriter, "generateColumnNames()");
+        PA.invokeMethod(rewriter, "substituteGroupbyKeyExpression()");
         PA.invokeMethod(rewriter, "rewriteGroupBys()");
-        PA.invokeMethod(rewriter, "variableCheckAndRewrite(boolean)", Boolean.TRUE);
+        PA.invokeMethod(rewriter, "rewriteSetOperations()");
+        PA.invokeMethod(rewriter, "variableCheckAndRewrite()");
+        PA.invokeMethod(rewriter, "rewriteGroupByAggregationSugar()");
+
     }
 
 }
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/denorm-cust-order.sqlpp b/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/denorm-cust-order.sqlpp
index 52ce35c..508d6ec 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/denorm-cust-order.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/denorm-cust-order.sqlpp
@@ -62,9 +62,9 @@
 create  dataset Orders(OrderType) primary key oid on group1;
 
 write output to asterix_nc1:"/tmp/custorder.adm";
-select element {'cid':cid,'cust':cust,'cnt-orders':count(o),'orders':o}
+select element {'cid':cid,'cust':(from g select c),'cnt-orders':count(o),'orders': (from g select o)}
 from  Customers as c,
       Orders as o
 where (c.cid = o.cid)
-group by c.cid as cid
+group by c.cid as cid group as g
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/orderby-desc-using-gby.sqlpp b/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/orderby-desc-using-gby.sqlpp
index 279adf6..2313e90 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/orderby-desc-using-gby.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/orderby-desc-using-gby.sqlpp
@@ -52,6 +52,6 @@
 write output to asterix_nc1:"rttest/gby-using-orderby-desc.adm";
 select element {'name':name,'age':age}
 from  Customers as c
-group by c.name as name
+group by c.name as name, c.age as age
 order by name desc,age
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/orders-aggreg.sqlpp b/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/orders-aggreg.sqlpp
index f82ce53..cca0211 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/orders-aggreg.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/orders-aggreg.sqlpp
@@ -40,13 +40,13 @@
 create  dataset Orders(OrderType) primary key oid on group1;
 
 write output to asterix_nc1:"/tmp/orders-aggreg.adm";
-select element {'cid':cid,'ordpercust':`orders-aggreg`.coll_count(o),'totalcust':`orders-aggreg`.coll_sum((
-        select element i.total
-        from  o as i
+select element {'cid':cid,'ordpercust':`orders-aggreg`.coll_count(g),'totalcust':`orders-aggreg`.coll_sum((
+        select element i.o.total
+        from  g as i
     )),'avgcust':`orders-aggreg`.coll_avg((
-        select element i.total
-        from  o as i
+        select element i.o.total
+        from  g as i
     ))}
 from  Orders as o
-group by o.cid as cid
+group by o.cid as cid group as g
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/q01_pricing_summary_report_nt.sqlpp b/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/q01_pricing_summary_report_nt.sqlpp
index 2cc5d36..6497eea 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/q01_pricing_summary_report_nt.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/q01_pricing_summary_report_nt.sqlpp
@@ -49,30 +49,30 @@
 
 write output to asterix_nc1:"rttest/tpch_q1_pricing_summary_report_nt.adm";
 select element {'l_returnflag':l_returnflag,'l_linestatus':l_linestatus,'sum_qty':tpch.coll_sum((
-        select element i.l_quantity
-        from  l as i
+        select element i.l.l_quantity
+        from  g as i
     )),'sum_base_price':tpch.coll_sum((
-        select element i.l_extendedprice
-        from  l as i
+        select element i.l.l_extendedprice
+        from  g as i
     )),'sum_disc_price':tpch.coll_sum((
-        select element (i.l_extendedprice * (1 - i.l_discount))
-        from  l as i
+        select element (i.l.l_extendedprice * (1 - i.l.l_discount))
+        from  g as i
     )),'sum_charge':tpch.coll_sum((
-        select element (i.l_extendedprice * (1 - i.l_discount) * (1 + i.l_tax))
-        from  l as i
+        select element (i.l.l_extendedprice * (1 - i.l.l_discount) * (1 + i.l.l_tax))
+        from  g as i
     )),'ave_qty':tpch.coll_avg((
-        select element i.l_quantity
-        from  l as i
+        select element i.l.l_quantity
+        from  g as i
     )),'ave_price':tpch.coll_avg((
-        select element i.l_extendedprice
-        from  l as i
+        select element i.l.l_extendedprice
+        from  g as i
     )),'ave_disc':tpch.coll_avg((
-        select element i.l_discount
-        from  l as i
-    )),'count_order':tpch.coll_count(l)}
+        select element i.l.l_discount
+        from  g as i
+    )),'count_order':tpch.coll_count(g)}
 from  LineItem as l
 where (l.l_shipdate <= '1998-09-02')
 /* +hash */
-group by l.l_returnflag as l_returnflag,l.l_linestatus as l_linestatus
+group by l.l_returnflag as l_returnflag,l.l_linestatus as l_linestatus group as g
 order by l_returnflag,l_linestatus
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/query-issue562.sqlpp b/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/query-issue562.sqlpp
index 645d320..7b49736 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/query-issue562.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/query-issue562.sqlpp
@@ -92,9 +92,9 @@
       with  phone_substr as tpch.substring(c.c_phone,1,2)
       where ((c.c_acctbal > 0.0) and ((phone_substr = '13') or (phone_substr = '31') or (phone_substr = '23') or (phone_substr = '29') or (phone_substr = '30') or (phone_substr = '18') or (phone_substr = '17')))
   ))
-select element {'cntrycode':cntrycode,'numcust':tpch.coll_count(ct),'totacctbal':tpch.coll_sum((
-        select element i.c_acctbal
-        from  ct as i
+select element {'cntrycode':cntrycode,'numcust':tpch.coll_count(g),'totacctbal':tpch.coll_sum((
+        select element i.ct.c_acctbal
+        from  g as i
     ))}
 from  tpch.q22_customer_tmp() as ct
 where (tpch.coll_count((
@@ -102,6 +102,6 @@
     from  Orders as o
     where (ct.c_custkey = o.o_custkey)
 )) = 0)
-group by ct.cntrycode as cntrycode
+group by ct.cntrycode as cntrycode group as g
 order by cntrycode
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/split-materialization-above-join.sqlpp b/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/split-materialization-above-join.sqlpp
index 187e6cb..2f75c10 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/split-materialization-above-join.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/queries_sqlpp/split-materialization-above-join.sqlpp
@@ -40,7 +40,7 @@
 from  DBLP as paperLeft,
       DBLP as paperRight,
       (
-    select element {'idLeft':idLeft,'idRight':idRight,'sim':sim[0]}
+    select element {'idLeft':idLeft,'idRight':idRight,'sim':g[0].sim[0]}
     from  DBLP as paperLeft,
           fuzzyjoin.`subset-collection`(tokensLeft,0,fuzzyjoin.`prefix-len-jaccard`(lenLeft,0.500000f)) as prefixTokenLeft,
           DBLP as paperRight,
@@ -75,7 +75,7 @@
       ),
           sim as fuzzyjoin.`similarity-jaccard-prefix`(lenLeft,tokensLeft,lenRight,tokensRight,prefixTokenLeft,0.500000f)
     where ((prefixTokenLeft = prefixTokenRight) and ((sim >= 0.500000f) and (paperLeft.id < paperRight.id)))
-    group by paperLeft.id as idLeft,paperRight.id as idRight
+    group by paperLeft.id as idLeft,paperRight.id as idRight group as g(sim as sim)
 ) as ridpair
 where ((ridpair.idLeft = paperLeft.id) and (ridpair.idRight = paperRight.id))
 order by paperLeft.id,paperRight.id
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/aggregate/constant-gby-agg.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/aggregate/constant-gby-agg.plan
index 26601ba..c83a85c 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/aggregate/constant-gby-agg.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/aggregate/constant-gby-agg.plan
@@ -3,13 +3,13 @@
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-          -- SORT_GROUP_BY[$$18]  |PARTITIONED|
+          -- SORT_GROUP_BY[$$38]  |PARTITIONED|
                   {
                     -- AGGREGATE  |LOCAL|
                       -- NESTED_TUPLE_SOURCE  |LOCAL|
                   }
-            -- HASH_PARTITION_EXCHANGE [$$18]  |PARTITIONED|
-              -- SORT_GROUP_BY[$$14]  |PARTITIONED|
+            -- HASH_PARTITION_EXCHANGE [$$38]  |PARTITIONED|
+              -- SORT_GROUP_BY[$$34]  |PARTITIONED|
                       {
                         -- AGGREGATE  |LOCAL|
                           -- NESTED_TUPLE_SOURCE  |LOCAL|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/gby_partitioning_property_01.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/gby_partitioning_property_01.plan
index 7e11745..0d7d538 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/gby_partitioning_property_01.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/gby_partitioning_property_01.plan
@@ -3,13 +3,13 @@
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-          -- PRE_CLUSTERED_GROUP_BY[$$32]  |PARTITIONED|
+          -- PRE_CLUSTERED_GROUP_BY[$$59]  |PARTITIONED|
                   {
                     -- AGGREGATE  |LOCAL|
                       -- NESTED_TUPLE_SOURCE  |LOCAL|
                   }
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-              -- SORT_GROUP_BY[$$22]  |PARTITIONED|
+              -- SORT_GROUP_BY[$$49]  |PARTITIONED|
                       {
                         -- AGGREGATE  |LOCAL|
                           -- NESTED_TUPLE_SOURCE  |LOCAL|
@@ -17,8 +17,8 @@
                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                   -- STREAM_PROJECT  |PARTITIONED|
                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                      -- HYBRID_HASH_JOIN [$$22][$$25]  |PARTITIONED|
-                        -- HASH_PARTITION_EXCHANGE [$$22]  |PARTITIONED|
+                      -- HYBRID_HASH_JOIN [$$49][$$52]  |PARTITIONED|
+                        -- HASH_PARTITION_EXCHANGE [$$49]  |PARTITIONED|
                           -- STREAM_PROJECT  |PARTITIONED|
                             -- ASSIGN  |PARTITIONED|
                               -- STREAM_PROJECT  |PARTITIONED|
@@ -26,7 +26,7 @@
                                   -- DATASOURCE_SCAN  |PARTITIONED|
                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                       -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                        -- HASH_PARTITION_EXCHANGE [$$25]  |PARTITIONED|
+                        -- HASH_PARTITION_EXCHANGE [$$52]  |PARTITIONED|
                           -- STREAM_PROJECT  |PARTITIONED|
                             -- ASSIGN  |PARTITIONED|
                               -- STREAM_PROJECT  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/hints/broadcast_hint_1.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/hints/broadcast_hint_1.plan
index d45ccfe..86bb1c8 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/hints/broadcast_hint_1.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/hints/broadcast_hint_1.plan
@@ -4,7 +4,7 @@
       -- ASSIGN  |PARTITIONED|
         -- STREAM_PROJECT  |PARTITIONED|
           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-            -- HYBRID_HASH_JOIN [$$21, $$23, $$25][$$22, $$24, $$26]  |PARTITIONED|
+            -- HYBRID_HASH_JOIN [$$35, $$37, $$39][$$36, $$38, $$40]  |PARTITIONED|
               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                 -- STREAM_PROJECT  |PARTITIONED|
                   -- ASSIGN  |PARTITIONED|
@@ -20,4 +20,4 @@
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                         -- DATASOURCE_SCAN  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                            -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
\ No newline at end of file
+                            -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/hints/broadcast_hint_2.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/hints/broadcast_hint_2.plan
index d45ccfe..86bb1c8 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/hints/broadcast_hint_2.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/hints/broadcast_hint_2.plan
@@ -4,7 +4,7 @@
       -- ASSIGN  |PARTITIONED|
         -- STREAM_PROJECT  |PARTITIONED|
           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-            -- HYBRID_HASH_JOIN [$$21, $$23, $$25][$$22, $$24, $$26]  |PARTITIONED|
+            -- HYBRID_HASH_JOIN [$$35, $$37, $$39][$$36, $$38, $$40]  |PARTITIONED|
               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                 -- STREAM_PROJECT  |PARTITIONED|
                   -- ASSIGN  |PARTITIONED|
@@ -20,4 +20,4 @@
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                         -- DATASOURCE_SCAN  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                            -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
\ No newline at end of file
+                            -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/hints/broadcast_hint_3.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/hints/broadcast_hint_3.plan
index b7669dd..240b1aa 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/hints/broadcast_hint_3.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/hints/broadcast_hint_3.plan
@@ -4,8 +4,8 @@
       -- ASSIGN  |PARTITIONED|
         -- STREAM_PROJECT  |PARTITIONED|
           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-            -- HYBRID_HASH_JOIN [$$21, $$24, $$25][$$22, $$23, $$26]  |PARTITIONED|
-              -- HASH_PARTITION_EXCHANGE [$$21, $$24, $$25]  |PARTITIONED|
+            -- HYBRID_HASH_JOIN [$$35, $$38, $$39][$$36, $$37, $$40]  |PARTITIONED|
+              -- HASH_PARTITION_EXCHANGE [$$35, $$38, $$39]  |PARTITIONED|
                 -- STREAM_PROJECT  |PARTITIONED|
                   -- ASSIGN  |PARTITIONED|
                     -- STREAM_PROJECT  |PARTITIONED|
@@ -13,11 +13,11 @@
                         -- DATASOURCE_SCAN  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                             -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-              -- HASH_PARTITION_EXCHANGE [$$22, $$23, $$26]  |PARTITIONED|
+              -- HASH_PARTITION_EXCHANGE [$$36, $$37, $$40]  |PARTITIONED|
                 -- STREAM_PROJECT  |PARTITIONED|
                   -- ASSIGN  |PARTITIONED|
                     -- STREAM_PROJECT  |PARTITIONED|
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                         -- DATASOURCE_SCAN  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                            -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
\ No newline at end of file
+                            -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/loj-core.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/loj-core.plan
index 1d34c95..2cab787 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/loj-core.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/loj-core.plan
@@ -2,20 +2,20 @@
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
-        -- SORT_MERGE_EXCHANGE [$$15(ASC) ]  |PARTITIONED|
-          -- STABLE_SORT [$$15(ASC)]  |PARTITIONED|
+        -- SORT_MERGE_EXCHANGE [$$36(ASC) ]  |PARTITIONED|
+          -- STABLE_SORT [$$36(ASC)]  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
               -- STREAM_PROJECT  |PARTITIONED|
                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                  -- HYBRID_HASH_JOIN [$$17][$$18]  |PARTITIONED|
-                    -- HASH_PARTITION_EXCHANGE [$$17]  |PARTITIONED|
+                  -- HYBRID_HASH_JOIN [$$38][$$39]  |PARTITIONED|
+                    -- HASH_PARTITION_EXCHANGE [$$38]  |PARTITIONED|
                       -- STREAM_PROJECT  |PARTITIONED|
                         -- ASSIGN  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                             -- DATASOURCE_SCAN  |PARTITIONED|
                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                 -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                    -- HASH_PARTITION_EXCHANGE [$$18]  |PARTITIONED|
+                    -- HASH_PARTITION_EXCHANGE [$$39]  |PARTITIONED|
                       -- ASSIGN  |PARTITIONED|
                         -- STREAM_PROJECT  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/loj-sugar.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/loj-sugar.plan
index 1d34c95..a547407 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/loj-sugar.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/loj-sugar.plan
@@ -2,20 +2,20 @@
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
-        -- SORT_MERGE_EXCHANGE [$$15(ASC) ]  |PARTITIONED|
-          -- STABLE_SORT [$$15(ASC)]  |PARTITIONED|
+        -- SORT_MERGE_EXCHANGE [$$29(ASC) ]  |PARTITIONED|
+          -- STABLE_SORT [$$29(ASC)]  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
               -- STREAM_PROJECT  |PARTITIONED|
                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                  -- HYBRID_HASH_JOIN [$$17][$$18]  |PARTITIONED|
-                    -- HASH_PARTITION_EXCHANGE [$$17]  |PARTITIONED|
+                  -- HYBRID_HASH_JOIN [$$31][$$32]  |PARTITIONED|
+                    -- HASH_PARTITION_EXCHANGE [$$31]  |PARTITIONED|
                       -- STREAM_PROJECT  |PARTITIONED|
                         -- ASSIGN  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                             -- DATASOURCE_SCAN  |PARTITIONED|
                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                 -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                    -- HASH_PARTITION_EXCHANGE [$$18]  |PARTITIONED|
+                    -- HASH_PARTITION_EXCHANGE [$$32]  |PARTITIONED|
                       -- ASSIGN  |PARTITIONED|
                         -- STREAM_PROJECT  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-05.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-05.plan
index 15f9171..7becb2c 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-05.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-05.plan
@@ -2,13 +2,13 @@
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
-        -- SORT_MERGE_EXCHANGE [$$18(ASC), $$19(ASC) ]  |PARTITIONED|
-          -- STABLE_SORT [$$18(ASC), $$19(ASC)]  |PARTITIONED|
+        -- SORT_MERGE_EXCHANGE [$$32(ASC), $$33(ASC) ]  |PARTITIONED|
+          -- STABLE_SORT [$$32(ASC), $$33(ASC)]  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
               -- STREAM_PROJECT  |PARTITIONED|
                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                  -- HYBRID_HASH_JOIN [$$16][$$17]  |PARTITIONED|
-                    -- HASH_PARTITION_EXCHANGE [$$16]  |PARTITIONED|
+                  -- HYBRID_HASH_JOIN [$$30][$$31]  |PARTITIONED|
+                    -- HASH_PARTITION_EXCHANGE [$$30]  |PARTITIONED|
                       -- STREAM_PROJECT  |PARTITIONED|
                         -- ASSIGN  |PARTITIONED|
                           -- STREAM_PROJECT  |PARTITIONED|
@@ -16,7 +16,7 @@
                               -- DATASOURCE_SCAN  |PARTITIONED|
                                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                   -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                    -- HASH_PARTITION_EXCHANGE [$$17]  |PARTITIONED|
+                    -- HASH_PARTITION_EXCHANGE [$$31]  |PARTITIONED|
                       -- STREAM_PROJECT  |PARTITIONED|
                         -- ASSIGN  |PARTITIONED|
                           -- STREAM_PROJECT  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-06.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-06.plan
index 15f9171..7becb2c 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-06.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-06.plan
@@ -2,13 +2,13 @@
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
-        -- SORT_MERGE_EXCHANGE [$$18(ASC), $$19(ASC) ]  |PARTITIONED|
-          -- STABLE_SORT [$$18(ASC), $$19(ASC)]  |PARTITIONED|
+        -- SORT_MERGE_EXCHANGE [$$32(ASC), $$33(ASC) ]  |PARTITIONED|
+          -- STABLE_SORT [$$32(ASC), $$33(ASC)]  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
               -- STREAM_PROJECT  |PARTITIONED|
                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                  -- HYBRID_HASH_JOIN [$$16][$$17]  |PARTITIONED|
-                    -- HASH_PARTITION_EXCHANGE [$$16]  |PARTITIONED|
+                  -- HYBRID_HASH_JOIN [$$30][$$31]  |PARTITIONED|
+                    -- HASH_PARTITION_EXCHANGE [$$30]  |PARTITIONED|
                       -- STREAM_PROJECT  |PARTITIONED|
                         -- ASSIGN  |PARTITIONED|
                           -- STREAM_PROJECT  |PARTITIONED|
@@ -16,7 +16,7 @@
                               -- DATASOURCE_SCAN  |PARTITIONED|
                                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                   -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                    -- HASH_PARTITION_EXCHANGE [$$17]  |PARTITIONED|
+                    -- HASH_PARTITION_EXCHANGE [$$31]  |PARTITIONED|
                       -- STREAM_PROJECT  |PARTITIONED|
                         -- ASSIGN  |PARTITIONED|
                           -- STREAM_PROJECT  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-07.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-07.plan
index 7f5a841..913c442 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-07.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-07.plan
@@ -2,13 +2,13 @@
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
-        -- SORT_MERGE_EXCHANGE [$$20(ASC), $$21(ASC) ]  |PARTITIONED|
-          -- STABLE_SORT [$$20(ASC), $$21(ASC)]  |PARTITIONED|
+        -- SORT_MERGE_EXCHANGE [$$34(ASC), $$35(ASC) ]  |PARTITIONED|
+          -- STABLE_SORT [$$34(ASC), $$35(ASC)]  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
               -- STREAM_PROJECT  |PARTITIONED|
                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                  -- HYBRID_HASH_JOIN [$$17][$$18]  |PARTITIONED|
-                    -- HASH_PARTITION_EXCHANGE [$$17]  |PARTITIONED|
+                  -- HYBRID_HASH_JOIN [$$31][$$32]  |PARTITIONED|
+                    -- HASH_PARTITION_EXCHANGE [$$31]  |PARTITIONED|
                       -- STREAM_PROJECT  |PARTITIONED|
                         -- ASSIGN  |PARTITIONED|
                           -- STREAM_PROJECT  |PARTITIONED|
@@ -16,7 +16,7 @@
                               -- DATASOURCE_SCAN  |PARTITIONED|
                                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                   -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                    -- HASH_PARTITION_EXCHANGE [$$18]  |PARTITIONED|
+                    -- HASH_PARTITION_EXCHANGE [$$32]  |PARTITIONED|
                       -- STREAM_PROJECT  |PARTITIONED|
                         -- ASSIGN  |PARTITIONED|
                           -- STREAM_PROJECT  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-08.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-08.plan
index 06483e4..9f54d38 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-08.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-08.plan
@@ -2,8 +2,8 @@
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
-        -- SORT_MERGE_EXCHANGE [$$20(ASC), $$21(ASC) ]  |PARTITIONED|
-          -- STABLE_SORT [$$20(ASC), $$21(ASC)]  |PARTITIONED|
+        -- SORT_MERGE_EXCHANGE [$$34(ASC), $$35(ASC) ]  |PARTITIONED|
+          -- STABLE_SORT [$$34(ASC), $$35(ASC)]  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
               -- STREAM_PROJECT  |PARTITIONED|
                 -- STREAM_SELECT  |PARTITIONED|
@@ -12,7 +12,7 @@
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                         -- BTREE_SEARCH  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                            -- STABLE_SORT [$$25(ASC)]  |PARTITIONED|
+                            -- STABLE_SORT [$$39(ASC)]  |PARTITIONED|
                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                 -- STREAM_PROJECT  |PARTITIONED|
                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-09.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-09.plan
index 06483e4..9f54d38 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-09.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-equi-join-non-enforced/btree-equi-join-non-enforced-09.plan
@@ -2,8 +2,8 @@
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
-        -- SORT_MERGE_EXCHANGE [$$20(ASC), $$21(ASC) ]  |PARTITIONED|
-          -- STABLE_SORT [$$20(ASC), $$21(ASC)]  |PARTITIONED|
+        -- SORT_MERGE_EXCHANGE [$$34(ASC), $$35(ASC) ]  |PARTITIONED|
+          -- STABLE_SORT [$$34(ASC), $$35(ASC)]  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
               -- STREAM_PROJECT  |PARTITIONED|
                 -- STREAM_SELECT  |PARTITIONED|
@@ -12,7 +12,7 @@
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                         -- BTREE_SEARCH  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                            -- STABLE_SORT [$$25(ASC)]  |PARTITIONED|
+                            -- STABLE_SORT [$$39(ASC)]  |PARTITIONED|
                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                 -- STREAM_PROJECT  |PARTITIONED|
                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-04.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-04.plan
index 459286e..4c8008f 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-04.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-04.plan
@@ -2,8 +2,8 @@
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
-        -- SORT_MERGE_EXCHANGE [$$11(ASC) ]  |PARTITIONED|
-          -- STABLE_SORT [$$11(ASC)]  |PARTITIONED|
+        -- SORT_MERGE_EXCHANGE [$$18(ASC) ]  |PARTITIONED|
+          -- STABLE_SORT [$$18(ASC)]  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
               -- STREAM_PROJECT  |PARTITIONED|
                 -- STREAM_SELECT  |PARTITIONED|
@@ -12,7 +12,7 @@
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                         -- BTREE_SEARCH  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                            -- STABLE_SORT [$$16(ASC)]  |PARTITIONED|
+                            -- STABLE_SORT [$$23(ASC)]  |PARTITIONED|
                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                 -- STREAM_PROJECT  |PARTITIONED|
                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-05.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-05.plan
index 459286e..4c8008f 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-05.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-05.plan
@@ -2,8 +2,8 @@
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
-        -- SORT_MERGE_EXCHANGE [$$11(ASC) ]  |PARTITIONED|
-          -- STABLE_SORT [$$11(ASC)]  |PARTITIONED|
+        -- SORT_MERGE_EXCHANGE [$$18(ASC) ]  |PARTITIONED|
+          -- STABLE_SORT [$$18(ASC)]  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
               -- STREAM_PROJECT  |PARTITIONED|
                 -- STREAM_SELECT  |PARTITIONED|
@@ -12,7 +12,7 @@
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                         -- BTREE_SEARCH  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                            -- STABLE_SORT [$$16(ASC)]  |PARTITIONED|
+                            -- STABLE_SORT [$$23(ASC)]  |PARTITIONED|
                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                 -- STREAM_PROJECT  |PARTITIONED|
                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-06.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-06.plan
index 01c6a30..844758a 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-06.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-06.plan
@@ -2,8 +2,8 @@
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
-        -- SORT_MERGE_EXCHANGE [$$11(ASC) ]  |PARTITIONED|
-          -- STABLE_SORT [$$11(ASC)]  |PARTITIONED|
+        -- SORT_MERGE_EXCHANGE [$$18(ASC) ]  |PARTITIONED|
+          -- STABLE_SORT [$$18(ASC)]  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
               -- STREAM_PROJECT  |PARTITIONED|
                 -- STREAM_SELECT  |PARTITIONED|
@@ -12,7 +12,7 @@
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                         -- BTREE_SEARCH  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                            -- STABLE_SORT [$$15(ASC)]  |PARTITIONED|
+                            -- STABLE_SORT [$$22(ASC)]  |PARTITIONED|
                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                 -- STREAM_PROJECT  |PARTITIONED|
                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-07.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-07.plan
index 01c6a30..844758a 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-07.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-07.plan
@@ -2,8 +2,8 @@
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
-        -- SORT_MERGE_EXCHANGE [$$11(ASC) ]  |PARTITIONED|
-          -- STABLE_SORT [$$11(ASC)]  |PARTITIONED|
+        -- SORT_MERGE_EXCHANGE [$$18(ASC) ]  |PARTITIONED|
+          -- STABLE_SORT [$$18(ASC)]  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
               -- STREAM_PROJECT  |PARTITIONED|
                 -- STREAM_SELECT  |PARTITIONED|
@@ -12,7 +12,7 @@
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                         -- BTREE_SEARCH  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                            -- STABLE_SORT [$$15(ASC)]  |PARTITIONED|
+                            -- STABLE_SORT [$$22(ASC)]  |PARTITIONED|
                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                 -- STREAM_PROJECT  |PARTITIONED|
                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-08.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-08.plan
index 01c6a30..844758a 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-08.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-08.plan
@@ -2,8 +2,8 @@
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
-        -- SORT_MERGE_EXCHANGE [$$11(ASC) ]  |PARTITIONED|
-          -- STABLE_SORT [$$11(ASC)]  |PARTITIONED|
+        -- SORT_MERGE_EXCHANGE [$$18(ASC) ]  |PARTITIONED|
+          -- STABLE_SORT [$$18(ASC)]  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
               -- STREAM_PROJECT  |PARTITIONED|
                 -- STREAM_SELECT  |PARTITIONED|
@@ -12,7 +12,7 @@
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                         -- BTREE_SEARCH  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                            -- STABLE_SORT [$$15(ASC)]  |PARTITIONED|
+                            -- STABLE_SORT [$$22(ASC)]  |PARTITIONED|
                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                 -- STREAM_PROJECT  |PARTITIONED|
                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-09.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-09.plan
index 01c6a30..844758a 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-09.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-09.plan
@@ -2,8 +2,8 @@
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
-        -- SORT_MERGE_EXCHANGE [$$11(ASC) ]  |PARTITIONED|
-          -- STABLE_SORT [$$11(ASC)]  |PARTITIONED|
+        -- SORT_MERGE_EXCHANGE [$$18(ASC) ]  |PARTITIONED|
+          -- STABLE_SORT [$$18(ASC)]  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
               -- STREAM_PROJECT  |PARTITIONED|
                 -- STREAM_SELECT  |PARTITIONED|
@@ -12,7 +12,7 @@
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                         -- BTREE_SEARCH  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                            -- STABLE_SORT [$$15(ASC)]  |PARTITIONED|
+                            -- STABLE_SORT [$$22(ASC)]  |PARTITIONED|
                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                 -- STREAM_PROJECT  |PARTITIONED|
                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-10.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-10.plan
index 01c6a30..844758a 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-10.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-10.plan
@@ -2,8 +2,8 @@
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
-        -- SORT_MERGE_EXCHANGE [$$11(ASC) ]  |PARTITIONED|
-          -- STABLE_SORT [$$11(ASC)]  |PARTITIONED|
+        -- SORT_MERGE_EXCHANGE [$$18(ASC) ]  |PARTITIONED|
+          -- STABLE_SORT [$$18(ASC)]  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
               -- STREAM_PROJECT  |PARTITIONED|
                 -- STREAM_SELECT  |PARTITIONED|
@@ -12,7 +12,7 @@
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                         -- BTREE_SEARCH  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                            -- STABLE_SORT [$$15(ASC)]  |PARTITIONED|
+                            -- STABLE_SORT [$$22(ASC)]  |PARTITIONED|
                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                 -- STREAM_PROJECT  |PARTITIONED|
                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-105.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-105.plan
index aa6a642..1a359dd 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-105.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-105.plan
@@ -2,8 +2,8 @@
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
-        -- SORT_MERGE_EXCHANGE [$$15(ASC) ]  |PARTITIONED|
-          -- STABLE_SORT [$$15(ASC)]  |PARTITIONED|
+        -- SORT_MERGE_EXCHANGE [$$22(ASC) ]  |PARTITIONED|
+          -- STABLE_SORT [$$22(ASC)]  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
               -- STREAM_PROJECT  |PARTITIONED|
                 -- STREAM_SELECT  |PARTITIONED|
@@ -14,7 +14,7 @@
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                             -- INTERSECT  |PARTITIONED|
                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                -- STABLE_SORT [$$19(ASC)]  |PARTITIONED|
+                                -- STABLE_SORT [$$26(ASC)]  |PARTITIONED|
                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                     -- STREAM_PROJECT  |PARTITIONED|
                                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
@@ -23,7 +23,7 @@
                                             -- ASSIGN  |PARTITIONED|
                                               -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                -- STABLE_SORT [$$22(ASC)]  |PARTITIONED|
+                                -- STABLE_SORT [$$29(ASC)]  |PARTITIONED|
                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                     -- STREAM_PROJECT  |PARTITIONED|
                                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-11.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-11.plan
index 41da8df..ad089de 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-11.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/open-index-non-enforced/btree-index-non-enforced/btree-index-non-enforced-11.plan
@@ -2,8 +2,8 @@
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
-        -- SORT_MERGE_EXCHANGE [$$14(ASC) ]  |PARTITIONED|
-          -- STABLE_SORT [$$14(ASC)]  |PARTITIONED|
+        -- SORT_MERGE_EXCHANGE [$$21(ASC) ]  |PARTITIONED|
+          -- STABLE_SORT [$$21(ASC)]  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
               -- STREAM_PROJECT  |PARTITIONED|
                 -- STREAM_SELECT  |PARTITIONED|
@@ -13,7 +13,7 @@
                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                           -- BTREE_SEARCH  |PARTITIONED|
                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                              -- STABLE_SORT [$$19(ASC)]  |PARTITIONED|
+                              -- STABLE_SORT [$$26(ASC)]  |PARTITIONED|
                                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                   -- STREAM_PROJECT  |PARTITIONED|
                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-159-3.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-159-3.plan
index ab2661b..07978f6 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-159-3.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-159-3.plan
@@ -3,14 +3,14 @@
     -- STREAM_LIMIT  |UNPARTITIONED|
       -- STREAM_PROJECT  |PARTITIONED|
         -- ASSIGN  |PARTITIONED|
-          -- SORT_MERGE_EXCHANGE [$$27(DESC), $$28(DESC) ]  |PARTITIONED|
+          -- SORT_MERGE_EXCHANGE [$$41(DESC), $$42(DESC) ]  |PARTITIONED|
             -- STREAM_LIMIT  |PARTITIONED|
               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                -- STABLE_SORT [topK: 5] [$$27(DESC), $$28(DESC)]  |PARTITIONED|
+                -- STABLE_SORT [topK: 5] [$$41(DESC), $$42(DESC)]  |PARTITIONED|
                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                     -- STREAM_PROJECT  |PARTITIONED|
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                        -- HYBRID_HASH_JOIN [$$27][$$36]  |PARTITIONED|
+                        -- HYBRID_HASH_JOIN [$$41][$$50]  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                             -- STREAM_PROJECT  |PARTITIONED|
                               -- ASSIGN  |PARTITIONED|
@@ -27,7 +27,7 @@
                                                     -- DATASOURCE_SCAN  |PARTITIONED|
                                                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                         -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                          -- HASH_PARTITION_EXCHANGE [$$36]  |PARTITIONED|
+                          -- HASH_PARTITION_EXCHANGE [$$50]  |PARTITIONED|
                             -- STREAM_PROJECT  |PARTITIONED|
                               -- STREAM_SELECT  |PARTITIONED|
                                 -- SUBPLAN  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-1671.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-1671.plan
index 3aaaeb0..d26d5a0 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-1671.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-1671.plan
@@ -4,10 +4,10 @@
       -- STREAM_PROJECT  |PARTITIONED|
         -- ASSIGN  |PARTITIONED|
           -- STREAM_PROJECT  |PARTITIONED|
-            -- SORT_MERGE_EXCHANGE [$$10(ASC), $$11(ASC) ]  |PARTITIONED|
+            -- SORT_MERGE_EXCHANGE [$$17(ASC), $$18(ASC) ]  |PARTITIONED|
               -- STREAM_LIMIT  |PARTITIONED|
                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                  -- STABLE_SORT [topK: 0] [$$10(ASC), $$11(ASC)]  |PARTITIONED|
+                  -- STABLE_SORT [topK: 0] [$$17(ASC), $$18(ASC)]  |PARTITIONED|
                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                       -- ASSIGN  |PARTITIONED|
                         -- STREAM_PROJECT  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-1806.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-1806.plan
index ad30823..0f8b28f 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-1806.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-1806.plan
@@ -3,13 +3,13 @@
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
         -- SORT_MERGE_EXCHANGE [$$l_returnflag(ASC), $$l_linestatus(ASC) ]  |PARTITIONED|
-          -- SORT_GROUP_BY[$$96, $$97]  |PARTITIONED|
+          -- SORT_GROUP_BY[$$140, $$141]  |PARTITIONED|
                   {
                     -- AGGREGATE  |LOCAL|
                       -- NESTED_TUPLE_SOURCE  |LOCAL|
                   }
-            -- HASH_PARTITION_EXCHANGE [$$96, $$97]  |PARTITIONED|
-              -- SORT_GROUP_BY[$$64, $$65]  |PARTITIONED|
+            -- HASH_PARTITION_EXCHANGE [$$140, $$141]  |PARTITIONED|
+              -- SORT_GROUP_BY[$$108, $$109]  |PARTITIONED|
                       {
                         -- AGGREGATE  |LOCAL|
                           -- NESTED_TUPLE_SOURCE  |LOCAL|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-810-2.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-810-2.plan
index 238736a..1d80ccf 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-810-2.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-810-2.plan
@@ -3,7 +3,7 @@
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
         -- SORT_MERGE_EXCHANGE [$$l_returnflag(ASC), $$l_linestatus(ASC) ]  |PARTITIONED|
-          -- PRE_CLUSTERED_GROUP_BY[$$44, $$45]  |PARTITIONED|
+          -- PRE_CLUSTERED_GROUP_BY[$$104, $$105]  |PARTITIONED|
                   {
                     -- AGGREGATE  |LOCAL|
                       -- NESTED_TUPLE_SOURCE  |LOCAL|
@@ -13,9 +13,9 @@
                       -- NESTED_TUPLE_SOURCE  |LOCAL|
                   }
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-              -- STABLE_SORT [$$44(ASC), $$45(ASC)]  |PARTITIONED|
-                -- HASH_PARTITION_EXCHANGE [$$44, $$45]  |PARTITIONED|
-                  -- PRE_CLUSTERED_GROUP_BY[$$30, $$31]  |PARTITIONED|
+              -- STABLE_SORT [$$104(ASC), $$105(ASC)]  |PARTITIONED|
+                -- HASH_PARTITION_EXCHANGE [$$104, $$105]  |PARTITIONED|
+                  -- PRE_CLUSTERED_GROUP_BY[$$90, $$91]  |PARTITIONED|
                           {
                             -- AGGREGATE  |LOCAL|
                               -- STREAM_SELECT  |LOCAL|
@@ -27,7 +27,7 @@
                                 -- NESTED_TUPLE_SOURCE  |LOCAL|
                           }
                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                      -- STABLE_SORT [$$30(ASC), $$31(ASC)]  |PARTITIONED|
+                      -- STABLE_SORT [$$90(ASC), $$91(ASC)]  |PARTITIONED|
                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                           -- ASSIGN  |PARTITIONED|
                             -- STREAM_PROJECT  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-810-3.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-810-3.plan
index 9a7df35..56a7aca 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-810-3.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-810-3.plan
@@ -3,7 +3,7 @@
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
         -- SORT_MERGE_EXCHANGE [$$l_returnflag(ASC), $$l_linestatus(ASC) ]  |PARTITIONED|
-          -- PRE_CLUSTERED_GROUP_BY[$$44, $$45]  |PARTITIONED|
+          -- PRE_CLUSTERED_GROUP_BY[$$112, $$113]  |PARTITIONED|
                   {
                     -- AGGREGATE  |LOCAL|
                       -- NESTED_TUPLE_SOURCE  |LOCAL|
@@ -13,9 +13,9 @@
                       -- NESTED_TUPLE_SOURCE  |LOCAL|
                   }
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-              -- STABLE_SORT [$$44(ASC), $$45(ASC)]  |PARTITIONED|
-                -- HASH_PARTITION_EXCHANGE [$$44, $$45]  |PARTITIONED|
-                  -- PRE_CLUSTERED_GROUP_BY[$$31, $$32]  |PARTITIONED|
+              -- STABLE_SORT [$$112(ASC), $$113(ASC)]  |PARTITIONED|
+                -- HASH_PARTITION_EXCHANGE [$$112, $$113]  |PARTITIONED|
+                  -- PRE_CLUSTERED_GROUP_BY[$$99, $$100]  |PARTITIONED|
                           {
                             -- AGGREGATE  |LOCAL|
                               -- STREAM_SELECT  |LOCAL|
@@ -27,7 +27,7 @@
                                 -- NESTED_TUPLE_SOURCE  |LOCAL|
                           }
                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                      -- STABLE_SORT [$$31(ASC), $$32(ASC)]  |PARTITIONED|
+                      -- STABLE_SORT [$$99(ASC), $$100(ASC)]  |PARTITIONED|
                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                           -- ASSIGN  |PARTITIONED|
                             -- STREAM_PROJECT  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-810.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-810.plan
index 18b4218..76cd11f 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-810.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/query-ASTERIXDB-810.plan
@@ -3,7 +3,7 @@
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
         -- SORT_MERGE_EXCHANGE [$$l_returnflag(ASC), $$l_linestatus(ASC) ]  |PARTITIONED|
-          -- PRE_CLUSTERED_GROUP_BY[$$44, $$45]  |PARTITIONED|
+          -- PRE_CLUSTERED_GROUP_BY[$$120, $$121]  |PARTITIONED|
                   {
                     -- AGGREGATE  |LOCAL|
                       -- NESTED_TUPLE_SOURCE  |LOCAL|
@@ -13,9 +13,9 @@
                       -- NESTED_TUPLE_SOURCE  |LOCAL|
                   }
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-              -- STABLE_SORT [$$44(ASC), $$45(ASC)]  |PARTITIONED|
-                -- HASH_PARTITION_EXCHANGE [$$44, $$45]  |PARTITIONED|
-                  -- PRE_CLUSTERED_GROUP_BY[$$32, $$33]  |PARTITIONED|
+              -- STABLE_SORT [$$120(ASC), $$121(ASC)]  |PARTITIONED|
+                -- HASH_PARTITION_EXCHANGE [$$120, $$121]  |PARTITIONED|
+                  -- PRE_CLUSTERED_GROUP_BY[$$108, $$109]  |PARTITIONED|
                           {
                             -- AGGREGATE  |LOCAL|
                               -- STREAM_SELECT  |LOCAL|
@@ -27,7 +27,7 @@
                                 -- NESTED_TUPLE_SOURCE  |LOCAL|
                           }
                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                      -- STABLE_SORT [$$32(ASC), $$33(ASC)]  |PARTITIONED|
+                      -- STABLE_SORT [$$108(ASC), $$109(ASC)]  |PARTITIONED|
                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                           -- ASSIGN  |PARTITIONED|
                             -- STREAM_PROJECT  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/exists.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/exists.plan
index 3f47dac..1ae1e60 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/exists.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/exists.plan
@@ -3,13 +3,13 @@
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
         -- SORT_MERGE_EXCHANGE [$$cntrycode(ASC) ]  |PARTITIONED|
-          -- SORT_GROUP_BY[$$78]  |PARTITIONED|
+          -- SORT_GROUP_BY[$$146]  |PARTITIONED|
                   {
                     -- AGGREGATE  |LOCAL|
                       -- NESTED_TUPLE_SOURCE  |LOCAL|
                   }
-            -- HASH_PARTITION_EXCHANGE [$$78]  |PARTITIONED|
-              -- SORT_GROUP_BY[$$55]  |PARTITIONED|
+            -- HASH_PARTITION_EXCHANGE [$$146]  |PARTITIONED|
+              -- SORT_GROUP_BY[$$123]  |PARTITIONED|
                       {
                         -- AGGREGATE  |LOCAL|
                           -- NESTED_TUPLE_SOURCE  |LOCAL|
@@ -21,25 +21,25 @@
                         -- STREAM_SELECT  |PARTITIONED|
                           -- STREAM_PROJECT  |PARTITIONED|
                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                              -- SORT_GROUP_BY[$$75]  |PARTITIONED|
+                              -- SORT_GROUP_BY[$$143]  |PARTITIONED|
                                       {
                                         -- AGGREGATE  |LOCAL|
                                           -- NESTED_TUPLE_SOURCE  |LOCAL|
                                       }
-                                -- HASH_PARTITION_EXCHANGE [$$75]  |PARTITIONED|
-                                  -- PRE_CLUSTERED_GROUP_BY[$$69]  |PARTITIONED|
+                                -- HASH_PARTITION_EXCHANGE [$$143]  |PARTITIONED|
+                                  -- PRE_CLUSTERED_GROUP_BY[$$137]  |PARTITIONED|
                                           {
                                             -- AGGREGATE  |LOCAL|
                                               -- STREAM_SELECT  |LOCAL|
                                                 -- NESTED_TUPLE_SOURCE  |LOCAL|
                                           }
                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                      -- STABLE_SORT [$$69(ASC)]  |PARTITIONED|
+                                      -- STABLE_SORT [$$137(ASC)]  |PARTITIONED|
                                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                           -- STREAM_PROJECT  |PARTITIONED|
                                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                              -- HYBRID_HASH_JOIN [$$64][$$61]  |PARTITIONED|
-                                                -- HASH_PARTITION_EXCHANGE [$$64]  |PARTITIONED|
+                                              -- HYBRID_HASH_JOIN [$$132][$$129]  |PARTITIONED|
+                                                -- HASH_PARTITION_EXCHANGE [$$132]  |PARTITIONED|
                                                   -- ASSIGN  |PARTITIONED|
                                                     -- STREAM_PROJECT  |PARTITIONED|
                                                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
@@ -66,7 +66,7 @@
                                                                                 -- DATASOURCE_SCAN  |PARTITIONED|
                                                                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                     -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                                                -- HASH_PARTITION_EXCHANGE [$$61]  |PARTITIONED|
+                                                -- HASH_PARTITION_EXCHANGE [$$129]  |PARTITIONED|
                                                   -- ASSIGN  |PARTITIONED|
                                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                       -- DATASOURCE_SCAN  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/in.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/in.plan
index 8276df2..7f916f16 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/in.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/in.plan
@@ -2,13 +2,13 @@
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
-        -- SORT_MERGE_EXCHANGE [$$26(ASC) ]  |PARTITIONED|
-          -- STABLE_SORT [$$26(ASC)]  |PARTITIONED|
+        -- SORT_MERGE_EXCHANGE [$$40(ASC) ]  |PARTITIONED|
+          -- STABLE_SORT [$$40(ASC)]  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
               -- STREAM_PROJECT  |PARTITIONED|
                 -- STREAM_SELECT  |PARTITIONED|
                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                    -- PRE_CLUSTERED_GROUP_BY[$$19]  |PARTITIONED|
+                    -- PRE_CLUSTERED_GROUP_BY[$$33]  |PARTITIONED|
                             {
                               -- AGGREGATE  |LOCAL|
                                 -- STREAM_SELECT  |LOCAL|
@@ -17,7 +17,7 @@
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                         -- STREAM_PROJECT  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                            -- HYBRID_HASH_JOIN [$$19][$$7]  |PARTITIONED|
+                            -- HYBRID_HASH_JOIN [$$33][$$21]  |PARTITIONED|
                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                 -- STREAM_PROJECT  |PARTITIONED|
                                   -- STREAM_SELECT  |PARTITIONED|
@@ -25,7 +25,7 @@
                                       -- DATASOURCE_SCAN  |PARTITIONED|
                                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                           -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                              -- HASH_PARTITION_EXCHANGE [$$7]  |PARTITIONED|
+                              -- HASH_PARTITION_EXCHANGE [$$21]  |PARTITIONED|
                                 -- STREAM_PROJECT  |PARTITIONED|
                                   -- ASSIGN  |PARTITIONED|
                                     -- STREAM_PROJECT  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/in_correlated.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/in_correlated.plan
index 268b914..7f0bb3b 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/in_correlated.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/in_correlated.plan
@@ -2,13 +2,13 @@
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
-        -- SORT_MERGE_EXCHANGE [$$31(ASC) ]  |PARTITIONED|
-          -- STABLE_SORT [$$31(ASC)]  |PARTITIONED|
+        -- SORT_MERGE_EXCHANGE [$$45(ASC) ]  |PARTITIONED|
+          -- STABLE_SORT [$$45(ASC)]  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
               -- STREAM_PROJECT  |PARTITIONED|
                 -- STREAM_SELECT  |PARTITIONED|
                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                    -- PRE_CLUSTERED_GROUP_BY[$$23]  |PARTITIONED|
+                    -- PRE_CLUSTERED_GROUP_BY[$$37]  |PARTITIONED|
                             {
                               -- AGGREGATE  |LOCAL|
                                 -- STREAM_SELECT  |LOCAL|
@@ -22,7 +22,7 @@
                                       -- NESTED_TUPLE_SOURCE  |LOCAL|
                             }
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                        -- HYBRID_HASH_JOIN [$$23][$$22]  |PARTITIONED|
+                        -- HYBRID_HASH_JOIN [$$37][$$36]  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                             -- STREAM_SELECT  |PARTITIONED|
                               -- ASSIGN  |PARTITIONED|
@@ -30,7 +30,7 @@
                                   -- DATASOURCE_SCAN  |PARTITIONED|
                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                       -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                          -- HASH_PARTITION_EXCHANGE [$$22]  |PARTITIONED|
+                          -- HASH_PARTITION_EXCHANGE [$$36]  |PARTITIONED|
                             -- STREAM_PROJECT  |PARTITIONED|
                               -- ASSIGN  |PARTITIONED|
                                 -- STREAM_PROJECT  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/not_exists.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/not_exists.plan
index 311ab6d..7ef3e37 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/not_exists.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/not_exists.plan
@@ -3,13 +3,13 @@
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
         -- SORT_MERGE_EXCHANGE [$$cntrycode(ASC) ]  |PARTITIONED|
-          -- SORT_GROUP_BY[$$79]  |PARTITIONED|
+          -- SORT_GROUP_BY[$$147]  |PARTITIONED|
                   {
                     -- AGGREGATE  |LOCAL|
                       -- NESTED_TUPLE_SOURCE  |LOCAL|
                   }
-            -- HASH_PARTITION_EXCHANGE [$$79]  |PARTITIONED|
-              -- SORT_GROUP_BY[$$56]  |PARTITIONED|
+            -- HASH_PARTITION_EXCHANGE [$$147]  |PARTITIONED|
+              -- SORT_GROUP_BY[$$124]  |PARTITIONED|
                       {
                         -- AGGREGATE  |LOCAL|
                           -- NESTED_TUPLE_SOURCE  |LOCAL|
@@ -21,25 +21,25 @@
                         -- STREAM_SELECT  |PARTITIONED|
                           -- STREAM_PROJECT  |PARTITIONED|
                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                              -- SORT_GROUP_BY[$$76]  |PARTITIONED|
+                              -- SORT_GROUP_BY[$$144]  |PARTITIONED|
                                       {
                                         -- AGGREGATE  |LOCAL|
                                           -- NESTED_TUPLE_SOURCE  |LOCAL|
                                       }
-                                -- HASH_PARTITION_EXCHANGE [$$76]  |PARTITIONED|
-                                  -- PRE_CLUSTERED_GROUP_BY[$$70]  |PARTITIONED|
+                                -- HASH_PARTITION_EXCHANGE [$$144]  |PARTITIONED|
+                                  -- PRE_CLUSTERED_GROUP_BY[$$138]  |PARTITIONED|
                                           {
                                             -- AGGREGATE  |LOCAL|
                                               -- STREAM_SELECT  |LOCAL|
                                                 -- NESTED_TUPLE_SOURCE  |LOCAL|
                                           }
                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                      -- STABLE_SORT [$$70(ASC)]  |PARTITIONED|
+                                      -- STABLE_SORT [$$138(ASC)]  |PARTITIONED|
                                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                           -- STREAM_PROJECT  |PARTITIONED|
                                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                              -- HYBRID_HASH_JOIN [$$65][$$62]  |PARTITIONED|
-                                                -- HASH_PARTITION_EXCHANGE [$$65]  |PARTITIONED|
+                                              -- HYBRID_HASH_JOIN [$$133][$$130]  |PARTITIONED|
+                                                -- HASH_PARTITION_EXCHANGE [$$133]  |PARTITIONED|
                                                   -- ASSIGN  |PARTITIONED|
                                                     -- STREAM_PROJECT  |PARTITIONED|
                                                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
@@ -66,7 +66,7 @@
                                                                                 -- DATASOURCE_SCAN  |PARTITIONED|
                                                                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                     -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                                                -- HASH_PARTITION_EXCHANGE [$$62]  |PARTITIONED|
+                                                -- HASH_PARTITION_EXCHANGE [$$130]  |PARTITIONED|
                                                   -- ASSIGN  |PARTITIONED|
                                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                       -- DATASOURCE_SCAN  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/query-ASTERIXDB-1572.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/query-ASTERIXDB-1572.plan
index 6a9d39c..ec9715e 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/query-ASTERIXDB-1572.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/subquery/query-ASTERIXDB-1572.plan
@@ -5,20 +5,20 @@
         -- STREAM_PROJECT  |PARTITIONED|
           -- STREAM_SELECT  |PARTITIONED|
             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-              -- PRE_CLUSTERED_GROUP_BY[$$44]  |PARTITIONED|
+              -- PRE_CLUSTERED_GROUP_BY[$$58]  |PARTITIONED|
                       {
                         -- AGGREGATE  |LOCAL|
                           -- STREAM_SELECT  |LOCAL|
                             -- NESTED_TUPLE_SOURCE  |LOCAL|
                       }
                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                  -- STABLE_SORT [$$44(ASC)]  |PARTITIONED|
+                  -- STABLE_SORT [$$58(ASC)]  |PARTITIONED|
                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                       -- STREAM_PROJECT  |PARTITIONED|
                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                          -- HYBRID_HASH_JOIN [$$44][$#4]  |PARTITIONED|
+                          -- HYBRID_HASH_JOIN [$$58][$#4]  |PARTITIONED|
                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                              -- PRE_CLUSTERED_GROUP_BY[$$42]  |PARTITIONED|
+                              -- PRE_CLUSTERED_GROUP_BY[$$56]  |PARTITIONED|
                                       {
                                         -- AGGREGATE  |LOCAL|
                                           -- STREAM_SELECT  |LOCAL|
@@ -27,22 +27,22 @@
                                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                   -- STREAM_PROJECT  |PARTITIONED|
                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                      -- HYBRID_HASH_JOIN [$$42][$#3]  |PARTITIONED|
+                                      -- HYBRID_HASH_JOIN [$$56][$#3]  |PARTITIONED|
                                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                          -- PRE_CLUSTERED_GROUP_BY[$$40]  |PARTITIONED|
+                                          -- PRE_CLUSTERED_GROUP_BY[$$54]  |PARTITIONED|
                                                   {
                                                     -- AGGREGATE  |LOCAL|
                                                       -- STREAM_SELECT  |LOCAL|
                                                         -- NESTED_TUPLE_SOURCE  |LOCAL|
                                                   }
                                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                              -- STABLE_SORT [$$40(ASC)]  |PARTITIONED|
+                                              -- STABLE_SORT [$$54(ASC)]  |PARTITIONED|
                                                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                   -- STREAM_PROJECT  |PARTITIONED|
                                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                      -- HYBRID_HASH_JOIN [$$40][$#2]  |PARTITIONED|
+                                                      -- HYBRID_HASH_JOIN [$$54][$#2]  |PARTITIONED|
                                                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                          -- PRE_CLUSTERED_GROUP_BY[$$33]  |PARTITIONED|
+                                                          -- PRE_CLUSTERED_GROUP_BY[$$47]  |PARTITIONED|
                                                                   {
                                                                     -- AGGREGATE  |LOCAL|
                                                                       -- STREAM_SELECT  |LOCAL|
@@ -51,7 +51,7 @@
                                                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                               -- STREAM_PROJECT  |PARTITIONED|
                                                                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                                  -- HYBRID_HASH_JOIN [$$33][$#1]  |PARTITIONED|
+                                                                  -- HYBRID_HASH_JOIN [$$47][$#1]  |PARTITIONED|
                                                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                       -- STREAM_PROJECT  |PARTITIONED|
                                                                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1580.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1580.plan
index 78d1566..a647c7c 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1580.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1580.plan
@@ -4,21 +4,21 @@
       -- STREAM_PROJECT  |PARTITIONED|
         -- ASSIGN  |PARTITIONED|
           -- STREAM_PROJECT  |PARTITIONED|
-            -- SORT_MERGE_EXCHANGE [$$59(ASC) ]  |PARTITIONED|
+            -- SORT_MERGE_EXCHANGE [$$110(ASC) ]  |PARTITIONED|
               -- STREAM_LIMIT  |PARTITIONED|
                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                  -- STABLE_SORT [topK: 100] [$$59(ASC)]  |PARTITIONED|
+                  -- STABLE_SORT [topK: 100] [$$110(ASC)]  |PARTITIONED|
                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                       -- STREAM_PROJECT  |PARTITIONED|
                         -- STREAM_SELECT  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                            -- SORT_GROUP_BY[$$69]  |PARTITIONED|
+                            -- SORT_GROUP_BY[$$120]  |PARTITIONED|
                                     {
                                       -- AGGREGATE  |LOCAL|
                                         -- NESTED_TUPLE_SOURCE  |LOCAL|
                                     }
-                              -- HASH_PARTITION_EXCHANGE [$$69]  |PARTITIONED|
-                                -- SORT_GROUP_BY[$$47]  |PARTITIONED|
+                              -- HASH_PARTITION_EXCHANGE [$$120]  |PARTITIONED|
+                                -- SORT_GROUP_BY[$$98]  |PARTITIONED|
                                         {
                                           -- AGGREGATE  |LOCAL|
                                             -- NESTED_TUPLE_SOURCE  |LOCAL|
@@ -26,33 +26,33 @@
                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                     -- STREAM_PROJECT  |PARTITIONED|
                                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                        -- HYBRID_HASH_JOIN [$$51][$$54]  |PARTITIONED|
-                                          -- HASH_PARTITION_EXCHANGE [$$51]  |PARTITIONED|
+                                        -- HYBRID_HASH_JOIN [$$102][$$105]  |PARTITIONED|
+                                          -- HASH_PARTITION_EXCHANGE [$$102]  |PARTITIONED|
                                             -- STREAM_PROJECT  |PARTITIONED|
                                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                -- HYBRID_HASH_JOIN [$$60][$$53]  |PARTITIONED|
-                                                  -- HASH_PARTITION_EXCHANGE [$$60]  |PARTITIONED|
+                                                -- HYBRID_HASH_JOIN [$$111][$$104]  |PARTITIONED|
+                                                  -- HASH_PARTITION_EXCHANGE [$$111]  |PARTITIONED|
                                                     -- STREAM_PROJECT  |PARTITIONED|
                                                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                        -- HYBRID_HASH_JOIN [$$50][$$65]  |PARTITIONED|
-                                                          -- HASH_PARTITION_EXCHANGE [$$50]  |PARTITIONED|
+                                                        -- HYBRID_HASH_JOIN [$$101][$$116]  |PARTITIONED|
+                                                          -- HASH_PARTITION_EXCHANGE [$$101]  |PARTITIONED|
                                                             -- STREAM_PROJECT  |PARTITIONED|
                                                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                                -- HYBRID_HASH_JOIN [$$49][$$63]  |PARTITIONED|
+                                                                -- HYBRID_HASH_JOIN [$$100][$$114]  |PARTITIONED|
                                                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                     -- ASSIGN  |PARTITIONED|
                                                                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                         -- DATASOURCE_SCAN  |PARTITIONED|
                                                                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                             -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                                                                  -- HASH_PARTITION_EXCHANGE [$$63]  |PARTITIONED|
+                                                                  -- HASH_PARTITION_EXCHANGE [$$114]  |PARTITIONED|
                                                                     -- STREAM_PROJECT  |PARTITIONED|
                                                                       -- ASSIGN  |PARTITIONED|
                                                                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                           -- DATASOURCE_SCAN  |PARTITIONED|
                                                                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                               -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                                                          -- HASH_PARTITION_EXCHANGE [$$65]  |PARTITIONED|
+                                                          -- HASH_PARTITION_EXCHANGE [$$116]  |PARTITIONED|
                                                             -- STREAM_PROJECT  |PARTITIONED|
                                                               -- ASSIGN  |PARTITIONED|
                                                                 -- STREAM_PROJECT  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1581-correlated.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1581-correlated.plan
index babbeeb..906e52f 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1581-correlated.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1581-correlated.plan
@@ -8,7 +8,7 @@
               -- ASSIGN  |PARTITIONED|
                 -- STREAM_PROJECT  |PARTITIONED|
                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                    -- PRE_CLUSTERED_GROUP_BY[$$95]  |PARTITIONED|
+                    -- PRE_CLUSTERED_GROUP_BY[$$144]  |PARTITIONED|
                             {
                               -- AGGREGATE  |LOCAL|
                                 -- AGGREGATE  |LOCAL|
@@ -20,9 +20,9 @@
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                         -- STREAM_PROJECT  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                            -- HYBRID_HASH_JOIN [$$95][$$96]  |PARTITIONED|
+                            -- HYBRID_HASH_JOIN [$$144][$$145]  |PARTITIONED|
                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                -- PRE_CLUSTERED_GROUP_BY[$$83]  |PARTITIONED|
+                                -- PRE_CLUSTERED_GROUP_BY[$$132]  |PARTITIONED|
                                         {
                                           -- AGGREGATE  |LOCAL|
                                             -- AGGREGATE  |LOCAL|
@@ -32,13 +32,13 @@
                                                     -- NESTED_TUPLE_SOURCE  |LOCAL|
                                         }
                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                    -- STABLE_SORT [$$83(ASC)]  |PARTITIONED|
+                                    -- STABLE_SORT [$$132(ASC)]  |PARTITIONED|
                                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                         -- STREAM_PROJECT  |PARTITIONED|
                                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                            -- HYBRID_HASH_JOIN [$$83][$$84]  |PARTITIONED|
+                                            -- HYBRID_HASH_JOIN [$$132][$$133]  |PARTITIONED|
                                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                -- PRE_CLUSTERED_GROUP_BY[$$63]  |PARTITIONED|
+                                                -- PRE_CLUSTERED_GROUP_BY[$$112]  |PARTITIONED|
                                                         {
                                                           -- AGGREGATE  |LOCAL|
                                                             -- AGGREGATE  |LOCAL|
@@ -48,7 +48,7 @@
                                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                     -- STREAM_PROJECT  |PARTITIONED|
                                                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                        -- HYBRID_HASH_JOIN [$$63][$$73]  |PARTITIONED|
+                                                        -- HYBRID_HASH_JOIN [$$112][$$122]  |PARTITIONED|
                                                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                             -- STREAM_PROJECT  |PARTITIONED|
                                                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
@@ -66,7 +66,7 @@
                                                               -- ASSIGN  |PARTITIONED|
                                                                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                   -- REPLICATE  |PARTITIONED|
-                                                                    -- HASH_PARTITION_EXCHANGE [$$120]  |PARTITIONED|
+                                                                    -- HASH_PARTITION_EXCHANGE [$$169]  |PARTITIONED|
                                                                       -- ASSIGN  |PARTITIONED|
                                                                         -- STREAM_PROJECT  |PARTITIONED|
                                                                           -- ASSIGN  |PARTITIONED|
@@ -78,18 +78,18 @@
                                                                                       -- DATASOURCE_SCAN  |PARTITIONED|
                                                                                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                           -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                                              -- HASH_PARTITION_EXCHANGE [$$84]  |PARTITIONED|
+                                              -- HASH_PARTITION_EXCHANGE [$$133]  |PARTITIONED|
                                                 -- ASSIGN  |PARTITIONED|
                                                   -- STREAM_PROJECT  |PARTITIONED|
                                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                      -- HYBRID_HASH_JOIN [$$77][$$76]  |PARTITIONED|
-                                                        -- HASH_PARTITION_EXCHANGE [$$77]  |PARTITIONED|
+                                                      -- HYBRID_HASH_JOIN [$$126][$$125]  |PARTITIONED|
+                                                        -- HASH_PARTITION_EXCHANGE [$$126]  |PARTITIONED|
                                                           -- STREAM_PROJECT  |PARTITIONED|
                                                             -- ASSIGN  |PARTITIONED|
                                                               -- STREAM_PROJECT  |PARTITIONED|
                                                                 -- STREAM_SELECT  |PARTITIONED|
                                                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                                    -- PRE_CLUSTERED_GROUP_BY[$$85]  |PARTITIONED|
+                                                                    -- PRE_CLUSTERED_GROUP_BY[$$134]  |PARTITIONED|
                                                                             {
                                                                               -- AGGREGATE  |LOCAL|
                                                                                 -- AGGREGATE  |LOCAL|
@@ -99,7 +99,7 @@
                                                                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                         -- STREAM_PROJECT  |PARTITIONED|
                                                                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                                            -- HYBRID_HASH_JOIN [$$85][$$87]  |PARTITIONED|
+                                                                            -- HYBRID_HASH_JOIN [$$134][$$136]  |PARTITIONED|
                                                                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                 -- STREAM_PROJECT  |PARTITIONED|
                                                                                   -- ASSIGN  |PARTITIONED|
@@ -115,7 +115,7 @@
                                                                                   -- ASSIGN  |PARTITIONED|
                                                                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                       -- REPLICATE  |PARTITIONED|
-                                                                                        -- HASH_PARTITION_EXCHANGE [$$120]  |PARTITIONED|
+                                                                                        -- HASH_PARTITION_EXCHANGE [$$169]  |PARTITIONED|
                                                                                           -- ASSIGN  |PARTITIONED|
                                                                                             -- STREAM_PROJECT  |PARTITIONED|
                                                                                               -- ASSIGN  |PARTITIONED|
@@ -127,7 +127,7 @@
                                                                                                           -- DATASOURCE_SCAN  |PARTITIONED|
                                                                                                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                                               -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                                                        -- HASH_PARTITION_EXCHANGE [$$76]  |PARTITIONED|
+                                                        -- HASH_PARTITION_EXCHANGE [$$125]  |PARTITIONED|
                                                           -- STREAM_PROJECT  |PARTITIONED|
                                                             -- ASSIGN  |PARTITIONED|
                                                               -- STREAM_PROJECT  |PARTITIONED|
@@ -140,13 +140,13 @@
                                                                             -- DATASOURCE_SCAN  |PARTITIONED|
                                                                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                 -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                              -- HASH_PARTITION_EXCHANGE [$$96]  |PARTITIONED|
+                              -- HASH_PARTITION_EXCHANGE [$$145]  |PARTITIONED|
                                 -- ASSIGN  |PARTITIONED|
                                   -- STREAM_PROJECT  |PARTITIONED|
                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                      -- HYBRID_HASH_JOIN [$$79][$$78]  |PARTITIONED|
-                                        -- HASH_PARTITION_EXCHANGE [$$79]  |PARTITIONED|
-                                          -- PRE_CLUSTERED_GROUP_BY[$$97]  |PARTITIONED|
+                                      -- HYBRID_HASH_JOIN [$$128][$$127]  |PARTITIONED|
+                                        -- HASH_PARTITION_EXCHANGE [$$128]  |PARTITIONED|
+                                          -- PRE_CLUSTERED_GROUP_BY[$$146]  |PARTITIONED|
                                                   {
                                                     -- AGGREGATE  |LOCAL|
                                                       -- AGGREGATE  |LOCAL|
@@ -155,18 +155,18 @@
                                                             -- NESTED_TUPLE_SOURCE  |LOCAL|
                                                   }
                                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                              -- STABLE_SORT [$$97(ASC)]  |PARTITIONED|
+                                              -- STABLE_SORT [$$146(ASC)]  |PARTITIONED|
                                                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                   -- STREAM_PROJECT  |PARTITIONED|
                                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                      -- HYBRID_HASH_JOIN [$$97][$$100]  |PARTITIONED|
+                                                      -- HYBRID_HASH_JOIN [$$146][$$149]  |PARTITIONED|
                                                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                           -- STREAM_PROJECT  |PARTITIONED|
                                                             -- STREAM_SELECT  |PARTITIONED|
                                                               -- STREAM_PROJECT  |PARTITIONED|
                                                                 -- ASSIGN  |PARTITIONED|
                                                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                                    -- PRE_CLUSTERED_GROUP_BY[$$101]  |PARTITIONED|
+                                                                    -- PRE_CLUSTERED_GROUP_BY[$$150]  |PARTITIONED|
                                                                             {
                                                                               -- AGGREGATE  |LOCAL|
                                                                                 -- AGGREGATE  |LOCAL|
@@ -176,7 +176,7 @@
                                                                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                         -- STREAM_PROJECT  |PARTITIONED|
                                                                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                                            -- HYBRID_HASH_JOIN [$$101][$$102]  |PARTITIONED|
+                                                                            -- HYBRID_HASH_JOIN [$$150][$$151]  |PARTITIONED|
                                                                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                 -- STREAM_PROJECT  |PARTITIONED|
                                                                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
@@ -194,7 +194,7 @@
                                                                                   -- ASSIGN  |PARTITIONED|
                                                                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                       -- REPLICATE  |PARTITIONED|
-                                                                                        -- HASH_PARTITION_EXCHANGE [$$120]  |PARTITIONED|
+                                                                                        -- HASH_PARTITION_EXCHANGE [$$169]  |PARTITIONED|
                                                                                           -- ASSIGN  |PARTITIONED|
                                                                                             -- STREAM_PROJECT  |PARTITIONED|
                                                                                               -- ASSIGN  |PARTITIONED|
@@ -206,18 +206,18 @@
                                                                                                           -- DATASOURCE_SCAN  |PARTITIONED|
                                                                                                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                                               -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                                                        -- HASH_PARTITION_EXCHANGE [$$100]  |PARTITIONED|
+                                                        -- HASH_PARTITION_EXCHANGE [$$149]  |PARTITIONED|
                                                           -- ASSIGN  |PARTITIONED|
                                                             -- STREAM_PROJECT  |PARTITIONED|
                                                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                                -- HYBRID_HASH_JOIN [$$114][$$113]  |PARTITIONED|
-                                                                  -- HASH_PARTITION_EXCHANGE [$$114]  |PARTITIONED|
+                                                                -- HYBRID_HASH_JOIN [$$163][$$162]  |PARTITIONED|
+                                                                  -- HASH_PARTITION_EXCHANGE [$$163]  |PARTITIONED|
                                                                     -- STREAM_PROJECT  |PARTITIONED|
                                                                       -- ASSIGN  |PARTITIONED|
                                                                         -- STREAM_PROJECT  |PARTITIONED|
                                                                           -- STREAM_SELECT  |PARTITIONED|
                                                                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                                              -- PRE_CLUSTERED_GROUP_BY[$$119]  |PARTITIONED|
+                                                                              -- PRE_CLUSTERED_GROUP_BY[$$168]  |PARTITIONED|
                                                                                       {
                                                                                         -- AGGREGATE  |LOCAL|
                                                                                           -- AGGREGATE  |LOCAL|
@@ -227,7 +227,7 @@
                                                                                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                   -- STREAM_PROJECT  |PARTITIONED|
                                                                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                                                      -- HYBRID_HASH_JOIN [$$119][$$120]  |PARTITIONED|
+                                                                                      -- HYBRID_HASH_JOIN [$$168][$$169]  |PARTITIONED|
                                                                                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                           -- REPLICATE  |PARTITIONED|
                                                                                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
@@ -237,7 +237,7 @@
                                                                                                     -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
                                                                                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                           -- REPLICATE  |PARTITIONED|
-                                                                                            -- HASH_PARTITION_EXCHANGE [$$120]  |PARTITIONED|
+                                                                                            -- HASH_PARTITION_EXCHANGE [$$169]  |PARTITIONED|
                                                                                               -- ASSIGN  |PARTITIONED|
                                                                                                 -- STREAM_PROJECT  |PARTITIONED|
                                                                                                   -- ASSIGN  |PARTITIONED|
@@ -249,7 +249,7 @@
                                                                                                               -- DATASOURCE_SCAN  |PARTITIONED|
                                                                                                                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                                                   -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                                                                  -- HASH_PARTITION_EXCHANGE [$$113]  |PARTITIONED|
+                                                                  -- HASH_PARTITION_EXCHANGE [$$162]  |PARTITIONED|
                                                                     -- STREAM_PROJECT  |PARTITIONED|
                                                                       -- ASSIGN  |PARTITIONED|
                                                                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
@@ -260,7 +260,7 @@
                                                                                   -- DATASOURCE_SCAN  |PARTITIONED|
                                                                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                       -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                                        -- HASH_PARTITION_EXCHANGE [$$78]  |PARTITIONED|
+                                        -- HASH_PARTITION_EXCHANGE [$$127]  |PARTITIONED|
                                           -- STREAM_PROJECT  |PARTITIONED|
                                             -- ASSIGN  |PARTITIONED|
                                               -- STREAM_PROJECT  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1581.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1581.plan
index f914055..c335414 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1581.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1581.plan
@@ -16,7 +16,7 @@
                 -- STREAM_PROJECT  |PARTITIONED|
                   -- ASSIGN  |PARTITIONED|
                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                      -- PRE_CLUSTERED_GROUP_BY[$$92]  |PARTITIONED|
+                      -- PRE_CLUSTERED_GROUP_BY[$$141]  |PARTITIONED|
                               {
                                 -- AGGREGATE  |LOCAL|
                                   -- AGGREGATE  |LOCAL|
@@ -28,9 +28,9 @@
                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                           -- STREAM_PROJECT  |PARTITIONED|
                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                              -- HYBRID_HASH_JOIN [$$92][$$93]  |PARTITIONED|
+                              -- HYBRID_HASH_JOIN [$$141][$$142]  |PARTITIONED|
                                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                  -- PRE_CLUSTERED_GROUP_BY[$$32]  |PARTITIONED|
+                                  -- PRE_CLUSTERED_GROUP_BY[$$77]  |PARTITIONED|
                                           {
                                             -- AGGREGATE  |LOCAL|
                                               -- AGGREGATE  |LOCAL|
@@ -40,12 +40,12 @@
                                                       -- NESTED_TUPLE_SOURCE  |LOCAL|
                                           }
                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                      -- STABLE_SORT [$$32(ASC)]  |PARTITIONED|
+                                      -- STABLE_SORT [$$77(ASC)]  |PARTITIONED|
                                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                           -- STREAM_PROJECT  |PARTITIONED|
                                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                              -- HYBRID_HASH_JOIN [$$32][$$85]  |PARTITIONED|
-                                                -- HASH_PARTITION_EXCHANGE [$$32]  |PARTITIONED|
+                                              -- HYBRID_HASH_JOIN [$$77][$$134]  |PARTITIONED|
+                                                -- HASH_PARTITION_EXCHANGE [$$77]  |PARTITIONED|
                                                   -- STREAM_PROJECT  |UNPARTITIONED|
                                                     -- ASSIGN  |UNPARTITIONED|
                                                       -- ONE_TO_ONE_EXCHANGE  |UNPARTITIONED|
@@ -63,7 +63,7 @@
                                                                               -- DATASOURCE_SCAN  |PARTITIONED|
                                                                                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                   -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                                                -- HASH_PARTITION_EXCHANGE [$$85]  |PARTITIONED|
+                                                -- HASH_PARTITION_EXCHANGE [$$134]  |PARTITIONED|
                                                   -- ASSIGN  |PARTITIONED|
                                                     -- STREAM_PROJECT  |PARTITIONED|
                                                       -- STREAM_SELECT  |PARTITIONED|
@@ -94,7 +94,7 @@
                                                                                                         -- DATASOURCE_SCAN  |PARTITIONED|
                                                                                                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                                             -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                                -- HASH_PARTITION_EXCHANGE [$$93]  |PARTITIONED|
+                                -- HASH_PARTITION_EXCHANGE [$$142]  |PARTITIONED|
                                   -- ASSIGN  |PARTITIONED|
                                     -- STREAM_PROJECT  |PARTITIONED|
                                       -- STREAM_SELECT  |PARTITIONED|
@@ -108,7 +108,7 @@
                                                       -- STREAM_SELECT  |PARTITIONED|
                                                         -- ASSIGN  |PARTITIONED|
                                                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                            -- PRE_CLUSTERED_GROUP_BY[$$94]  |PARTITIONED|
+                                                            -- PRE_CLUSTERED_GROUP_BY[$$143]  |PARTITIONED|
                                                                     {
                                                                       -- AGGREGATE  |LOCAL|
                                                                         -- AGGREGATE  |LOCAL|
@@ -117,12 +117,12 @@
                                                                               -- NESTED_TUPLE_SOURCE  |LOCAL|
                                                                     }
                                                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                                -- STABLE_SORT [$$94(ASC)]  |PARTITIONED|
+                                                                -- STABLE_SORT [$$143(ASC)]  |PARTITIONED|
                                                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                     -- STREAM_PROJECT  |PARTITIONED|
                                                                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                                        -- HYBRID_HASH_JOIN [$$94][$$95]  |PARTITIONED|
-                                                                          -- HASH_PARTITION_EXCHANGE [$$94]  |PARTITIONED|
+                                                                        -- HYBRID_HASH_JOIN [$$143][$$144]  |PARTITIONED|
+                                                                          -- HASH_PARTITION_EXCHANGE [$$143]  |PARTITIONED|
                                                                             -- STREAM_PROJECT  |UNPARTITIONED|
                                                                               -- ASSIGN  |UNPARTITIONED|
                                                                                 -- ONE_TO_ONE_EXCHANGE  |UNPARTITIONED|
@@ -140,7 +140,7 @@
                                                                                                         -- DATASOURCE_SCAN  |PARTITIONED|
                                                                                                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                                             -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                                                                          -- HASH_PARTITION_EXCHANGE [$$95]  |PARTITIONED|
+                                                                          -- HASH_PARTITION_EXCHANGE [$$144]  |PARTITIONED|
                                                                             -- ASSIGN  |PARTITIONED|
                                                                               -- STREAM_PROJECT  |PARTITIONED|
                                                                                 -- STREAM_SELECT  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1591.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1591.plan
index 90d7b02..4925110 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1591.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1591.plan
@@ -4,76 +4,76 @@
       -- STREAM_PROJECT  |PARTITIONED|
         -- ASSIGN  |PARTITIONED|
           -- STREAM_PROJECT  |PARTITIONED|
-            -- SORT_MERGE_EXCHANGE [$$112(ASC) ]  |PARTITIONED|
+            -- SORT_MERGE_EXCHANGE [$$168(ASC) ]  |PARTITIONED|
               -- STREAM_LIMIT  |PARTITIONED|
                 -- STREAM_PROJECT  |PARTITIONED|
                   -- STREAM_SELECT  |PARTITIONED|
                     -- STREAM_PROJECT  |PARTITIONED|
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                        -- SORT_GROUP_BY[$$121, $$122]  |PARTITIONED|
+                        -- SORT_GROUP_BY[$$177, $$178]  |PARTITIONED|
                                 {
                                   -- AGGREGATE  |LOCAL|
                                     -- NESTED_TUPLE_SOURCE  |LOCAL|
                                 }
-                          -- HASH_PARTITION_EXCHANGE [$$121, $$122]  |PARTITIONED|
-                            -- PRE_CLUSTERED_GROUP_BY[$$109, $$110]  |PARTITIONED|
+                          -- HASH_PARTITION_EXCHANGE [$$177, $$178]  |PARTITIONED|
+                            -- PRE_CLUSTERED_GROUP_BY[$$165, $$166]  |PARTITIONED|
                                     {
                                       -- AGGREGATE  |LOCAL|
                                         -- STREAM_SELECT  |LOCAL|
                                           -- NESTED_TUPLE_SOURCE  |LOCAL|
                                     }
                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                -- STABLE_SORT [$$109(ASC), $$110(ASC)]  |PARTITIONED|
+                                -- STABLE_SORT [$$165(ASC), $$166(ASC)]  |PARTITIONED|
                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                     -- STREAM_PROJECT  |PARTITIONED|
                                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                        -- HYBRID_HASH_JOIN [$$109][$$91]  |PARTITIONED|
-                                          -- HASH_PARTITION_EXCHANGE [$$109]  |PARTITIONED|
-                                            -- SORT_GROUP_BY[$$118, $$119]  |PARTITIONED|
+                                        -- HYBRID_HASH_JOIN [$$165][$$147]  |PARTITIONED|
+                                          -- HASH_PARTITION_EXCHANGE [$$165]  |PARTITIONED|
+                                            -- SORT_GROUP_BY[$$174, $$175]  |PARTITIONED|
                                                     {
                                                       -- AGGREGATE  |LOCAL|
                                                         -- NESTED_TUPLE_SOURCE  |LOCAL|
                                                     }
-                                              -- HASH_PARTITION_EXCHANGE [$$118, $$119]  |PARTITIONED|
-                                                -- PRE_CLUSTERED_GROUP_BY[$$106, $$107]  |PARTITIONED|
+                                              -- HASH_PARTITION_EXCHANGE [$$174, $$175]  |PARTITIONED|
+                                                -- PRE_CLUSTERED_GROUP_BY[$$162, $$163]  |PARTITIONED|
                                                         {
                                                           -- AGGREGATE  |LOCAL|
                                                             -- STREAM_SELECT  |LOCAL|
                                                               -- NESTED_TUPLE_SOURCE  |LOCAL|
                                                         }
                                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                    -- STABLE_SORT [$$106(ASC), $$107(ASC)]  |PARTITIONED|
+                                                    -- STABLE_SORT [$$162(ASC), $$163(ASC)]  |PARTITIONED|
                                                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                         -- STREAM_PROJECT  |PARTITIONED|
                                                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                            -- HYBRID_HASH_JOIN [$$106][$$89]  |PARTITIONED|
-                                                              -- HASH_PARTITION_EXCHANGE [$$106]  |PARTITIONED|
+                                                            -- HYBRID_HASH_JOIN [$$162][$$145]  |PARTITIONED|
+                                                              -- HASH_PARTITION_EXCHANGE [$$162]  |PARTITIONED|
                                                                 -- STREAM_PROJECT  |PARTITIONED|
                                                                   -- STREAM_SELECT  |PARTITIONED|
                                                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                                      -- SORT_GROUP_BY[$$115, $$116]  |PARTITIONED|
+                                                                      -- SORT_GROUP_BY[$$171, $$172]  |PARTITIONED|
                                                                               {
                                                                                 -- AGGREGATE  |LOCAL|
                                                                                   -- NESTED_TUPLE_SOURCE  |LOCAL|
                                                                               }
-                                                                        -- HASH_PARTITION_EXCHANGE [$$115, $$116]  |PARTITIONED|
-                                                                          -- PRE_CLUSTERED_GROUP_BY[$$70, $$71]  |PARTITIONED|
+                                                                        -- HASH_PARTITION_EXCHANGE [$$171, $$172]  |PARTITIONED|
+                                                                          -- PRE_CLUSTERED_GROUP_BY[$$126, $$127]  |PARTITIONED|
                                                                                   {
                                                                                     -- AGGREGATE  |LOCAL|
                                                                                       -- STREAM_SELECT  |LOCAL|
                                                                                         -- NESTED_TUPLE_SOURCE  |LOCAL|
                                                                                   }
                                                                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                                              -- STABLE_SORT [$$70(ASC), $$71(ASC)]  |PARTITIONED|
+                                                                              -- STABLE_SORT [$$126(ASC), $$127(ASC)]  |PARTITIONED|
                                                                                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                   -- STREAM_PROJECT  |PARTITIONED|
                                                                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                                                      -- HYBRID_HASH_JOIN [$$70][$$87]  |PARTITIONED|
-                                                                                        -- HASH_PARTITION_EXCHANGE [$$70]  |PARTITIONED|
+                                                                                      -- HYBRID_HASH_JOIN [$$126][$$143]  |PARTITIONED|
+                                                                                        -- HASH_PARTITION_EXCHANGE [$$126]  |PARTITIONED|
                                                                                           -- STREAM_PROJECT  |PARTITIONED|
                                                                                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                                                              -- HYBRID_HASH_JOIN [$$81][$$71]  |PARTITIONED|
-                                                                                                -- HASH_PARTITION_EXCHANGE [$$81]  |PARTITIONED|
+                                                                                              -- HYBRID_HASH_JOIN [$$137][$$127]  |PARTITIONED|
+                                                                                                -- HASH_PARTITION_EXCHANGE [$$137]  |PARTITIONED|
                                                                                                   -- ASSIGN  |PARTITIONED|
                                                                                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                                       -- DATASOURCE_SCAN  |PARTITIONED|
@@ -83,12 +83,12 @@
                                                                                                   -- DATASOURCE_SCAN  |PARTITIONED|
                                                                                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                                       -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                                                                                        -- HASH_PARTITION_EXCHANGE [$$87]  |PARTITIONED|
+                                                                                        -- HASH_PARTITION_EXCHANGE [$$143]  |PARTITIONED|
                                                                                           -- ASSIGN  |PARTITIONED|
                                                                                             -- STREAM_PROJECT  |PARTITIONED|
                                                                                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                                                                -- HYBRID_HASH_JOIN [$$92][$$74]  |PARTITIONED|
-                                                                                                  -- HASH_PARTITION_EXCHANGE [$$92]  |PARTITIONED|
+                                                                                                -- HYBRID_HASH_JOIN [$$148][$$130]  |PARTITIONED|
+                                                                                                  -- HASH_PARTITION_EXCHANGE [$$148]  |PARTITIONED|
                                                                                                     -- ASSIGN  |PARTITIONED|
                                                                                                       -- STREAM_PROJECT  |PARTITIONED|
                                                                                                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
@@ -103,12 +103,12 @@
                                                                                                             -- DATASOURCE_SCAN  |PARTITIONED|
                                                                                                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                                                 -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                                                              -- HASH_PARTITION_EXCHANGE [$$89]  |PARTITIONED|
+                                                              -- HASH_PARTITION_EXCHANGE [$$145]  |PARTITIONED|
                                                                 -- ASSIGN  |PARTITIONED|
                                                                   -- STREAM_PROJECT  |PARTITIONED|
                                                                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                                      -- HYBRID_HASH_JOIN [$$94][$$77]  |PARTITIONED|
-                                                                        -- HASH_PARTITION_EXCHANGE [$$94]  |PARTITIONED|
+                                                                      -- HYBRID_HASH_JOIN [$$150][$$133]  |PARTITIONED|
+                                                                        -- HASH_PARTITION_EXCHANGE [$$150]  |PARTITIONED|
                                                                           -- ASSIGN  |PARTITIONED|
                                                                             -- STREAM_PROJECT  |PARTITIONED|
                                                                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
@@ -126,12 +126,12 @@
                                                                                         -- DATASOURCE_SCAN  |PARTITIONED|
                                                                                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                                                                             -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
-                                          -- HASH_PARTITION_EXCHANGE [$$91]  |PARTITIONED|
+                                          -- HASH_PARTITION_EXCHANGE [$$147]  |PARTITIONED|
                                             -- ASSIGN  |PARTITIONED|
                                               -- STREAM_PROJECT  |PARTITIONED|
                                                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                                                  -- HYBRID_HASH_JOIN [$$96][$$80]  |PARTITIONED|
-                                                    -- HASH_PARTITION_EXCHANGE [$$96]  |PARTITIONED|
+                                                  -- HYBRID_HASH_JOIN [$$152][$$136]  |PARTITIONED|
+                                                    -- HASH_PARTITION_EXCHANGE [$$152]  |PARTITIONED|
                                                       -- ASSIGN  |PARTITIONED|
                                                         -- STREAM_PROJECT  |PARTITIONED|
                                                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1596.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1596.plan
index 442d1ec..d845b25 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1596.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpcds/query-ASTERIXDB-1596.plan
@@ -3,16 +3,16 @@
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
         -- STREAM_PROJECT  |PARTITIONED|
-          -- SORT_MERGE_EXCHANGE [$$23(ASC), $$24(ASC) ]  |PARTITIONED|
-            -- STABLE_SORT [$$23(ASC), $$24(ASC)]  |PARTITIONED|
+          -- SORT_MERGE_EXCHANGE [$$44(ASC), $$45(ASC) ]  |PARTITIONED|
+            -- STABLE_SORT [$$44(ASC), $$45(ASC)]  |PARTITIONED|
               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                 -- STREAM_PROJECT  |PARTITIONED|
                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                    -- HYBRID_HASH_JOIN [$$23][$$27]  |PARTITIONED|
-                      -- HASH_PARTITION_EXCHANGE [$$23]  |PARTITIONED|
+                    -- HYBRID_HASH_JOIN [$$44][$$48]  |PARTITIONED|
+                      -- HASH_PARTITION_EXCHANGE [$$44]  |PARTITIONED|
                         -- STREAM_PROJECT  |PARTITIONED|
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                            -- HYBRID_HASH_JOIN [$$24, $$23][$$26, $$25]  |PARTITIONED|
+                            -- HYBRID_HASH_JOIN [$$45, $$44][$$47, $$46]  |PARTITIONED|
                               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                 -- DATASOURCE_SCAN  |PARTITIONED|
                                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpch/q12_shipping.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpch/q12_shipping.plan
index 655b2f5..c2790a4 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpch/q12_shipping.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpch/q12_shipping.plan
@@ -3,13 +3,13 @@
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
         -- SORT_MERGE_EXCHANGE [$$l_shipmode(ASC) ]  |PARTITIONED|
-          -- SORT_GROUP_BY[$$91]  |PARTITIONED|
+          -- SORT_GROUP_BY[$$119]  |PARTITIONED|
                   {
                     -- AGGREGATE  |LOCAL|
                       -- NESTED_TUPLE_SOURCE  |LOCAL|
                   }
-            -- HASH_PARTITION_EXCHANGE [$$91]  |PARTITIONED|
-              -- SORT_GROUP_BY[$$73]  |PARTITIONED|
+            -- HASH_PARTITION_EXCHANGE [$$119]  |PARTITIONED|
+              -- SORT_GROUP_BY[$$101]  |PARTITIONED|
                       {
                         -- AGGREGATE  |LOCAL|
                           -- NESTED_TUPLE_SOURCE  |LOCAL|
@@ -17,12 +17,12 @@
                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                   -- STREAM_PROJECT  |PARTITIONED|
                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                      -- HYBRID_HASH_JOIN [$$73][$$80]  |PARTITIONED|
+                      -- HYBRID_HASH_JOIN [$$101][$$108]  |PARTITIONED|
                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                           -- STREAM_PROJECT  |PARTITIONED|
                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                              -- HYBRID_HASH_JOIN [$$82][$$77]  |PARTITIONED|
-                                -- HASH_PARTITION_EXCHANGE [$$82]  |PARTITIONED|
+                              -- HYBRID_HASH_JOIN [$$110][$$105]  |PARTITIONED|
+                                -- HASH_PARTITION_EXCHANGE [$$110]  |PARTITIONED|
                                   -- STREAM_PROJECT  |PARTITIONED|
                                     -- STREAM_SELECT  |PARTITIONED|
                                       -- ASSIGN  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpch/q12_shipping_broadcast.plan b/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpch/q12_shipping_broadcast.plan
index 8fd10f5..789992e 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpch/q12_shipping_broadcast.plan
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results/tpch/q12_shipping_broadcast.plan
@@ -3,13 +3,13 @@
     -- STREAM_PROJECT  |PARTITIONED|
       -- ASSIGN  |PARTITIONED|
         -- SORT_MERGE_EXCHANGE [$$l_shipmode(ASC) ]  |PARTITIONED|
-          -- SORT_GROUP_BY[$$91]  |PARTITIONED|
+          -- SORT_GROUP_BY[$$119]  |PARTITIONED|
                   {
                     -- AGGREGATE  |LOCAL|
                       -- NESTED_TUPLE_SOURCE  |LOCAL|
                   }
-            -- HASH_PARTITION_EXCHANGE [$$91]  |PARTITIONED|
-              -- SORT_GROUP_BY[$$73]  |PARTITIONED|
+            -- HASH_PARTITION_EXCHANGE [$$119]  |PARTITIONED|
+              -- SORT_GROUP_BY[$$101]  |PARTITIONED|
                       {
                         -- AGGREGATE  |LOCAL|
                           -- NESTED_TUPLE_SOURCE  |LOCAL|
@@ -17,11 +17,11 @@
                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                   -- STREAM_PROJECT  |PARTITIONED|
                     -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                      -- HYBRID_HASH_JOIN [$$73][$$80]  |PARTITIONED|
+                      -- HYBRID_HASH_JOIN [$$101][$$108]  |PARTITIONED|
                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                           -- STREAM_PROJECT  |PARTITIONED|
                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                              -- HYBRID_HASH_JOIN [$$81][$$77]  |PARTITIONED|
+                              -- HYBRID_HASH_JOIN [$$109][$$105]  |PARTITIONED|
                                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
                                   -- STREAM_PROJECT  |PARTITIONED|
                                     -- STREAM_SELECT  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index-join/secondary-equi-join_06.ast b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index-join/secondary-equi-join_06.ast
index b29f485..91f2ae0 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index-join/secondary-equi-join_06.ast
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index-join/secondary-equi-join_06.ast
@@ -20,12 +20,12 @@
         SELECT ELEMENT [
         LiteralExpr [LONG] [1]
         ]
-        FROM [          Variable [ Name=#1 ]
-          AS Variable [ Name=#2 ]
+        FROM [          Variable [ Name=#2 ]
+          AS Variable [ Name=#3 ]
         ]
       )
     ]
-    null
+    $1
     ]
     FROM [      FunctionCall asterix.dataset@1[
         LiteralExpr [STRING] [testdst]
@@ -35,11 +35,11 @@
     Groupby
       Variable [ Name=$val ]
       :=
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [val]
+      FunctionCall asterix.field-access-by-name@2[
         Variable [ Name=$testdst ]
+        LiteralExpr [STRING] [val]
       ]
-      GROUP AS Variable [ Name=#1 ]
+      GROUP AS Variable [ Name=#2 ]
       (
         testdst:=Variable [ Name=$testdst ]
       )
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index/btree-secondary-64.ast b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index/btree-secondary-64.ast
index b3036cb..3f9b7d2 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index/btree-secondary-64.ast
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index/btree-secondary-64.ast
@@ -28,3 +28,8 @@
   AS Variable [ Name=$testdst ]
 ]
 Group All
+  GROUP AS Variable [ Name=#1 ]
+  (
+    testdst:=Variable [ Name=$testdst ]
+  )
+
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index/btree-secondary-65.ast b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index/btree-secondary-65.ast
index cbb7874..89be71d 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index/btree-secondary-65.ast
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index/btree-secondary-65.ast
@@ -37,3 +37,8 @@
     LiteralExpr [LONG] [3]
   ]
 Group All
+  GROUP AS Variable [ Name=#1 ]
+  (
+    t:=Variable [ Name=$t ]
+  )
+
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index/btree-secondary-66.ast b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index/btree-secondary-66.ast
index e596270..f40c406 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index/btree-secondary-66.ast
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index/btree-secondary-66.ast
@@ -34,3 +34,8 @@
   AS Variable [ Name=$t ]
 ]
 Group All
+  GROUP AS Variable [ Name=#1 ]
+  (
+    t:=Variable [ Name=$t ]
+  )
+
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index/btree-secondary-67.ast b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index/btree-secondary-67.ast
index 027e42d..645418e 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index/btree-secondary-67.ast
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/btree-index/btree-secondary-67.ast
@@ -34,3 +34,8 @@
   AS Variable [ Name=$t ]
 ]
 Group All
+  GROUP AS Variable [ Name=#1 ]
+  (
+    t:=Variable [ Name=$t ]
+  )
+
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/count-tweets.ast b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/count-tweets.ast
index a0bee23..2a05929 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/count-tweets.ast
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/count-tweets.ast
@@ -63,5 +63,6 @@
   (
     t:=Variable [ Name=$t ]
     token:=Variable [ Name=$token ]
+    tokens:=Variable [ Name=$tokens ]
   )
 
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/denorm-cust-order.ast b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/denorm-cust-order.ast
index 6cf99d5..d5aba38 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/denorm-cust-order.ast
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/denorm-cust-order.ast
@@ -43,11 +43,18 @@
   (
     LiteralExpr [STRING] [cust]
     :
-    FunctionCall asterix.resolve@-1[
-      LiteralExpr [STRING] [cust]
-      Variable [ Name=$cid ]
-      Variable [ Name=#1 ]
-    ]
+    (
+      SELECT [
+      FunctionCall asterix.field-access-by-name@2[
+        Variable [ Name=$g ]
+        LiteralExpr [STRING] [c]
+      ]
+      c
+      ]
+      FROM [        Variable [ Name=$g ]
+        AS Variable [ Name=$g ]
+      ]
+    )
   )
   (
     LiteralExpr [STRING] [cnt-orders]
@@ -56,12 +63,12 @@
       (
         SELECT ELEMENT [
         FieldAccessor [
-          Variable [ Name=#2 ]
+          Variable [ Name=#1 ]
           Field=o
         ]
         ]
-        FROM [          Variable [ Name=#1 ]
-          AS Variable [ Name=#2 ]
+        FROM [          Variable [ Name=$g ]
+          AS Variable [ Name=#1 ]
         ]
       )
     ]
@@ -69,11 +76,18 @@
   (
     LiteralExpr [STRING] [orders]
     :
-    FunctionCall asterix.resolve@-1[
-      LiteralExpr [STRING] [o]
-      Variable [ Name=$cid ]
-      Variable [ Name=#1 ]
-    ]
+    (
+      SELECT [
+      FunctionCall asterix.field-access-by-name@2[
+        Variable [ Name=$g ]
+        LiteralExpr [STRING] [o]
+      ]
+      o
+      ]
+      FROM [        Variable [ Name=$g ]
+        AS Variable [ Name=$g ]
+      ]
+    )
   )
 ]
 ]
@@ -106,7 +120,7 @@
     Variable [ Name=$c ]
     Field=cid
   ]
-  GROUP AS Variable [ Name=#1 ]
+  GROUP AS Variable [ Name=$g ]
   (
     c:=Variable [ Name=$c ]
     o:=Variable [ Name=$o ]
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/distinct_aggregate.ast b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/distinct_aggregate.ast
index cbf0d66..29c8bc1 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/distinct_aggregate.ast
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/distinct_aggregate.ast
@@ -45,7 +45,7 @@
           Field=g
         ]
         ]
-        FROM [          Variable [ Name=#2 ]
+        FROM [          Variable [ Name=#1 ]
           AS Variable [ Name=#3 ]
         ]
       )
@@ -106,7 +106,7 @@
         Variable [ Name=$l ]
         Field=l_suppkey
       ]
-      GROUP AS Variable [ Name=#1 ]
+      GROUP AS Variable [ Name=#2 ]
       (
         l:=Variable [ Name=$l ]
       )
@@ -127,7 +127,7 @@
     Variable [ Name=$g ]
     Field=l_linestatus
   ]
-  GROUP AS Variable [ Name=#2 ]
+  GROUP AS Variable [ Name=#1 ]
   (
     g:=Variable [ Name=$g ]
   )
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/fj-dblp-csx.ast b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/fj-dblp-csx.ast
index 3901eaf..37e1bc3 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/fj-dblp-csx.ast
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/fj-dblp-csx.ast
@@ -176,6 +176,12 @@
     prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
     paperCSX:=Variable [ Name=$paperCSX ]
     prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+    idDBLP:=Variable [ Name=$idDBLP ]
+    unrankedTokensDBLP:=Variable [ Name=$unrankedTokensDBLP ]
+    tokensDBLP:=Variable [ Name=$tokensDBLP ]
+    idCSX:=Variable [ Name=$idCSX ]
+    unrankedTokensCSX:=Variable [ Name=$unrankedTokensCSX ]
+    tokensCSX:=Variable [ Name=$tokensCSX ]
   )
 
 Orderby
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/inlined_q18_large_volume_customer.ast b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/inlined_q18_large_volume_customer.ast
index 5fc59bb..1f37cba 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/inlined_q18_large_volume_customer.ast
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/inlined_q18_large_volume_customer.ast
@@ -148,7 +148,7 @@
         Variable [ Name=$l ]
         Field=l_orderkey
       ]
-      GROUP AS Variable [ Name=#1 ]
+      GROUP AS Variable [ Name=#2 ]
       (
         l:=Variable [ Name=$l ]
       )
@@ -241,7 +241,7 @@
     Variable [ Name=$o ]
     Field=o_totalprice
   ]
-  GROUP AS Variable [ Name=#2 ]
+  GROUP AS Variable [ Name=#1 ]
   (
     c:=Variable [ Name=$c ]
     o:=Variable [ Name=$o ]
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/orderby-desc-using-gby.ast b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/orderby-desc-using-gby.ast
index 1984dbf..29582fe 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/orderby-desc-using-gby.ast
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/orderby-desc-using-gby.ast
@@ -32,11 +32,7 @@
   (
     LiteralExpr [STRING] [age]
     :
-    FunctionCall asterix.resolve@-1[
-      LiteralExpr [STRING] [age]
-      Variable [ Name=$name ]
-      Variable [ Name=#1 ]
-    ]
+    Variable [ Name=$age ]
   )
 ]
 ]
@@ -52,6 +48,12 @@
     Variable [ Name=$c ]
     Field=name
   ]
+  Variable [ Name=$age ]
+  :=
+  FieldAccessor [
+    Variable [ Name=$c ]
+    Field=age
+  ]
   GROUP AS Variable [ Name=#1 ]
   (
     c:=Variable [ Name=$c ]
@@ -60,10 +62,6 @@
 Orderby
   Variable [ Name=$name ]
   DESC
-  FunctionCall asterix.resolve@-1[
-    LiteralExpr [STRING] [age]
-    Variable [ Name=$name ]
-    Variable [ Name=#1 ]
-  ]
+  Variable [ Name=$age ]
   ASC
 
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/orders-aggreg.ast b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/orders-aggreg.ast
index 213d7ef..5f5644e 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/orders-aggreg.ast
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/orders-aggreg.ast
@@ -23,11 +23,7 @@
     LiteralExpr [STRING] [ordpercust]
     :
     FunctionCall asterix.count@1[
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [o]
-        Variable [ Name=$cid ]
-        Variable [ Name=#1 ]
-      ]
+      Variable [ Name=$g ]
     ]
   )
   (
@@ -37,13 +33,14 @@
       (
         SELECT ELEMENT [
         FieldAccessor [
-          Variable [ Name=$i ]
+          FieldAccessor [
+            Variable [ Name=$i ]
+            Field=o
+          ]
           Field=total
         ]
         ]
-        FROM [          FunctionCall asterix.dataset@1[
-            LiteralExpr [STRING] [o]
-          ]
+        FROM [          Variable [ Name=$g ]
           AS Variable [ Name=$i ]
         ]
       )
@@ -56,13 +53,14 @@
       (
         SELECT ELEMENT [
         FieldAccessor [
-          Variable [ Name=$i ]
+          FieldAccessor [
+            Variable [ Name=$i ]
+            Field=o
+          ]
           Field=total
         ]
         ]
-        FROM [          FunctionCall asterix.dataset@1[
-            LiteralExpr [STRING] [o]
-          ]
+        FROM [          Variable [ Name=$g ]
           AS Variable [ Name=$i ]
         ]
       )
@@ -82,7 +80,7 @@
     Variable [ Name=$o ]
     Field=cid
   ]
-  GROUP AS Variable [ Name=#1 ]
+  GROUP AS Variable [ Name=$g ]
   (
     o:=Variable [ Name=$o ]
   )
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/q01_pricing_summary_report_nt.ast b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/q01_pricing_summary_report_nt.ast
index 2ea4576..f023a0d 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/q01_pricing_summary_report_nt.ast
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/q01_pricing_summary_report_nt.ast
@@ -41,13 +41,14 @@
       (
         SELECT ELEMENT [
         FieldAccessor [
-          Variable [ Name=$i ]
+          FieldAccessor [
+            Variable [ Name=$i ]
+            Field=l
+          ]
           Field=l_quantity
         ]
         ]
-        FROM [          FunctionCall asterix.dataset@1[
-            LiteralExpr [STRING] [l]
-          ]
+        FROM [          Variable [ Name=$g ]
           AS Variable [ Name=$i ]
         ]
       )
@@ -60,13 +61,14 @@
       (
         SELECT ELEMENT [
         FieldAccessor [
-          Variable [ Name=$i ]
+          FieldAccessor [
+            Variable [ Name=$i ]
+            Field=l
+          ]
           Field=l_extendedprice
         ]
         ]
-        FROM [          FunctionCall asterix.dataset@1[
-            LiteralExpr [STRING] [l]
-          ]
+        FROM [          Variable [ Name=$g ]
           AS Variable [ Name=$i ]
         ]
       )
@@ -80,7 +82,10 @@
         SELECT ELEMENT [
         OperatorExpr [
           FieldAccessor [
-            Variable [ Name=$i ]
+            FieldAccessor [
+              Variable [ Name=$i ]
+              Field=l
+            ]
             Field=l_extendedprice
           ]
           *
@@ -88,15 +93,16 @@
             LiteralExpr [LONG] [1]
             -
             FieldAccessor [
-              Variable [ Name=$i ]
+              FieldAccessor [
+                Variable [ Name=$i ]
+                Field=l
+              ]
               Field=l_discount
             ]
           ]
         ]
         ]
-        FROM [          FunctionCall asterix.dataset@1[
-            LiteralExpr [STRING] [l]
-          ]
+        FROM [          Variable [ Name=$g ]
           AS Variable [ Name=$i ]
         ]
       )
@@ -110,7 +116,10 @@
         SELECT ELEMENT [
         OperatorExpr [
           FieldAccessor [
-            Variable [ Name=$i ]
+            FieldAccessor [
+              Variable [ Name=$i ]
+              Field=l
+            ]
             Field=l_extendedprice
           ]
           *
@@ -118,7 +127,10 @@
             LiteralExpr [LONG] [1]
             -
             FieldAccessor [
-              Variable [ Name=$i ]
+              FieldAccessor [
+                Variable [ Name=$i ]
+                Field=l
+              ]
               Field=l_discount
             ]
           ]
@@ -127,15 +139,16 @@
             LiteralExpr [LONG] [1]
             +
             FieldAccessor [
-              Variable [ Name=$i ]
+              FieldAccessor [
+                Variable [ Name=$i ]
+                Field=l
+              ]
               Field=l_tax
             ]
           ]
         ]
         ]
-        FROM [          FunctionCall asterix.dataset@1[
-            LiteralExpr [STRING] [l]
-          ]
+        FROM [          Variable [ Name=$g ]
           AS Variable [ Name=$i ]
         ]
       )
@@ -148,13 +161,14 @@
       (
         SELECT ELEMENT [
         FieldAccessor [
-          Variable [ Name=$i ]
+          FieldAccessor [
+            Variable [ Name=$i ]
+            Field=l
+          ]
           Field=l_quantity
         ]
         ]
-        FROM [          FunctionCall asterix.dataset@1[
-            LiteralExpr [STRING] [l]
-          ]
+        FROM [          Variable [ Name=$g ]
           AS Variable [ Name=$i ]
         ]
       )
@@ -167,13 +181,14 @@
       (
         SELECT ELEMENT [
         FieldAccessor [
-          Variable [ Name=$i ]
+          FieldAccessor [
+            Variable [ Name=$i ]
+            Field=l
+          ]
           Field=l_extendedprice
         ]
         ]
-        FROM [          FunctionCall asterix.dataset@1[
-            LiteralExpr [STRING] [l]
-          ]
+        FROM [          Variable [ Name=$g ]
           AS Variable [ Name=$i ]
         ]
       )
@@ -186,13 +201,14 @@
       (
         SELECT ELEMENT [
         FieldAccessor [
-          Variable [ Name=$i ]
+          FieldAccessor [
+            Variable [ Name=$i ]
+            Field=l
+          ]
           Field=l_discount
         ]
         ]
-        FROM [          FunctionCall asterix.dataset@1[
-            LiteralExpr [STRING] [l]
-          ]
+        FROM [          Variable [ Name=$g ]
           AS Variable [ Name=$i ]
         ]
       )
@@ -202,12 +218,7 @@
     LiteralExpr [STRING] [count_order]
     :
     FunctionCall asterix.count@1[
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [l]
-        Variable [ Name=$l_linestatus ]
-        Variable [ Name=$l_returnflag ]
-        Variable [ Name=#1 ]
-      ]
+      Variable [ Name=$g ]
     ]
   )
 ]
@@ -239,7 +250,7 @@
     Variable [ Name=$l ]
     Field=l_linestatus
   ]
-  GROUP AS Variable [ Name=#1 ]
+  GROUP AS Variable [ Name=$g ]
   (
     l:=Variable [ Name=$l ]
   )
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/q2.ast b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/q2.ast
index d11b11c..5fe4817 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/q2.ast
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/q2.ast
@@ -87,6 +87,7 @@
   (
     event:=Variable [ Name=$event ]
     sponsor:=Variable [ Name=$sponsor ]
+    es:=Variable [ Name=$es ]
   )
 
 Let Variable [ Name=$sig_sponsorship_count ]
@@ -94,17 +95,13 @@
   FunctionCall asterix.sql-count@1[
     (
       SELECT ELEMENT [
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [es]
-        Variable [ Name=$sponsor ]
-        Variable [ Name=$event ]
-        Variable [ Name=$sig_name ]
-        Variable [ Name=#1 ]
-        Variable [ Name=#2 ]
+      FieldAccessor [
+        Variable [ Name=#3 ]
+        Field=es
       ]
       ]
       FROM [        Variable [ Name=#1 ]
-        AS Variable [ Name=#2 ]
+        AS Variable [ Name=#3 ]
       ]
     )
   ]
@@ -129,7 +126,7 @@
               Field=e
             ]
             ]
-            FROM [              Variable [ Name=#3 ]
+            FROM [              Variable [ Name=#2 ]
               AS Variable [ Name=#4 ]
             ]
           )
@@ -152,7 +149,7 @@
         ]
         Field=chapter_name
       ]
-      GROUP AS Variable [ Name=#3 ]
+      GROUP AS Variable [ Name=#2 ]
       (
         e:=Variable [ Name=$e ]
       )
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/query-issue562.ast b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/query-issue562.ast
index f73b58d..370c903 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/query-issue562.ast
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/query-issue562.ast
@@ -227,11 +227,7 @@
     LiteralExpr [STRING] [numcust]
     :
     FunctionCall asterix.count@1[
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [ct]
-        Variable [ Name=$cntrycode ]
-        Variable [ Name=#1 ]
-      ]
+      Variable [ Name=$g ]
     ]
   )
   (
@@ -241,13 +237,14 @@
       (
         SELECT ELEMENT [
         FieldAccessor [
-          Variable [ Name=$i ]
+          FieldAccessor [
+            Variable [ Name=$i ]
+            Field=ct
+          ]
           Field=c_acctbal
         ]
         ]
-        FROM [          FunctionCall asterix.dataset@1[
-            LiteralExpr [STRING] [ct]
-          ]
+        FROM [          Variable [ Name=$g ]
           AS Variable [ Name=$i ]
         ]
       )
@@ -295,7 +292,7 @@
     Variable [ Name=$ct ]
     Field=cntrycode
   ]
-  GROUP AS Variable [ Name=#1 ]
+  GROUP AS Variable [ Name=$g ]
   (
     ct:=Variable [ Name=$ct ]
   )
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/rtree-index-join/query-issue838.ast b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/rtree-index-join/query-issue838.ast
index 52aa967..abab286 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/rtree-index-join/query-issue838.ast
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/rtree-index-join/query-issue838.ast
@@ -61,10 +61,9 @@
     Let Variable [ Name=$circle ]
       :=
       FunctionCall twitter.create-circle@2[
-        FunctionCall asterix.resolve@-1[
-          LiteralExpr [STRING] [location]
+        FunctionCall asterix.field-access-by-name@2[
           Variable [ Name=$tweet ]
-          Variable [ Name=$sub ]
+          LiteralExpr [STRING] [location]
         ]
         LiteralExpr [DOUBLE] [30.0]
       ]
diff --git a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/split-materialization-above-join.ast b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/split-materialization-above-join.ast
index 70acd67..a37fcfa 100644
--- a/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/split-materialization-above-join.ast
+++ b/asterixdb/asterix-app/src/test/resources/optimizerts/results_parser_sqlpp/split-materialization-above-join.ast
@@ -60,19 +60,12 @@
         LiteralExpr [STRING] [sim]
         :
         IndexAccessor [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [sim]
-            Variable [ Name=#5 ]
-            Variable [ Name=$lenLeft ]
-            Variable [ Name=$idLeft ]
-            Variable [ Name=$lenRight ]
-            Variable [ Name=$tokensLeft ]
-            Variable [ Name=$prefixTokenRight ]
-            Variable [ Name=$tokensRight ]
-            Variable [ Name=$paperLeft ]
-            Variable [ Name=$paperRight ]
-            Variable [ Name=$idRight ]
-            Variable [ Name=$prefixTokenLeft ]
+          FieldAccessor [
+            IndexAccessor [
+              Variable [ Name=$g ]
+              Index:               LiteralExpr [LONG] [0]
+            ]
+            Field=sim
           ]
           Index:           LiteralExpr [LONG] [0]
         ]
@@ -85,17 +78,13 @@
       AS Variable [ Name=$paperLeft ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensLeft]
-          Variable [ Name=$paperLeft ]
-          Variable [ Name=$paperRight ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
-          FunctionCall asterix.resolve@-1[
+          FunctionCall asterix.dataset@1[
             LiteralExpr [STRING] [lenLeft]
-            Variable [ Name=$paperLeft ]
-            Variable [ Name=$paperRight ]
           ]
           LiteralExpr [FLOAT] [0.5]
         ]
@@ -108,19 +97,13 @@
       AS Variable [ Name=$paperRight ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensRight]
-          Variable [ Name=$paperLeft ]
-          Variable [ Name=$paperRight ]
-          Variable [ Name=$prefixTokenLeft ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
-          FunctionCall asterix.resolve@-1[
+          FunctionCall asterix.dataset@1[
             LiteralExpr [STRING] [lenRight]
-            Variable [ Name=$paperLeft ]
-            Variable [ Name=$paperRight ]
-            Variable [ Name=$prefixTokenLeft ]
           ]
           LiteralExpr [FLOAT] [0.5]
         ]
@@ -183,12 +166,12 @@
                 (
                   SELECT ELEMENT [
                   FieldAccessor [
-                    Variable [ Name=#2 ]
+                    Variable [ Name=#3 ]
                     Field=paper
                   ]
                   ]
                   FROM [                    Variable [ Name=#1 ]
-                    AS Variable [ Name=#2 ]
+                    AS Variable [ Name=#3 ]
                   ]
                 )
               ]
@@ -198,7 +181,7 @@
 
           )
           AS Variable [ Name=$tokenRanked ]
- AT
+ AT 
 Variable [ Name=$i ]
         ]
         Where
@@ -257,7 +240,7 @@
               Variable [ Name=$tokenGroupped ]
               :=
               Variable [ Name=$token ]
-              GROUP AS Variable [ Name=#3 ]
+              GROUP AS Variable [ Name=#2 ]
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
@@ -272,7 +255,7 @@
                     Field=paper
                   ]
                   ]
-                  FROM [                    Variable [ Name=#3 ]
+                  FROM [                    Variable [ Name=#2 ]
                     AS Variable [ Name=#4 ]
                   ]
                 )
@@ -283,7 +266,7 @@
 
           )
           AS Variable [ Name=$tokenRanked ]
- AT
+ AT 
 Variable [ Name=$i ]
         ]
         Where
@@ -348,12 +331,9 @@
         Variable [ Name=$paperRight ]
         Field=id
       ]
-      GROUP AS Variable [ Name=#5 ]
+      GROUP AS Variable [ Name=$g ]
       (
-        paperLeft:=Variable [ Name=$paperLeft ]
-        prefixTokenLeft:=Variable [ Name=$prefixTokenLeft ]
-        paperRight:=Variable [ Name=$paperRight ]
-        prefixTokenRight:=Variable [ Name=$prefixTokenRight ]
+        sim:=Variable [ Name=$sim ]
       )
 
   )
diff --git a/asterixdb/asterix-app/src/test/resources/parserts/queries_sqlpp/columnalias2.sqlpp b/asterixdb/asterix-app/src/test/resources/parserts/queries_sqlpp/columnalias2.sqlpp
index f74cf47..2e82be5 100644
--- a/asterixdb/asterix-app/src/test/resources/parserts/queries_sqlpp/columnalias2.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/parserts/queries_sqlpp/columnalias2.sqlpp
@@ -17,8 +17,8 @@
  * under the License.
  */
 
-SELECT SQRT(t.a*t.b) AS root FROM tbl_name root
+SELECT sum(t.a*t.b) AS root FROM tbl_name root
 GROUP BY root.id
-WITH u AS root.time
-HAVING root.orders > 0
+WITH u AS min(root.time)
+HAVING count(root.orders) > 0
 ORDER BY u;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/2.ast b/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/2.ast
index 9175953..a605028 100644
--- a/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/2.ast
+++ b/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/2.ast
@@ -54,6 +54,7 @@
   (
     event:=Variable [ Name=$event ]
     sponsor:=Variable [ Name=$sponsor ]
+    es:=Variable [ Name=$es ]
   )
 
 Let Variable [ Name=$sig_sponsorship_count ]
@@ -61,17 +62,13 @@
   FunctionCall asterix.sql-count@1[
     (
       SELECT ELEMENT [
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [es]
-        Variable [ Name=$sponsor ]
-        Variable [ Name=$event ]
-        Variable [ Name=$sig_name ]
-        Variable [ Name=#1 ]
-        Variable [ Name=#2 ]
+      FieldAccessor [
+        Variable [ Name=#3 ]
+        Field=es
       ]
       ]
       FROM [        Variable [ Name=#1 ]
-        AS Variable [ Name=#2 ]
+        AS Variable [ Name=#3 ]
       ]
     )
   ]
@@ -91,19 +88,15 @@
         FunctionCall asterix.sql-count@1[
           (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [es]
-              Variable [ Name=#4 ]
-              Variable [ Name=$sponsor ]
-              Variable [ Name=$sig_sponsorship_count ]
-              Variable [ Name=$chapter_name ]
-              Variable [ Name=$event ]
-              Variable [ Name=$sig_name ]
-              Variable [ Name=#1 ]
-              Variable [ Name=#3 ]
+            FieldAccessor [
+              FieldAccessor [
+                Variable [ Name=#4 ]
+                Field=e
+              ]
+              Field=es
             ]
             ]
-            FROM [              Variable [ Name=#3 ]
+            FROM [              Variable [ Name=#2 ]
               AS Variable [ Name=#4 ]
             ]
           )
@@ -126,7 +119,7 @@
         ]
         Field=chapter_name
       ]
-      GROUP AS Variable [ Name=#3 ]
+      GROUP AS Variable [ Name=#2 ]
       (
         e:=Variable [ Name=$e ]
       )
diff --git a/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/LetFor.ast b/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/LetFor.ast
index 5adaa1e..cf95f08 100644
--- a/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/LetFor.ast
+++ b/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/LetFor.ast
@@ -1,7 +1,7 @@
 Query:
 Let Variable [ Name=$users ]
   :=
-  FunctionCall asterix.resolve@-1[
+  FunctionCall asterix.dataset@1[
     LiteralExpr [STRING] [User]
   ]
 SELECT ELEMENT [
diff --git a/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/columnalias.ast b/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/columnalias.ast
index 3bcc2ab..9c5aaf5 100644
--- a/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/columnalias.ast
+++ b/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/columnalias.ast
@@ -1,28 +1,6 @@
 Query:
 SELECT [
-FunctionCall null.sqrt@1[
-  OperatorExpr [
-    FieldAccessor [
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [t]
-        Variable [ Name=$u ]
-        Variable [ Name=$root ]
-        Variable [ Name=#1 ]
-      ]
-      Field=a
-    ]
-    *
-    FieldAccessor [
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [t]
-        Variable [ Name=$u ]
-        Variable [ Name=$root ]
-        Variable [ Name=#1 ]
-      ]
-      Field=b
-    ]
-  ]
-]
+Variable [ Name=$root ]
 root
 ]
 FROM [  FunctionCall asterix.dataset@1[
diff --git a/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/columnalias2.ast b/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/columnalias2.ast
index 1ffd234..563b883 100644
--- a/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/columnalias2.ast
+++ b/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/columnalias2.ast
@@ -1,27 +1,36 @@
 Query:
 SELECT [
-FunctionCall null.sqrt@1[
-  OperatorExpr [
-    FieldAccessor [
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [t]
-        Variable [ Name=$u ]
-        Variable [ Name=#1 ]
-        Variable [ Name=$id ]
+FunctionCall asterix.sql-sum@1[
+  (
+    SELECT ELEMENT [
+    OperatorExpr [
+      FieldAccessor [
+        FieldAccessor [
+          FieldAccessor [
+            Variable [ Name=#4 ]
+            Field=root
+          ]
+          Field=t
+        ]
+        Field=a
       ]
-      Field=a
-    ]
-    *
-    FieldAccessor [
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [t]
-        Variable [ Name=$u ]
-        Variable [ Name=#1 ]
-        Variable [ Name=$id ]
+      *
+      FieldAccessor [
+        FieldAccessor [
+          FieldAccessor [
+            Variable [ Name=#4 ]
+            Field=root
+          ]
+          Field=t
+        ]
+        Field=b
       ]
-      Field=b
     ]
-  ]
+    ]
+    FROM [      Variable [ Name=#1 ]
+      AS Variable [ Name=#4 ]
+    ]
+  )
 ]
 root
 ]
@@ -44,24 +53,39 @@
 
 Let Variable [ Name=$u ]
   :=
-  FieldAccessor [
-    FunctionCall asterix.resolve@-1[
-      LiteralExpr [STRING] [root]
-      Variable [ Name=#1 ]
-      Variable [ Name=$id ]
-    ]
-    Field=time
+  FunctionCall asterix.sql-min@1[
+    (
+      SELECT ELEMENT [
+      FieldAccessor [
+        FieldAccessor [
+          Variable [ Name=#2 ]
+          Field=root
+        ]
+        Field=time
+      ]
+      ]
+      FROM [        Variable [ Name=#1 ]
+        AS Variable [ Name=#2 ]
+      ]
+    )
   ]
  HAVING
   OperatorExpr [
-    FieldAccessor [
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [root]
-        Variable [ Name=$u ]
-        Variable [ Name=#1 ]
-        Variable [ Name=$id ]
-      ]
-      Field=orders
+    FunctionCall asterix.sql-count@1[
+      (
+        SELECT ELEMENT [
+        FieldAccessor [
+          FieldAccessor [
+            Variable [ Name=#3 ]
+            Field=root
+          ]
+          Field=orders
+        ]
+        ]
+        FROM [          Variable [ Name=#1 ]
+          AS Variable [ Name=#3 ]
+        ]
+      )
     ]
     >
     LiteralExpr [LONG] [0]
diff --git a/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/columnalias3.ast b/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/columnalias3.ast
index 83a3894..6db92c9 100644
--- a/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/columnalias3.ast
+++ b/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/columnalias3.ast
@@ -4,29 +4,7 @@
   (
     LiteralExpr [STRING] [root]
     :
-    FunctionCall null.sqrt@1[
-      OperatorExpr [
-        FieldAccessor [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [t]
-            Variable [ Name=$u ]
-            Variable [ Name=$root ]
-            Variable [ Name=#1 ]
-          ]
-          Field=a
-        ]
-        *
-        FieldAccessor [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [t]
-            Variable [ Name=$u ]
-            Variable [ Name=$root ]
-            Variable [ Name=#1 ]
-          ]
-          Field=b
-        ]
-      ]
-    ]
+    Variable [ Name=$root ]
   )
 ]
 ]
diff --git a/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/functionDecl1.ast b/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/functionDecl1.ast
index 3df40fc..6c92c37 100644
--- a/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/functionDecl1.ast
+++ b/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/functionDecl1.ast
@@ -102,7 +102,7 @@
 Let Variable [ Name=$result ]
   :=
   FunctionCall null.calculate@1[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [Events]
     ]
   ]
diff --git a/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/nestedFLWOGR.ast b/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/nestedFLWOGR.ast
index 695e4c6..b43814a 100644
--- a/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/nestedFLWOGR.ast
+++ b/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/nestedFLWOGR.ast
@@ -14,7 +14,7 @@
 FROM [  (
     Let Variable [ Name=$data ]
       :=
-      FunctionCall asterix.resolve@-1[
+      FunctionCall asterix.dataset@1[
         LiteralExpr [STRING] [User]
       ]
     SELECT ELEMENT [
diff --git a/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/nestedFLWOGR3.ast b/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/nestedFLWOGR3.ast
index 927c7f8..f4d8694 100644
--- a/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/nestedFLWOGR3.ast
+++ b/asterixdb/asterix-app/src/test/resources/parserts/results_parser_sqlpp/nestedFLWOGR3.ast
@@ -54,6 +54,7 @@
   (
     event:=Variable [ Name=$event ]
     sponsor:=Variable [ Name=$sponsor ]
+    es:=Variable [ Name=$es ]
   )
 
 Let Variable [ Name=$sig_sponsorship_count ]
@@ -61,17 +62,13 @@
   FunctionCall asterix.sql-count@1[
     (
       SELECT ELEMENT [
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [es]
-        Variable [ Name=$sponsor ]
-        Variable [ Name=$event ]
-        Variable [ Name=$sig_name ]
-        Variable [ Name=#1 ]
-        Variable [ Name=#2 ]
+      FieldAccessor [
+        Variable [ Name=#3 ]
+        Field=es
       ]
       ]
       FROM [        Variable [ Name=#1 ]
-        AS Variable [ Name=#2 ]
+        AS Variable [ Name=#3 ]
       ]
     )
   ]
@@ -91,19 +88,15 @@
         FunctionCall asterix.sql-count@1[
           (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [es]
-              Variable [ Name=#4 ]
-              Variable [ Name=$sponsor ]
-              Variable [ Name=$sig_sponsorship_count ]
-              Variable [ Name=$chapter_name ]
-              Variable [ Name=$event ]
-              Variable [ Name=$sig_name ]
-              Variable [ Name=#1 ]
-              Variable [ Name=#3 ]
+            FieldAccessor [
+              FieldAccessor [
+                Variable [ Name=#4 ]
+                Field=e
+              ]
+              Field=es
             ]
             ]
-            FROM [              Variable [ Name=#3 ]
+            FROM [              Variable [ Name=#2 ]
               AS Variable [ Name=#4 ]
             ]
           )
@@ -126,7 +119,7 @@
         ]
         Field=chapter_name
       ]
-      GROUP AS Variable [ Name=#3 ]
+      GROUP AS Variable [ Name=#2 ]
       (
         e:=Variable [ Name=$e ]
       )
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/custord/join_q_09/join_q_09.2.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/custord/join_q_09/join_q_09.2.query.sqlpp
index 49aa67f..32071ee 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/custord/join_q_09/join_q_09.2.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/custord/join_q_09/join_q_09.2.query.sqlpp
@@ -17,10 +17,10 @@
  * under the License.
  */
 
-/** This query is a negative test for ambiguous alias reference. */
+/** This query is a test for ambiguous alias reference. */
 
 SELECT c.name AS cust_name,
-       age AS cust_age,
+       age AS age,
        o.total AS order_total,
        [o.oid,o.cid] AS orderList
 FROM test.Customers c, test.Orders o
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/dapd/q2-4/q2-4.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/dapd/q2-4/q2-4.3.query.sqlpp
index a16706d..7aa1ca9 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/dapd/q2-4/q2-4.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/dapd/q2-4/q2-4.3.query.sqlpp
@@ -29,11 +29,11 @@
        (
          SELECT chapter_name, COUNT(e) AS escount
          FROM es AS e
-         GROUP BY chapter_name
+         GROUP BY sponsor.chapter_name
        ) chapter_breakdown
 FROM  Event,
       Event.sponsoring_sigs AS sponsor
-GROUP BY sig_id GROUP AS es
+GROUP BY sponsor.sig_id GROUP AS es
 ORDER BY total_count DESC
 LIMIT 5
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-3_1.1/dblp-3_1.1.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-3_1.1/dblp-3_1.1.3.query.sqlpp
index 5e0785e..8adf8dd 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-3_1.1/dblp-3_1.1.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-3_1.1/dblp-3_1.1.3.query.sqlpp
@@ -62,7 +62,7 @@
           sim as fuzzyjoin.`similarity-jaccard-prefix`(lenLeft,tokensLeft,lenRight,tokensRight,prefixTokenLeft,0.500000f)
     where ((prefixTokenLeft = prefixTokenRight) and ((sim >= 0.500000f) and (paperLeft.id < paperRight.id)))
     /* +hash */
-    group by paperLeft.id as idLeft,paperRight.id as idRight
+    group by paperLeft.id as idLeft,paperRight.id as idRight,sim as sim
 ) as ridpair,
       DBLP as paperLeft,
       DBLP as paperRight
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-3_1.2/dblp-3_1.2.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-3_1.2/dblp-3_1.2.3.query.sqlpp
index 5e0785e..8adf8dd 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-3_1.2/dblp-3_1.2.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-3_1.2/dblp-3_1.2.3.query.sqlpp
@@ -62,7 +62,7 @@
           sim as fuzzyjoin.`similarity-jaccard-prefix`(lenLeft,tokensLeft,lenRight,tokensRight,prefixTokenLeft,0.500000f)
     where ((prefixTokenLeft = prefixTokenRight) and ((sim >= 0.500000f) and (paperLeft.id < paperRight.id)))
     /* +hash */
-    group by paperLeft.id as idLeft,paperRight.id as idRight
+    group by paperLeft.id as idLeft,paperRight.id as idRight,sim as sim
 ) as ridpair,
       DBLP as paperLeft,
       DBLP as paperRight
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-3_1/dblp-3_1.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-3_1/dblp-3_1.3.query.sqlpp
index dd94d30..d9e5106 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-3_1/dblp-3_1.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-3_1/dblp-3_1.3.query.sqlpp
@@ -61,7 +61,7 @@
       ),
           sim as fuzzyjoin.`similarity-jaccard-prefix`(lenLeft,tokensLeft,lenRight,tokensRight,prefixTokenLeft,0.500000f)
     where ((prefixTokenLeft = prefixTokenRight) and ((sim >= 0.500000f) and (paperLeft.id < paperRight.id)))
-    group by paperLeft.id as idLeft,paperRight.id as idRight
+    group by paperLeft.id as idLeft,paperRight.id as idRight,sim as sim
 ) as ridpair
 where ((ridpair.idLeft = paperLeft.id) and (ridpair.idRight = paperRight.id))
 order by paperLeft.id,paperRight.id
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-2_5.1/dblp-csx-2_5.1.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-2_5.1/dblp-csx-2_5.1.3.query.sqlpp
index 1d1735c..21b0d5b 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-2_5.1/dblp-csx-2_5.1.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-2_5.1/dblp-csx-2_5.1.3.query.sqlpp
@@ -65,6 +65,6 @@
   ),
       sim as fuzzyjoin.`similarity-jaccard-prefix`(lenDBLP,tokensDBLP,lenCSX,tokensCSX,prefixTokenDBLP,0.500000f)
 where ((prefixTokenDBLP = prefixTokenCSX) and (sim >= 0.500000f))
-group by idDBLP as idDBLP,idCSX as idCSX
+group by idDBLP as idDBLP,idCSX as idCSX,sim as sim
 order by idDBLP,idCSX
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-2_5.2/dblp-csx-2_5.2.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-2_5.2/dblp-csx-2_5.2.3.query.sqlpp
index f17649b..deea71d 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-2_5.2/dblp-csx-2_5.2.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-2_5.2/dblp-csx-2_5.2.3.query.sqlpp
@@ -66,6 +66,6 @@
       sim as fuzzyjoin.`similarity-jaccard-prefix`(lenDBLP,tokensDBLP,lenCSX,tokensCSX,prefixTokenDBLP,0.500000f)
 where ((prefixTokenDBLP = prefixTokenCSX) and (sim >= 0.500000f))
 /* +hash */
-group by idDBLP as idDBLP,idCSX as idCSX
+group by idDBLP as idDBLP,idCSX as idCSX,sim as sim
 order by idDBLP,idCSX
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-2_5.3/dblp-csx-2_5.3.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-2_5.3/dblp-csx-2_5.3.3.query.sqlpp
index f17649b..deea71d 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-2_5.3/dblp-csx-2_5.3.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-2_5.3/dblp-csx-2_5.3.3.query.sqlpp
@@ -66,6 +66,6 @@
       sim as fuzzyjoin.`similarity-jaccard-prefix`(lenDBLP,tokensDBLP,lenCSX,tokensCSX,prefixTokenDBLP,0.500000f)
 where ((prefixTokenDBLP = prefixTokenCSX) and (sim >= 0.500000f))
 /* +hash */
-group by idDBLP as idDBLP,idCSX as idCSX
+group by idDBLP as idDBLP,idCSX as idCSX,sim as sim
 order by idDBLP,idCSX
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.1/dblp-csx-3_5.1.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.1/dblp-csx-3_5.1.3.query.sqlpp
index 2241df2..d85c7d3 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.1/dblp-csx-3_5.1.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.1/dblp-csx-3_5.1.3.query.sqlpp
@@ -67,7 +67,7 @@
       ),
           sim as fuzzyjoin.`similarity-jaccard-prefix`(lenDBLP,tokensDBLP,lenCSX,tokensCSX,prefixTokenDBLP,0.500000f)
     where ((prefixTokenDBLP = prefixTokenCSX) and (sim >= 0.500000f))
-    group by idDBLP as idDBLP,idCSX as idCSX
+    group by idDBLP as idDBLP,idCSX as idCSX,sim as sim
 ) as ridpair,
       DBLP as paperDBLP,
       CSX as paperCSX
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.2/dblp-csx-3_5.2.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.2/dblp-csx-3_5.2.3.query.sqlpp
index 0c69632..1238a9d 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.2/dblp-csx-3_5.2.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.2/dblp-csx-3_5.2.3.query.sqlpp
@@ -68,7 +68,7 @@
           sim as fuzzyjoin.`similarity-jaccard-prefix`(lenDBLP,tokensDBLP,lenCSX,tokensCSX,prefixTokenDBLP,0.500000f)
     where ((prefixTokenDBLP = prefixTokenCSX) and (sim >= 0.500000f))
     /* +hash */
-    group by idDBLP as idDBLP,idCSX as idCSX
+    group by idDBLP as idDBLP,idCSX as idCSX,sim as sim
 ) as ridpair,
       DBLP as paperDBLP,
       CSX as paperCSX
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.3.1/dblp-csx-3_5.3.1.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.3.1/dblp-csx-3_5.3.1.3.query.sqlpp
index 0c69632..1238a9d 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.3.1/dblp-csx-3_5.3.1.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.3.1/dblp-csx-3_5.3.1.3.query.sqlpp
@@ -68,7 +68,7 @@
           sim as fuzzyjoin.`similarity-jaccard-prefix`(lenDBLP,tokensDBLP,lenCSX,tokensCSX,prefixTokenDBLP,0.500000f)
     where ((prefixTokenDBLP = prefixTokenCSX) and (sim >= 0.500000f))
     /* +hash */
-    group by idDBLP as idDBLP,idCSX as idCSX
+    group by idDBLP as idDBLP,idCSX as idCSX,sim as sim
 ) as ridpair,
       DBLP as paperDBLP,
       CSX as paperCSX
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.4.1/dblp-csx-3_5.4.1.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.4.1/dblp-csx-3_5.4.1.3.query.sqlpp
index b9c649a..578d7c1 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.4.1/dblp-csx-3_5.4.1.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.4.1/dblp-csx-3_5.4.1.3.query.sqlpp
@@ -72,7 +72,7 @@
               sim as fuzzyjoin.`similarity-jaccard-prefix`(lenDBLP,tokensDBLP,lenCSX,tokensCSX,prefixTokenDBLP,0.500000f)
         where ((prefixTokenDBLP = prefixTokenCSX) and (sim >= 0.500000f))
         /* +hash */
-        group by idDBLP as idDBLP,idCSX as idCSX
+        group by idDBLP as idDBLP,idCSX as idCSX,sim as sim
     ) as ridpair
     where (ridpair.idDBLP = paperDBLP.id)
 ) as paperDBLPridpair
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.4/dblp-csx-3_5.4.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.4/dblp-csx-3_5.4.3.query.sqlpp
index dbde905..5f0f083 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.4/dblp-csx-3_5.4.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/fuzzyjoin/dblp-csx-3_5.4/dblp-csx-3_5.4.3.query.sqlpp
@@ -72,7 +72,7 @@
               sim as fuzzyjoin.`similarity-jaccard-prefix`(lenDBLP,tokensDBLP,lenCSX,tokensCSX,prefixTokenDBLP,0.500000f)
         where ((prefixTokenDBLP = prefixTokenCSX) and (sim >= 0.500000f))
         /* +hash */
-        group by idDBLP as idDBLP,idCSX as idCSX
+        group by idDBLP as idDBLP,idCSX as idCSX,sim as sim
     ) as ridpair
     where (ridpair.idDBLP = paperDBLP.id)
 ) as paperDBLPridpair
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/all_datasets/all_datasets.13.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/all_datasets/all_datasets.13.query.sqlpp
index f63fc2e..a30c374 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/all_datasets/all_datasets.13.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/all_datasets/all_datasets.13.query.sqlpp
@@ -25,11 +25,11 @@
     WHERE l_commitdate < l_receiptdate
 )
 
-SELECT o_orderpriority AS order_priority, count(*) AS count
-FROM tpch2.Orders
-JOIN tmp
-ON l_orderkey = o_orderkey
-WHERE o_orderdate >= '1993-07-01' AND o_orderdate < '1993-10-01'
-GROUP BY o_orderpriority
-ORDER BY o_orderpriority
+SELECT o.o_orderpriority AS order_priority, count(*) AS count
+FROM tpch2.Orders o
+JOIN tmp t
+ON t.l_orderkey = o.o_orderkey
+WHERE o.o_orderdate >= '1993-07-01' AND o.o_orderdate < '1993-10-01'
+GROUP BY o.o_orderpriority
+ORDER BY o.o_orderpriority
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/all_datasets/all_datasets.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/all_datasets/all_datasets.3.query.sqlpp
index f63fc2e..a30c374 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/all_datasets/all_datasets.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/all_datasets/all_datasets.3.query.sqlpp
@@ -25,11 +25,11 @@
     WHERE l_commitdate < l_receiptdate
 )
 
-SELECT o_orderpriority AS order_priority, count(*) AS count
-FROM tpch2.Orders
-JOIN tmp
-ON l_orderkey = o_orderkey
-WHERE o_orderdate >= '1993-07-01' AND o_orderdate < '1993-10-01'
-GROUP BY o_orderpriority
-ORDER BY o_orderpriority
+SELECT o.o_orderpriority AS order_priority, count(*) AS count
+FROM tpch2.Orders o
+JOIN tmp t
+ON t.l_orderkey = o.o_orderkey
+WHERE o.o_orderdate >= '1993-07-01' AND o.o_orderdate < '1993-10-01'
+GROUP BY o.o_orderpriority
+ORDER BY o.o_orderpriority
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/all_datasets/all_datasets.7.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/all_datasets/all_datasets.7.query.sqlpp
index f63fc2e..a30c374 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/all_datasets/all_datasets.7.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/all_datasets/all_datasets.7.query.sqlpp
@@ -25,11 +25,11 @@
     WHERE l_commitdate < l_receiptdate
 )
 
-SELECT o_orderpriority AS order_priority, count(*) AS count
-FROM tpch2.Orders
-JOIN tmp
-ON l_orderkey = o_orderkey
-WHERE o_orderdate >= '1993-07-01' AND o_orderdate < '1993-10-01'
-GROUP BY o_orderpriority
-ORDER BY o_orderpriority
+SELECT o.o_orderpriority AS order_priority, count(*) AS count
+FROM tpch2.Orders o
+JOIN tmp t
+ON t.l_orderkey = o.o_orderkey
+WHERE o.o_orderdate >= '1993-07-01' AND o.o_orderdate < '1993-10-01'
+GROUP BY o.o_orderpriority
+ORDER BY o.o_orderpriority
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/single_dataverse/single_dataverse.13.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/single_dataverse/single_dataverse.13.query.sqlpp
index 77667ab..ce9e993 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/single_dataverse/single_dataverse.13.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/single_dataverse/single_dataverse.13.query.sqlpp
@@ -26,11 +26,11 @@
     WHERE l_commitdate < l_receiptdate
 )
 
-SELECT o_orderpriority AS order_priority, count(*) AS count
-FROM Orders
-JOIN tmp
-ON l_orderkey = o_orderkey
-WHERE o_orderdate >= '1993-07-01' AND o_orderdate < '1993-10-01'
-GROUP BY o_orderpriority
-ORDER BY o_orderpriority
+SELECT o.o_orderpriority AS order_priority, count(*) AS count
+FROM Orders o
+JOIN tmp t
+ON t.l_orderkey = o.o_orderkey
+WHERE o.o_orderdate >= '1993-07-01' AND o.o_orderdate < '1993-10-01'
+GROUP BY o.o_orderpriority
+ORDER BY o.o_orderpriority
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/single_dataverse/single_dataverse.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/single_dataverse/single_dataverse.3.query.sqlpp
index 77667ab..ce9e993 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/single_dataverse/single_dataverse.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/single_dataverse/single_dataverse.3.query.sqlpp
@@ -26,11 +26,11 @@
     WHERE l_commitdate < l_receiptdate
 )
 
-SELECT o_orderpriority AS order_priority, count(*) AS count
-FROM Orders
-JOIN tmp
-ON l_orderkey = o_orderkey
-WHERE o_orderdate >= '1993-07-01' AND o_orderdate < '1993-10-01'
-GROUP BY o_orderpriority
-ORDER BY o_orderpriority
+SELECT o.o_orderpriority AS order_priority, count(*) AS count
+FROM Orders o
+JOIN tmp t
+ON t.l_orderkey = o.o_orderkey
+WHERE o.o_orderdate >= '1993-07-01' AND o.o_orderdate < '1993-10-01'
+GROUP BY o.o_orderpriority
+ORDER BY o.o_orderpriority
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/single_dataverse/single_dataverse.7.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/single_dataverse/single_dataverse.7.query.sqlpp
index 77667ab..ce9e993 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/single_dataverse/single_dataverse.7.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/rebalance/single_dataverse/single_dataverse.7.query.sqlpp
@@ -26,11 +26,11 @@
     WHERE l_commitdate < l_receiptdate
 )
 
-SELECT o_orderpriority AS order_priority, count(*) AS count
-FROM Orders
-JOIN tmp
-ON l_orderkey = o_orderkey
-WHERE o_orderdate >= '1993-07-01' AND o_orderdate < '1993-10-01'
-GROUP BY o_orderpriority
-ORDER BY o_orderpriority
+SELECT o.o_orderpriority AS order_priority, count(*) AS count
+FROM Orders o
+JOIN tmp t
+ON t.l_orderkey = o.o_orderkey
+WHERE o.o_orderdate >= '1993-07-01' AND o.o_orderdate < '1993-10-01'
+GROUP BY o.o_orderpriority
+ORDER BY o.o_orderpriority
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/conflict-fields-dataset/conflict-fields-dataset.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/conflict-fields-dataset/conflict-fields-dataset.3.query.sqlpp
index 2645ddc..6560931 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/conflict-fields-dataset/conflict-fields-dataset.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/conflict-fields-dataset/conflict-fields-dataset.3.query.sqlpp
@@ -21,4 +21,5 @@
 
 select *
 from samptable s1, samptable s2
-where samptable > 0;
+where samptable > 0
+order by s1.id
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/groupby_rename_with_sugar/groupby_rename_with_sugar.1.ddl.sqlpp
similarity index 75%
copy from asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp
copy to asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/groupby_rename_with_sugar/groupby_rename_with_sugar.1.ddl.sqlpp
index bd68de8..71e62d6 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/groupby_rename_with_sugar/groupby_rename_with_sugar.1.ddl.sqlpp
@@ -17,14 +17,12 @@
  * under the License.
  */
 
-USE TinySocial;
+drop dataverse test if exists;
+create dataverse test;
+use test;
 
-SELECT t.id id
-FROM FacebookUsers AS t
-UNION ALL
-SELECT s.`message-id` id
-FROM FacebookMessages AS s
-UNION ALL
-SELECT t.name id
-FROM FacebookUsers AS t
-ORDER BY t.id; // There is certainly no field called "t" in the union all results.
+create type orderType as {
+  oid: bigint
+};
+
+create dataset orders(orderType) primary key oid;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/groupby_rename_with_sugar/groupby_rename_with_sugar.2.update.sqlpp
similarity index 71%
copy from asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp
copy to asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/groupby_rename_with_sugar/groupby_rename_with_sugar.2.update.sqlpp
index bd68de8..4ec4dfb 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/groupby_rename_with_sugar/groupby_rename_with_sugar.2.update.sqlpp
@@ -17,14 +17,10 @@
  * under the License.
  */
 
-USE TinySocial;
+use test;
 
-SELECT t.id id
-FROM FacebookUsers AS t
-UNION ALL
-SELECT s.`message-id` id
-FROM FacebookMessages AS s
-UNION ALL
-SELECT t.name id
-FROM FacebookUsers AS t
-ORDER BY t.id; // There is certainly no field called "t" in the union all results.
+insert into orders ({'oid' : 100, 'pid': 0,  'amount': 1});
+insert into orders ({'oid' : 101, 'pid': 1,  'amount': 2});
+insert into orders ({'oid' : 102, 'pid': 2,  'amount': 3});
+insert into orders ({'oid' : 103, 'pid': 1,  'amount': 4});
+insert into orders ({'oid' : 104, 'pid': 0,  'amount': 6});
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/groupby_rename_with_sugar/groupby_rename_with_sugar.3.query.sqlpp
similarity index 75%
copy from asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp
copy to asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/groupby_rename_with_sugar/groupby_rename_with_sugar.3.query.sqlpp
index bd68de8..323a0e3 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/groupby_rename_with_sugar/groupby_rename_with_sugar.3.query.sqlpp
@@ -17,14 +17,9 @@
  * under the License.
  */
 
-USE TinySocial;
+use test;
 
-SELECT t.id id
-FROM FacebookUsers AS t
-UNION ALL
-SELECT s.`message-id` id
-FROM FacebookMessages AS s
-UNION ALL
-SELECT t.name id
-FROM FacebookUsers AS t
-ORDER BY t.id; // There is certainly no field called "t" in the union all results.
+select pid, sum(amount) as s, (select value g from g order by g.ord.oid) as g
+from orders o
+group by pid group as g(o as ord)
+order by pid
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/order_1/order_1.1.ddl.sqlpp
similarity index 74%
copy from asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp
copy to asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/order_1/order_1.1.ddl.sqlpp
index bd68de8..c577bea 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/order_1/order_1.1.ddl.sqlpp
@@ -17,14 +17,19 @@
  * under the License.
  */
 
-USE TinySocial;
+drop dataverse test if exists;
+create dataverse test;
+use test;
 
-SELECT t.id id
-FROM FacebookUsers AS t
-UNION ALL
-SELECT s.`message-id` id
-FROM FacebookMessages AS s
-UNION ALL
-SELECT t.name id
-FROM FacebookUsers AS t
-ORDER BY t.id; // There is certainly no field called "t" in the union all results.
+create type partType as {
+  pid: bigint
+};
+
+create type orderType as {
+  oid: bigint,
+  pid: bigint
+};
+
+create dataset parts(partType) primary key pid;
+
+create dataset orders(orderType) primary key oid;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/order_1/order_1.2.update.sqlpp
similarity index 72%
copy from asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp
copy to asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/order_1/order_1.2.update.sqlpp
index bd68de8..3e5e1d1 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/order_1/order_1.2.update.sqlpp
@@ -17,14 +17,13 @@
  * under the License.
  */
 
-USE TinySocial;
+use test;
 
-SELECT t.id id
-FROM FacebookUsers AS t
-UNION ALL
-SELECT s.`message-id` id
-FROM FacebookMessages AS s
-UNION ALL
-SELECT t.name id
-FROM FacebookUsers AS t
-ORDER BY t.id; // There is certainly no field called "t" in the union all results.
+insert into parts ({'pid': 0});
+insert into parts ({'pid': 1});
+
+insert into orders ({'oid' : 100, 'pid': 0});
+insert into orders ({'oid' : 101, 'pid': 1});
+insert into orders ({'oid' : 102, 'pid': 99});
+insert into orders ({'oid' : 103, 'pid': 1});
+insert into orders ({'oid' : 104, 'pid': 0});
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/order_1/order_1.3.query.sqlpp
similarity index 75%
copy from asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp
copy to asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/order_1/order_1.3.query.sqlpp
index bd68de8..01ed3a5 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/resolution/order_1/order_1.3.query.sqlpp
@@ -17,14 +17,8 @@
  * under the License.
  */
 
-USE TinySocial;
+use test;
 
-SELECT t.id id
-FROM FacebookUsers AS t
-UNION ALL
-SELECT s.`message-id` id
-FROM FacebookMessages AS s
-UNION ALL
-SELECT t.name id
-FROM FacebookUsers AS t
-ORDER BY t.id; // There is certainly no field called "t" in the union all results.
+select value oid from orders
+where pid in (select value pid from parts)
+order by oid
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/select-star/from/from.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/select-star/from/from.3.query.sqlpp
index 53fb0cf..cf61511 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/select-star/from/from.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/select-star/from/from.3.query.sqlpp
@@ -24,9 +24,9 @@
 FROM  Customer c,
       Orders o,
       LineItem l
-WHERE c_mktsegment = 'BUILDING' AND c_custkey = o_custkey
-      AND l_orderkey = o_orderkey AND o_orderdate < '1995-03-15'
-      AND l_shipdate > '1995-03-15'
-ORDER BY l_linenumber, l_orderkey
+WHERE c.c_mktsegment = 'BUILDING' AND c.c_custkey = o.o_custkey
+      AND l.l_orderkey = o.o_orderkey AND o.o_orderdate < '1995-03-15'
+      AND l.l_shipdate > '1995-03-15'
+ORDER BY l.l_linenumber, l.l_orderkey
 LIMIT 3;
 
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/select-star/join/join.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/select-star/join/join.3.query.sqlpp
index 5eeee7c..00f37cd 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/select-star/join/join.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/select-star/join/join.3.query.sqlpp
@@ -22,11 +22,11 @@
 
 SELECT *
 FROM  Customer c
-JOIN  Orders o ON c_custkey = o_custkey
-JOIN  LineItem l ON l_orderkey = o_orderkey
-WHERE c_mktsegment = 'BUILDING'
-      AND o_orderdate < '1995-03-15'
-      AND l_shipdate > '1995-03-15'
-ORDER BY l_linenumber, l_orderkey
+JOIN  Orders o ON c.c_custkey = o.o_custkey
+JOIN  LineItem l ON l.l_orderkey = o.o_orderkey
+WHERE c.c_mktsegment = 'BUILDING'
+      AND o.o_orderdate < '1995-03-15'
+      AND l.l_shipdate > '1995-03-15'
+ORDER BY l.l_linenumber, l.l_orderkey
 LIMIT 3;
 
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/select-star/mixed/mixed.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/select-star/mixed/mixed.3.query.sqlpp
index 95ac04e..188401b 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/select-star/mixed/mixed.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/select-star/mixed/mixed.3.query.sqlpp
@@ -20,13 +20,13 @@
 USE tpch;
 
 
-SELECT  c_custkey, *, o_orderkey
+SELECT  c.c_custkey, *, o.o_orderkey
 FROM  Customer c,
       Orders o,
       LineItem l
-WHERE c_mktsegment = 'BUILDING' AND c_custkey = o_custkey
-      AND l_orderkey = o_orderkey AND o_orderdate < '1995-03-15'
-      AND l_shipdate > '1995-03-15'
-ORDER BY l_linenumber, l_orderkey
+WHERE c.c_mktsegment = 'BUILDING' AND c.c_custkey = o.o_custkey
+      AND l.l_orderkey = o.o_orderkey AND o.o_orderdate < '1995-03-15'
+      AND l.l_shipdate > '1995-03-15'
+ORDER BY l.l_linenumber, l.l_orderkey
 LIMIT 3;
 
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/select-star/no_star/no_star.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/select-star/no_star/no_star.3.query.sqlpp
index 14ae8d1..16e0471 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/select-star/no_star/no_star.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/select-star/no_star/no_star.3.query.sqlpp
@@ -24,9 +24,9 @@
 FROM  Customer c,
       Orders o,
       LineItem l
-WHERE c_mktsegment = 'BUILDING' AND c_custkey = o_custkey
-      AND l_orderkey = o_orderkey AND o_orderdate < '1995-03-15'
-      AND l_shipdate > '1995-03-15'
-ORDER BY l_linenumber, l_orderkey
+WHERE c.c_mktsegment = 'BUILDING' AND c.c_custkey = o.o_custkey
+      AND l.l_orderkey = o.o_orderkey AND o.o_orderdate < '1995-03-15'
+      AND l.l_shipdate > '1995-03-15'
+ORDER BY l.l_linenumber, l.l_orderkey
 LIMIT 3;
 
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/temporal/overlap_bins_gby_1/overlap_bins_gby_1.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/temporal/overlap_bins_gby_1/overlap_bins_gby_1.3.query.sqlpp
index ce3159a..0f9b329 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/temporal/overlap_bins_gby_1/overlap_bins_gby_1.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/temporal/overlap_bins_gby_1/overlap_bins_gby_1.3.query.sqlpp
@@ -25,7 +25,7 @@
 
 
 select element {'timebin':bin,
-    'count':count((select value 1 from g)),
+    'count':coll_count((select value 1 from g)),
     'total_ms':coll_sum((
         select element
         `ms_from_day_time_duration`(`duration-from-interval`(`get-overlapping-interval`(bin, g.i2.interval)))
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q01/q01.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q01/q01.3.query.sqlpp
index f4f6d52..fa3764a 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q01/q01.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q01/q01.3.query.sqlpp
@@ -23,24 +23,24 @@
 with customer_total_return as
 (select sr_customer_sk as ctr_customer_sk
 ,sr_store_sk as ctr_store_sk
-,sum(sr_fee) as ctr_total_return
-from store_returns
-,date_dim
-where sr_returned_date_sk = d_date_sk
-and d_year = 2000
-group by sr_customer_sk
-,sr_store_sk)
+,sum(sr.sr_fee) as ctr_total_return
+from store_returns sr
+,date_dim d
+where sr.sr_returned_date_sk = d.d_date_sk
+and d.d_year = 2000
+group by sr.sr_customer_sk
+,sr.sr_store_sk)
 
-select  c_customer_id
+select c.c_customer_id
 from customer_total_return ctr1
-,store
-,customer
+,store s
+,customer c
 where ctr1.ctr_total_return > (
     select value (avg(ctr2.ctr_total_return)*1.2)
     from customer_total_return ctr2
     where ctr1.ctr_store_sk = ctr2.ctr_store_sk)[0]
-and s_store_sk = ctr1.ctr_store_sk
-and s_state = 'TN'
-and ctr1.ctr_customer_sk = c_customer_sk
-order by c_customer_id
+and s.s_store_sk = ctr1.ctr_store_sk
+and s.s_state = 'TN'
+and ctr1.ctr_customer_sk = c.c_customer_sk
+order by c.c_customer_id
 limit 100;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q03/q03.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q03/q03.3.query.sqlpp
index 67f4a14..612a8c5 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q03/q03.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q03/q03.3.query.sqlpp
@@ -20,10 +20,10 @@
 USE tpcds;
 
 
-SELECT dt.d_year
+SELECT d_year
        ,item.i_brand_id brand_id
        ,item.i_brand brand
-       ,sum(ss_ext_sales_price) sum_agg
+       ,sum(store_sales.ss_ext_sales_price) sum_agg
 FROM date_dim dt
     ,store_sales
     ,item
@@ -34,7 +34,7 @@
 GROUP BY dt.d_year
         ,item.i_brand
         ,item.i_brand_id
-ORDER BY dt.d_year
+ORDER BY d_year
          ,sum_agg desc
          ,brand_id
 LIMIT 100;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q07/q07.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q07/q07.3.query.sqlpp
index 14c8840..6f949b9 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q07/q07.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q07/q07.3.query.sqlpp
@@ -21,20 +21,20 @@
 
 
 SELECT  i_item_id,
-        avg(ss_quantity) agg1,
-        avg(ss_list_price) agg2,
-        avg(ss_coupon_amt) agg3,
-        avg(ss_sales_price) agg4
-FROM store_sales, customer_demographics, date_dim, item, promotion
-WHERE ss_sold_date_sk = d_date_sk
-AND   ss_item_sk = i_item_sk
-AND   ss_cdemo_sk = cd_demo_sk
-AND   ss_promo_sk = p_promo_sk
-AND   cd_gender = 'F'
-AND   cd_marital_status = 'W'
-AND   cd_education_status = 'Primary'
-AND   (p_channel_email = 'N' OR p_channel_event = 'N')
-AND   d_year = 1998
-GROUP BY i_item_id
+        avg(ss.ss_quantity) agg1,
+        avg(ss.ss_list_price) agg2,
+        avg(ss.ss_coupon_amt) agg3,
+        avg(ss.ss_sales_price) agg4
+FROM store_sales ss, customer_demographics cd, date_dim d, item i, promotion p
+WHERE ss.ss_sold_date_sk = d.d_date_sk
+AND   ss.ss_item_sk = i.i_item_sk
+AND   ss.ss_cdemo_sk = cd.cd_demo_sk
+AND   ss.ss_promo_sk = p.p_promo_sk
+AND   cd.cd_gender = 'F'
+AND   cd.cd_marital_status = 'W'
+AND   cd.cd_education_status = 'Primary'
+AND   (p.p_channel_email = 'N' OR p.p_channel_event = 'N')
+AND   d.d_year = 1998
+GROUP BY i.i_item_id
 ORDER BY i_item_id
 LIMIT 100;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q15/q15.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q15/q15.3.query.sqlpp
index ceb7134..484757a 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q15/q15.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q15/q15.3.query.sqlpp
@@ -21,20 +21,20 @@
 
 
 SELECT ca_zip
-      ,sum(cs_sales_price)
-FROM catalog_sales
-    ,customer
-    ,customer_address
-    ,date_dim
-WHERE cs_bill_customer_sk = c_customer_sk
-AND c_current_addr_sk = ca_address_sk
-AND ( substr(ca_zip,1,5) in ['85669', '86197','88274','83405','86475',
+      ,sum(cs.cs_sales_price)
+FROM catalog_sales cs
+    ,customer c
+    ,customer_address ca
+    ,date_dim d
+WHERE cs.cs_bill_customer_sk = c.c_customer_sk
+AND c.c_current_addr_sk = ca.ca_address_sk
+AND ( substr(ca.ca_zip,1,5) in ['85669', '86197','88274','83405','86475',
                              '85392', '85460', '80348', '81792']
-OR ca_state in ['CA','WA','GA']
-OR cs_sales_price > 500)
-AND cs_sold_date_sk = d_date_sk
-AND d_qoy = 2
-AND d_year = 2000
-GROUP BY ca_zip
+OR ca.ca_state in ['CA','WA','GA']
+OR cs.cs_sales_price > 500)
+AND cs.cs_sold_date_sk = d.d_date_sk
+AND d.d_qoy = 2
+AND d.d_year = 2000
+GROUP BY ca.ca_zip
 ORDER BY ca_zip
 LIMIT 100;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q19/q19.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q19/q19.3.query.sqlpp
index 12ca91f..5e3b339 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q19/q19.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q19/q19.3.query.sqlpp
@@ -21,21 +21,21 @@
 
 
 SELECT i_brand_id brand_id, i_brand brand, i_manufact_id, i_manufact,
-       SUM(ss_ext_sales_price) ext_price
-FROM date_dim, store_sales, item,customer,customer_address,store
-WHERE d_date_sk = ss_sold_date_sk
-AND ss_item_sk = i_item_sk
-AND i_manager_id=7
-AND d_moy=11
-AND d_year=1999
-AND ss_customer_sk = c_customer_sk
-AND c_current_addr_sk = ca_address_sk
-AND substr(ca_zip,1,5) != substr(s_zip,1,5)
-AND ss_store_sk = s_store_sk
-GROUP BY i_brand
-        ,i_brand_id
-        ,i_manufact_id
-        ,i_manufact
+       SUM(ss.ss_ext_sales_price) ext_price
+FROM date_dim d, store_sales ss, item i, customer c, customer_address ca, store s
+WHERE d.d_date_sk = ss.ss_sold_date_sk
+AND ss.ss_item_sk = i.i_item_sk
+AND i.i_manager_id=7
+AND d.d_moy=11
+AND d.d_year=1999
+AND ss.ss_customer_sk = c.c_customer_sk
+AND c.c_current_addr_sk = ca.ca_address_sk
+AND substr(ca.ca_zip,1,5) != substr(s.s_zip,1,5)
+AND ss.ss_store_sk = s.s_store_sk
+GROUP BY i.i_brand
+        ,i.i_brand_id
+        ,i.i_manufact_id
+        ,i.i_manufact
 ORDER BY ext_price desc
          ,i_brand
          ,i_brand_id
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q21/q21.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q21/q21.3.query.sqlpp
index d39c5bd..a62a7c6f 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q21/q21.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q21/q21.3.query.sqlpp
@@ -23,24 +23,24 @@
 SELECT  *
 FROM (SELECT w_warehouse_name
             ,i_item_id
-            ,SUM(CASE WHEN date(d_date) < date('1998-04-08')
-                 THEN inv_quantity_on_hand
+            ,SUM(CASE WHEN date(d.d_date) < date('1998-04-08')
+                 THEN inv.inv_quantity_on_hand
                  ELSE 0 END) AS inv_before
-            ,SUM(CASE WHEN date(d_date) >= date('1998-04-08')
-                      THEN inv_quantity_on_hand
+            ,SUM(CASE WHEN date(d.d_date) >= date('1998-04-08')
+                      THEN inv.inv_quantity_on_hand
                       ELSE 0 END) AS inv_after
-   FROM inventory
-       ,warehouse
-       ,item
-       ,date_dim
-   WHERE i_current_price >= 0.99
-     AND i_current_price <= 1.49
-     AND i_item_sk          = inv_item_sk
-     AND inv_warehouse_sk   = w_warehouse_sk
-     AND inv_date_sk    = d_date_sk
-     AND date(d_date) >= date('1998-03-09')
-     AND date(d_date) <= date('1998-05-08')
-   GROUP BY w_warehouse_name, i_item_id) x
+   FROM inventory inv
+       ,warehouse w
+       ,item i
+       ,date_dim d
+   WHERE i.i_current_price >= 0.99
+     AND i.i_current_price <= 1.49
+     AND i.i_item_sk          = inv.inv_item_sk
+     AND inv.inv_warehouse_sk   = w.w_warehouse_sk
+     AND inv.inv_date_sk    = d.d_date_sk
+     AND date(d.d_date) >= date('1998-03-09')
+     AND date(d.d_date) <= date('1998-05-08')
+   GROUP BY w.w_warehouse_name, i.i_item_id) x
    WHERE (CASE WHEN inv_before > 0
           THEN inv_after / inv_before
           ELSE null
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q24a/q24a.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q24a/q24a.3.query.sqlpp
index 9456961..c24c10e 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q24a/q24a.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q24a/q24a.3.query.sqlpp
@@ -31,31 +31,31 @@
       ,i_manager_id
       ,i_units
       ,i_size
-      ,SUM(ss_sales_price) netpaid
-FROM store_sales
-    ,store_returns
-    ,store
-    ,item
-    ,customer
-    ,customer_address
-WHERE ss_ticket_number = sr_ticket_number
-  AND ss_item_sk = sr_item_sk
-  AND ss_customer_sk = c_customer_sk
-  AND ss_item_sk = i_item_sk
-  AND ss_store_sk = s_store_sk
-  AND c_birth_country = UPPERCASE(ca_country)
-  AND s_zip = ca_zip
-AND s_market_id=7
-GROUP BY c_last_name
-        ,c_first_name
-        ,s_store_name
-        ,ca_state
-        ,s_state
-        ,i_color
-        ,i_current_price
-        ,i_manager_id
-        ,i_units
-        ,i_size)
+      ,SUM(ss.ss_sales_price) netpaid
+FROM store_sales ss
+    ,store_returns sr
+    ,store s
+    ,item i
+    ,customer c
+    ,customer_address ca
+WHERE ss.ss_ticket_number = sr.sr_ticket_number
+  AND ss.ss_item_sk = sr.sr_item_sk
+  AND ss.ss_customer_sk = c.c_customer_sk
+  AND ss.ss_item_sk = i.i_item_sk
+  AND ss.ss_store_sk = s.s_store_sk
+  AND c.c_birth_country = UPPERCASE(ca.ca_country)
+  AND s.s_zip = ca.ca_zip
+AND s.s_market_id=7
+GROUP BY c.c_last_name
+        ,c.c_first_name
+        ,s.s_store_name
+        ,ca.ca_state
+        ,s.s_state
+        ,i.i_color
+        ,i.i_current_price
+        ,i.i_manager_id
+        ,i.i_units
+        ,i.i_size)
 SELECT c_last_name
       ,c_first_name
       ,s_store_name
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q24b/q24b.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q24b/q24b.3.query.sqlpp
index 0c80d1d..86ffa7b 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q24b/q24b.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q24b/q24b.3.query.sqlpp
@@ -31,31 +31,31 @@
       ,i_manager_id
       ,i_units
       ,i_size
-      ,SUM(ss_sales_price) netpaid
-FROM store_sales
-    ,store_returns
-    ,store
-    ,item
-    ,customer
-    ,customer_address
-WHERE ss_ticket_number = sr_ticket_number
-  AND ss_item_sk = sr_item_sk
-  AND ss_customer_sk = c_customer_sk
-  AND ss_item_sk = i_item_sk
-  AND ss_store_sk = s_store_sk
-  AND c_birth_country = uppercase(ca_country)
-  AND s_zip = ca_zip
-  AND s_market_id = 7
-GROUP BY c_last_name
-        ,c_first_name
-        ,s_store_name
-        ,ca_state
-        ,s_state
-        ,i_color
-        ,i_current_price
-        ,i_manager_id
-        ,i_units
-        ,i_size)
+      ,SUM(ss.ss_sales_price) netpaid
+FROM store_sales ss
+    ,store_returns sr
+    ,store s
+    ,item i
+    ,customer c
+    ,customer_address ca
+WHERE ss.ss_ticket_number = sr.sr_ticket_number
+  AND ss.ss_item_sk = sr.sr_item_sk
+  AND ss.ss_customer_sk = c.c_customer_sk
+  AND ss.ss_item_sk = i.i_item_sk
+  AND ss.ss_store_sk = s.s_store_sk
+  AND c.c_birth_country = uppercase(ca.ca_country)
+  AND s.s_zip = ca.ca_zip
+  AND s.s_market_id = 7
+GROUP BY c.c_last_name
+        ,c.c_first_name
+        ,s.s_store_name
+        ,ca.ca_state
+        ,s.s_state
+        ,i.i_color
+        ,i.i_current_price
+        ,i.i_manager_id
+        ,i.i_units
+        ,i.i_size)
 SELECT c_last_name
       ,c_first_name
       ,s_store_name
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q25/q25.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q25/q25.3.query.sqlpp
index 8245836..7a473f8 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q25/q25.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q25/q25.3.query.sqlpp
@@ -25,42 +25,42 @@
  ,i_item_desc
  ,s_store_id
  ,s_store_name
- ,SUM(ss_net_profit) as store_sales_profit
- ,SUM(sr_net_loss) as store_returns_loss
- ,SUM(cs_net_profit) as catalog_sales_profit
+ ,SUM(ss.ss_net_profit) as store_sales_profit
+ ,SUM(sr.sr_net_loss) as store_returns_loss
+ ,SUM(cs.cs_net_profit) as catalog_sales_profit
  FROM
- store_sales
- ,store_returns
- ,catalog_sales
+ store_sales ss
+ ,store_returns sr
+ ,catalog_sales cs
  ,date_dim d1
  ,date_dim d2
  ,date_dim d3
- ,store
- ,item
+ ,store s
+ ,item i
  WHERE
  d1.d_moy = 4
  AND d1.d_year = 2000
- AND d1.d_date_sk = ss_sold_date_sk
- AND i_item_sk = ss_item_sk
- AND s_store_sk = ss_store_sk
- AND ss_customer_sk = sr_customer_sk
- AND ss_item_sk = sr_item_sk
- AND ss_ticket_number = sr_ticket_number
- AND sr_returned_date_sk = d2.d_date_sk
+ AND d1.d_date_sk = ss.ss_sold_date_sk
+ AND i.i_item_sk = ss.ss_item_sk
+ AND s.s_store_sk = ss.ss_store_sk
+ AND ss.ss_customer_sk = sr.sr_customer_sk
+ AND ss.ss_item_sk = sr.sr_item_sk
+ AND ss.ss_ticket_number = sr.sr_ticket_number
+ AND sr.sr_returned_date_sk = d2.d_date_sk
  AND d2.d_moy >= 4
  AND d2.d_moy <= 10
  AND d2.d_year = 2000
- AND sr_customer_sk = cs_bill_customer_sk
- AND sr_item_sk = cs_item_sk
- AND cs_sold_date_sk = d3.d_date_sk
+ AND sr.sr_customer_sk = cs.cs_bill_customer_sk
+ AND sr.sr_item_sk = cs.cs_item_sk
+ AND cs.cs_sold_date_sk = d3.d_date_sk
  AND d3.d_moy >= 4
  AND d3.d_moy <= 10
  AND d3.d_year = 2000
  GROUP BY
- i_item_id
- ,i_item_desc
- ,s_store_id
- ,s_store_name
+ i.i_item_id
+ ,i.i_item_desc
+ ,s.s_store_id
+ ,s.s_store_name
  ORDER BY
  i_item_id
  ,i_item_desc
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q26/q26.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q26/q26.3.query.sqlpp
index d5c38ce..7f219b7 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q26/q26.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q26/q26.3.query.sqlpp
@@ -21,20 +21,20 @@
 USE tpcds;
 
 SELECT  i_item_id,
-        avg(cs_quantity) agg1,
-        avg(cs_list_price) agg2,
-        avg(cs_coupon_amt) agg3,
-        avg(cs_sales_price) agg4
- FROM catalog_sales, customer_demographics, date_dim, item, promotion
- WHERE cs_sold_date_sk = d_date_sk AND
-       cs_item_sk = i_item_sk AND
-       cs_bill_cdemo_sk = cd_demo_sk AND
-       cs_promo_sk = p_promo_sk AND
-       cd_gender = 'F' AND
-       cd_marital_status = 'W' AND
-       cd_education_status = 'Primary' AND
-       (p_channel_email = 'N' OR p_channel_event = 'N') AND
-       d_year = 1998
- GROUP BY i_item_id
+        avg(cs.cs_quantity) agg1,
+        avg(cs.cs_list_price) agg2,
+        avg(cs.cs_coupon_amt) agg3,
+        avg(cs.cs_sales_price) agg4
+ FROM catalog_sales cs, customer_demographics cd, date_dim d, item i, promotion p
+ WHERE cs.cs_sold_date_sk = d.d_date_sk AND
+       cs.cs_item_sk = i.i_item_sk AND
+       cs.cs_bill_cdemo_sk = cd.cd_demo_sk AND
+       cs.cs_promo_sk = p.p_promo_sk AND
+       cd.cd_gender = 'F' AND
+       cd.cd_marital_status = 'W' AND
+       cd.cd_education_status = 'Primary' AND
+       (p.p_channel_email = 'N' OR p.p_channel_event = 'N') AND
+       d.d_year = 1998
+ GROUP BY i.i_item_id
  ORDER BY i_item_id
  LIMIT 100;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q29/q29.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q29/q29.3.query.sqlpp
index e2ba54d..2b7270f 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q29/q29.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q29/q29.3.query.sqlpp
@@ -25,39 +25,39 @@
     ,i_item_desc
     ,s_store_id
     ,s_store_name
-    ,SUM(ss_quantity)        as store_sales_quantity
-    ,SUM(sr_return_quantity) as store_returns_quantity
-    ,SUM(cs_quantity)        as catalog_sales_quantity
+    ,SUM(ss.ss_quantity)        as store_sales_quantity
+    ,SUM(sr.sr_return_quantity) as store_returns_quantity
+    ,SUM(cs.cs_quantity)        as catalog_sales_quantity
  FROM
-    store_sales
-   ,store_returns
-   ,catalog_sales
+    store_sales          ss
+   ,store_returns        sr
+   ,catalog_sales        cs
    ,date_dim             d1
    ,date_dim             d2
    ,date_dim             d3
-   ,store
-   ,item
+   ,store                s
+   ,item                 i
  WHERE
      d1.d_moy               = 4
  AND d1.d_year              = 1999
- AND d1.d_date_sk           = ss_sold_date_sk
- AND i_item_sk              = ss_item_sk
- AND s_store_sk             = ss_store_sk
- AND ss_customer_sk         = sr_customer_sk
- AND ss_item_sk             = sr_item_sk
- AND ss_ticket_number       = sr_ticket_number
- AND sr_returned_date_sk    = d2.d_date_sk
+ AND d1.d_date_sk           = ss.ss_sold_date_sk
+ AND i.i_item_sk            = ss.ss_item_sk
+ AND s.s_store_sk           = ss.ss_store_sk
+ AND ss.ss_customer_sk      = sr.sr_customer_sk
+ AND ss.ss_item_sk          = sr.sr_item_sk
+ AND ss.ss_ticket_number    = sr.sr_ticket_number
+ AND sr.sr_returned_date_sk = d2.d_date_sk
  AND d2.d_moy >= 4 AND  d2.d_moy <= 4 + 3
  AND d2.d_year              = 1999
- AND sr_customer_sk         = cs_bill_customer_sk
- AND sr_item_sk             = cs_item_sk
- AND cs_sold_date_sk        = d3.d_date_sk
+ AND sr.sr_customer_sk      = cs.cs_bill_customer_sk
+ AND sr.sr_item_sk          = cs.cs_item_sk
+ AND cs.cs_sold_date_sk     = d3.d_date_sk
  AND d3.d_year              IN [1999,1999+1,1999+2]
  GROUP BY
-    i_item_id
-   ,i_item_desc
-   ,s_store_id
-   ,s_store_name
+    i.i_item_id
+   ,i.i_item_desc
+   ,s.s_store_id
+   ,s.s_store_name
  ORDER BY
     i_item_id
    ,i_item_desc
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q30/q30.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q30/q30.3.query.sqlpp
index 0793006..8ba0feb 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q30/q30.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q30/q30.3.query.sqlpp
@@ -23,28 +23,28 @@
 WITH customer_total_return as
  (SELECT wr_returning_customer_sk as ctr_customer_sk
         ,ca_state as ctr_state,
-  sum(wr_return_amt) as ctr_total_return
- FROM web_returns
-     ,date_dim
-     ,customer_address
- where wr_returned_date_sk = d_date_sk
-   AND d_year =2002
-   AND wr_returning_addr_sk = ca_address_sk
- group by wr_returning_customer_sk
-         ,ca_state)
-  SELECT  c_customer_id,c_salutation,c_first_name,c_last_name,c_preferred_cust_flag
-       ,c_birth_day,c_birth_month,c_birth_year,c_birth_country,c_login,c_email_address
-       ,c_last_review_date,ctr_total_return
+  sum(wr.wr_return_amt) as ctr_total_return
+ FROM web_returns wr
+     ,date_dim d
+     ,customer_address ca
+ where wr.wr_returned_date_sk = d.d_date_sk
+   AND d.d_year =2002
+   AND wr.wr_returning_addr_sk = ca.ca_address_sk
+ group by wr.wr_returning_customer_sk
+         ,ca.ca_state)
+  SELECT  c.c_customer_id,c.c_salutation,c.c_first_name,c.c_last_name,c.c_preferred_cust_flag
+       ,c.c_birth_day,c.c_birth_month,c.c_birth_year,c.c_birth_country,c.c_login,c.c_email_address
+       ,c.c_last_review_date,ctr1.ctr_total_return
  FROM customer_total_return ctr1
-     ,customer_address
-     ,customer
+     ,customer_address ca
+     ,customer c
  where ctr1.ctr_total_return > (SELECT VALUE (AVG(ctr2.ctr_total_return)*1.2)
       FROM customer_total_return ctr2
                      where ctr1.ctr_state = ctr2.ctr_state)[0]
-       AND ca_address_sk = c_current_addr_sk
-       AND ca_state = 'IL'
-       AND ctr1.ctr_customer_sk = c_customer_sk
- ORDER BY c_customer_id,c_salutation,c_first_name,c_last_name,c_preferred_cust_flag
-                  ,c_birth_day,c_birth_month,c_birth_year,c_birth_country,c_login,c_email_address
-                  ,c_last_review_date,ctr_total_return
+       AND ca.ca_address_sk = c.c_current_addr_sk
+       AND ca.ca_state = 'IL'
+       AND ctr1.ctr_customer_sk = c.c_customer_sk
+ ORDER BY c.c_customer_id,c.c_salutation,c.c_first_name,c.c_last_name,c.c_preferred_cust_flag
+                  ,c.c_birth_day,c.c_birth_month,c.c_birth_year,c.c_birth_country,c.c_login,c.c_email_address
+                  ,c.c_last_review_date,ctr1.ctr_total_return
 LIMIT 100;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q31/q31.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q31/q31.3.query.sqlpp
index b869d5e..1768a95 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q31/q31.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q31/q31.3.query.sqlpp
@@ -21,17 +21,17 @@
 USE tpcds;
 
 WITH ss AS
- (SELECT ca_county,d_qoy, d_year,sum(ss_ext_sales_price) as store_sales
- FROM store_sales,date_dim,customer_address
- WHERE ss_sold_date_sk = d_date_sk
-  AND ss_addr_sk=ca_address_sk
- GROUP BY ca_county,d_qoy, d_year),
+ (SELECT ca_county,d_qoy, d_year,sum(ss.ss_ext_sales_price) as store_sales
+ FROM store_sales ss,date_dim d,customer_address ca
+ WHERE ss.ss_sold_date_sk = d.d_date_sk
+  AND ss.ss_addr_sk=ca.ca_address_sk
+ GROUP BY ca.ca_county,d.d_qoy, d.d_year),
  ws AS
- (SELECT ca_county,d_qoy, d_year,sum(ws_ext_sales_price) as web_sales
- FROM web_sales,date_dim,customer_address
- WHERE ws_sold_date_sk = d_date_sk
-  AND ws_bill_addr_sk=ca_address_sk
- GROUP BY ca_county,d_qoy, d_year)
+ (SELECT ca_county,d_qoy, d_year,sum(ws.ws_ext_sales_price) as web_sales
+ FROM web_sales ws,date_dim d,customer_address ca
+ WHERE ws.ws_sold_date_sk = d.d_date_sk
+  AND ws.ws_bill_addr_sk=ca.ca_address_sk
+ GROUP BY ca.ca_county,d.d_qoy, d.d_year)
  SELECT /* tt */
         ss1.ca_county
        ,ss1.d_year
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q34/q34.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q34/q34.3.query.sqlpp
index e81d182..b5908e8 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q34/q34.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q34/q34.3.query.sqlpp
@@ -20,12 +20,12 @@
 
 USE tpcds;
 
-SELECT  c_last_name
-       ,c_first_name
-       ,c_salutation
-       ,c_preferred_cust_flag
-       ,ss_ticket_number
-       ,cnt
+SELECT  c.c_last_name
+       ,c.c_first_name
+       ,c.c_salutation
+       ,c.c_preferred_cust_flag
+       ,dn.ss_ticket_number
+       ,dn.cnt
        FROM
        (select ss_ticket_number
           ,ss_customer_sk
@@ -48,8 +48,8 @@
      AND date_dim.d_year in [1998,1998+1,1998+2]
      AND store.s_county in ['Williamson County','Williamson County','Williamson County','Williamson County',
                            'Williamson County','Williamson County','Williamson County','Williamson County']
-GROUP BY ss_ticket_number,ss_customer_sk GROUP AS dngrp) dn, customer
-WHERE dn.ss_customer_sk = c_customer_sk
-      AND cnt >= 15
-      AND cnt <= 20
-ORDER BY c_last_name,c_first_name,c_salutation,c_preferred_cust_flag desc;
\ No newline at end of file
+GROUP BY store_sales.ss_ticket_number,store_sales.ss_customer_sk GROUP AS dngrp) dn, customer c
+WHERE dn.ss_customer_sk = c.c_customer_sk
+      AND dn.cnt >= 15
+      AND dn.cnt <= 20
+ORDER BY c.c_last_name,c.c_first_name,c.c_salutation,c.c_preferred_cust_flag desc;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q37/q37.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q37/q37.3.query.sqlpp
index df1b580..e05720c 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q37/q37.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q37/q37.3.query.sqlpp
@@ -23,14 +23,14 @@
 SELECT  i_item_id
        ,i_item_desc
        ,i_current_price
- FROM item, inventory, date_dim, catalog_sales
- WHERE i_current_price >= 22 AND i_current_price <= 22 + 30
- AND inv_item_sk = i_item_sk
- AND d_date_sk=inv_date_sk
- AND date(d_date) >= date('2001-06-02') AND date(d_date) <= date('2001-08-01')
- AND i_manufact_id in [678,964,918,849]
- AND inv_quantity_on_hand >= 100 AND inv_quantity_on_hand <= 500
- AND cs_item_sk = i_item_sk
- GROUP BY i_item_id,i_item_desc,i_current_price
+ FROM item i, inventory inv, date_dim d, catalog_sales cs
+ WHERE i.i_current_price >= 22 AND i.i_current_price <= 22 + 30
+ AND inv.inv_item_sk = i.i_item_sk
+ AND d.d_date_sk=inv.inv_date_sk
+ AND date(d.d_date) >= date('2001-06-02') AND date(d.d_date) <= date('2001-08-01')
+ AND i.i_manufact_id in [678,964,918,849]
+ AND inv.inv_quantity_on_hand >= 100 AND inv.inv_quantity_on_hand <= 500
+ AND cs.cs_item_sk = i.i_item_sk
+ GROUP BY i.i_item_id,i.i_item_desc,i.i_current_price
  ORDER BY i_item_id
  LIMIT 100;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q42/q42.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q42/q42.3.query.sqlpp
index cee34eb..94d3975 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q42/q42.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q42/q42.3.query.sqlpp
@@ -23,7 +23,7 @@
 SELECT  dt.d_year
   ,item.i_category_id
   ,item.i_category
-  ,sum(ss_ext_sales_price)
+  ,sum(store_sales.ss_ext_sales_price)
  FROM  date_dim dt
   ,store_sales
   ,item
@@ -35,7 +35,7 @@
  GROUP BY  dt.d_year
    ,item.i_category_id
    ,item.i_category
- ORDER BY SUM(ss_ext_sales_price) desc,dt.d_year
+ ORDER BY SUM(store_sales.ss_ext_sales_price) desc,dt.d_year
    ,item.i_category_id
    ,item.i_category
 LIMIT 100 ;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q43/q43.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q43/q43.3.query.sqlpp
index 6e77ed4..4db7758 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q43/q43.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q43/q43.3.query.sqlpp
@@ -21,18 +21,18 @@
 USE tpcds;
 
 SELECT  s_store_name, s_store_id,
-        SUM(CASE WHEN (d_day_name='Sunday') THEN ss_sales_price ELSE null END) sun_sales,
-        SUM(CASE WHEN (d_day_name='Monday') THEN ss_sales_price ELSE null END) mon_sales,
-        SUM(CASE WHEN (d_day_name='Tuesday') THEN ss_sales_price ELSE  null END) tue_sales,
-        SUM(CASE WHEN (d_day_name='Wednesday') THEN ss_sales_price ELSE null END) wed_sales,
-        SUM(CASE WHEN (d_day_name='Thursday') THEN ss_sales_price ELSE null END) thu_sales,
-        SUM(CASE WHEN (d_day_name='Friday') THEN ss_sales_price ELSE null END) fri_sales,
-        SUM(CASE WHEN (d_day_name='Saturday') THEN ss_sales_price ELSE null END) sat_sales
- FROM date_dim, store_sales, store
- where d_date_sk = ss_sold_date_sk and
-       s_store_sk = ss_store_sk and
-       s_gmt_offset = -5 and
-       d_year = 1998
- GROUP BY s_store_name, s_store_id
+        SUM(CASE WHEN (d.d_day_name='Sunday') THEN ss.ss_sales_price ELSE null END) sun_sales,
+        SUM(CASE WHEN (d.d_day_name='Monday') THEN ss.ss_sales_price ELSE null END) mon_sales,
+        SUM(CASE WHEN (d.d_day_name='Tuesday') THEN ss.ss_sales_price ELSE  null END) tue_sales,
+        SUM(CASE WHEN (d.d_day_name='Wednesday') THEN ss.ss_sales_price ELSE null END) wed_sales,
+        SUM(CASE WHEN (d.d_day_name='Thursday') THEN ss.ss_sales_price ELSE null END) thu_sales,
+        SUM(CASE WHEN (d.d_day_name='Friday') THEN ss.ss_sales_price ELSE null END) fri_sales,
+        SUM(CASE WHEN (d.d_day_name='Saturday') THEN ss.ss_sales_price ELSE null END) sat_sales
+ FROM date_dim d, store_sales ss, store s
+ where d.d_date_sk = ss.ss_sold_date_sk and
+       s.s_store_sk = ss.ss_store_sk and
+       s.s_gmt_offset = -5 and
+       d.d_year = 1998
+ GROUP BY s.s_store_name, s.s_store_id
  ORDER BY s_store_name, s_store_id,sun_sales,mon_sales,tue_sales,wed_sales,thu_sales,fri_sales,sat_sales
  LIMIT 100;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q45/q45.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q45/q45.3.query.sqlpp
index 83acd4a..d2a0d85 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q45/q45.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q45/q45.3.query.sqlpp
@@ -19,20 +19,20 @@
 
 
 USE tpcds;
-SELECT  ca_zip, ca_county, SUM(ws_sales_price)
- FROM web_sales, customer, customer_address, date_dim, item i2
- WHERE ws_bill_customer_sk = c_customer_sk
-  AND c_current_addr_sk = ca_address_sk
-  AND ws_item_sk = i2.i_item_sk
-  AND ( substr(ca_zip,1,5) IN ['85669', '86197','88274','83405','86475', '85392', '85460', '80348', '81792']
+SELECT  ca_zip, ca_county, SUM(ws.ws_sales_price)
+ FROM web_sales ws, customer c, customer_address ca, date_dim d, item i2
+ WHERE ws.ws_bill_customer_sk = c.c_customer_sk
+  AND c.c_current_addr_sk = ca.ca_address_sk
+  AND ws.ws_item_sk = i2.i_item_sk
+  AND ( substr(ca.ca_zip,1,5) IN ['85669', '86197','88274','83405','86475', '85392', '85460', '80348', '81792']
         OR
         i2.i_item_id IN (SELECT VALUE i1.i_item_id
                          FROM item i1
                          WHERE i1.i_item_sk in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
                          )
       )
-  AND ws_sold_date_sk = d_date_sk
-  AND d_qoy = 2 and d_year = 2000
- GROUP BY ca_zip, ca_county
+  AND ws.ws_sold_date_sk = d.d_date_sk
+  AND d.d_qoy = 2 and d.d_year = 2000
+ GROUP BY ca.ca_zip, ca.ca_county
  ORDER BY ca_zip, ca_county
  LIMIT 100;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q46/q46.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q46/q46.3.query.sqlpp
index 873d78b..202f579 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q46/q46.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q46/q46.3.query.sqlpp
@@ -20,18 +20,18 @@
 
 USE tpcds;
 
-SELECT  c_last_name
-       ,c_first_name
-       ,ca_city
-       ,bought_city
-       ,ss_ticket_number
-       ,amt,profit
+SELECT  customer.c_last_name
+       ,customer.c_first_name
+       ,current_addr.ca_city
+       ,dn.bought_city
+       ,dn.ss_ticket_number
+       ,dn.amt,dn.profit
  FROM
    (SELECT ss_ticket_number
           ,ss_customer_sk
           ,ca_city bought_city
-          ,sum(ss_coupon_amt) amt
-          ,sum(ss_net_profit) profit
+          ,sum(store_sales.ss_coupon_amt) amt
+          ,sum(store_sales.ss_net_profit) profit
     FROM store_sales,date_dim,store,household_demographics,customer_address
     WHERE store_sales.ss_sold_date_sk = date_dim.d_date_sk
     AND store_sales.ss_store_sk = store.s_store_sk
@@ -42,13 +42,13 @@
     AND date_dim.d_dow in [6,0]
     AND date_dim.d_year in [1999,1999+1,1999+2]
     AND store.s_city in ['Midway','Fairview','Fairview','Fairview','Fairview']
-    GROUP BY ss_ticket_number,ss_customer_sk,ss_addr_sk,ca_city) dn,customer,customer_address current_addr
-    WHERE ss_customer_sk = c_customer_sk
+    GROUP BY store_sales.ss_ticket_number,store_sales.ss_customer_sk,store_sales.ss_addr_sk,customer_address.ca_city) dn,customer,customer_address current_addr
+    WHERE dn.ss_customer_sk = customer.c_customer_sk
       AND customer.c_current_addr_sk = current_addr.ca_address_sk
-      AND current_addr.ca_city != bought_city
-  ORDER BY c_last_name
-          ,c_first_name
-          ,ca_city
-          ,bought_city
-          ,ss_ticket_number
+      AND current_addr.ca_city != dn.bought_city
+  ORDER BY customer.c_last_name
+          ,customer.c_first_name
+          ,current_addr.ca_city
+          ,dn.bought_city
+          ,dn.ss_ticket_number
   LIMIT 100;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q50/q50.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q50/q50.3.query.sqlpp
index 5bf8683..b7d4152 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q50/q50.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q50/q50.3.query.sqlpp
@@ -31,40 +31,40 @@
   ,s_county
   ,s_state
   ,s_zip
-  ,SUM((CASE WHEN (sr_returned_date_sk - ss_sold_date_sk) <= 30  THEN 1 ELSE 0 END))  AS c30_days
-  ,SUM((CASE WHEN ((sr_returned_date_sk - ss_sold_date_sk) > 30 AND
-                 (sr_returned_date_sk - ss_sold_date_sk) <= 60) THEN 1 ELSE 0 END ))  AS c31_60_days
-  ,SUM((CASE WHEN ((sr_returned_date_sk - ss_sold_date_sk) > 60 AND
-                 (sr_returned_date_sk - ss_sold_date_sk) <= 90) THEN 1 ELSE 0 END))  AS c61_90_days
-  ,SUM((CASE WHEN ((sr_returned_date_sk - ss_sold_date_sk) > 90 AND
-                 (sr_returned_date_sk - ss_sold_date_sk) <= 120) THEN 1 ELSE 0 END))  AS c91_120_days
-  ,SUM((CASE WHEN (sr_returned_date_sk - ss_sold_date_sk)  > 120 THEN 1 ELSE 0 END))  AS gt120_days
+  ,SUM((CASE WHEN (sr.sr_returned_date_sk - ss.ss_sold_date_sk) <= 30  THEN 1 ELSE 0 END))  AS c30_days
+  ,SUM((CASE WHEN ((sr.sr_returned_date_sk - ss.ss_sold_date_sk) > 30 AND
+                 (sr.sr_returned_date_sk - ss.ss_sold_date_sk) <= 60) THEN 1 ELSE 0 END ))  AS c31_60_days
+  ,SUM((CASE WHEN ((sr.sr_returned_date_sk - ss.ss_sold_date_sk) > 60 AND
+                 (sr.sr_returned_date_sk - ss.ss_sold_date_sk) <= 90) THEN 1 ELSE 0 END))  AS c61_90_days
+  ,SUM((CASE WHEN ((sr.sr_returned_date_sk - ss.ss_sold_date_sk) > 90 AND
+                 (sr.sr_returned_date_sk - ss.ss_sold_date_sk) <= 120) THEN 1 ELSE 0 END))  AS c91_120_days
+  ,SUM((CASE WHEN (sr.sr_returned_date_sk - ss.ss_sold_date_sk)  > 120 THEN 1 ELSE 0 END))  AS gt120_days
 FROM
-   store_sales
-  ,store_returns
-  ,store
+   store_sales ss
+  ,store_returns sr
+  ,store s
   ,date_dim d1
   ,date_dim d2
 WHERE
     d2.d_year = 2000
 AND d2.d_moy  = 9
-AND ss_ticket_number = sr_ticket_number
-AND ss_item_sk = sr_item_sk
-AND ss_sold_date_sk   = d1.d_date_sk
-AND sr_returned_date_sk   = d2.d_date_sk
-AND ss_customer_sk = sr_customer_sk
-AND ss_store_sk = s_store_sk
+AND ss.ss_ticket_number = sr.sr_ticket_number
+AND ss.ss_item_sk = sr.sr_item_sk
+AND ss.ss_sold_date_sk   = d1.d_date_sk
+AND sr.sr_returned_date_sk   = d2.d_date_sk
+AND ss.ss_customer_sk = sr.sr_customer_sk
+AND ss.ss_store_sk = s.s_store_sk
 GROUP BY
-   s_store_name
-  ,s_company_id
-  ,s_street_number
-  ,s_street_name
-  ,s_street_type
-  ,s_suite_number
-  ,s_city
-  ,s_county
-  ,s_state
-  ,s_zip
+   s.s_store_name
+  ,s.s_company_id
+  ,s.s_street_number
+  ,s.s_street_name
+  ,s.s_street_type
+  ,s.s_suite_number
+  ,s.s_city
+  ,s.s_county
+  ,s.s_state
+  ,s.s_zip
 ORDER BY s_store_name
         ,s_company_id
         ,s_street_number
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q52/q52.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q52/q52.3.query.sqlpp
index 6c3ad96..4b27365 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q52/q52.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q52/q52.3.query.sqlpp
@@ -23,7 +23,7 @@
 SELECT  dt.d_year
   ,item.i_brand_id brand_id
   ,item.i_brand brand
-  ,SUM(ss_ext_sales_price) ext_price
+  ,SUM(store_sales.ss_ext_sales_price) ext_price
  FROM date_dim dt
      ,store_sales
      ,item
@@ -35,7 +35,7 @@
  GROUP BY dt.d_year
   ,item.i_brand
   ,item.i_brand_id
- ORDER BY dt.d_year
+ ORDER BY d_year
   ,ext_price desc
   ,brand_id
 LIMIT 100 ;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q55/q55.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q55/q55.3.query.sqlpp
index 4928de3..d30e267 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q55/q55.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q55/q55.3.query.sqlpp
@@ -21,13 +21,13 @@
 USE tpcds;
 
 SELECT  i_brand_id brand_id, i_brand brand,
-  SUM(ss_ext_sales_price) ext_price
- FROM date_dim, store_sales, item
- WHERE d_date_sk = ss_sold_date_sk
-  AND ss_item_sk = i_item_sk
-  AND i_manager_id=36
-  AND d_moy=12
-  AND d_year=2001
- GROUP BY i_brand, i_brand_id
+  SUM(ss.ss_ext_sales_price) ext_price
+ FROM date_dim d, store_sales ss, item i
+ WHERE d.d_date_sk = ss.ss_sold_date_sk
+  AND ss.ss_item_sk = i.i_item_sk
+  AND i.i_manager_id=36
+  AND d.d_moy=12
+  AND d.d_year=2001
+ GROUP BY i.i_brand, i.i_brand_id
  ORDER BY ext_price desc, i_brand_id
 LIMIT 100 ;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q59/q59.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q59/q59.3.query.sqlpp
index ff45e4d..638219e 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q59/q59.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q59/q59.3.query.sqlpp
@@ -23,41 +23,41 @@
 WITH wss AS
  (SELECT d_week_seq,
         ss_store_sk,
-        SUM(CASE WHEN d_day_name='Sunday' THEN ss_sales_price ELSE null END) sun_sales,
-        SUM(CASE WHEN d_day_name='Monday' THEN ss_sales_price ELSE null END) mon_sales,
-        SUM(CASE WHEN d_day_name='Tuesday' THEN ss_sales_price ELSE  null END) tue_sales,
-        SUM(CASE WHEN d_day_name='Wednesday' THEN ss_sales_price ELSE null END) wed_sales,
-        SUM(CASE WHEN d_day_name='Thursday' THEN ss_sales_price ELSE null END) thu_sales,
-        SUM(CASE WHEN d_day_name='Friday' THEN ss_sales_price ELSE null END) fri_sales,
-        SUM(CASE WHEN d_day_name='Saturday' THEN ss_sales_price ELSE null END) sat_sales
- FROM store_sales,date_dim
- WHERE d_date_sk = ss_sold_date_sk
- GROUP BY d_week_seq,ss_store_sk
+        SUM(CASE WHEN d.d_day_name='Sunday' THEN ss.ss_sales_price ELSE null END) sun_sales,
+        SUM(CASE WHEN d.d_day_name='Monday' THEN ss.ss_sales_price ELSE null END) mon_sales,
+        SUM(CASE WHEN d.d_day_name='Tuesday' THEN ss.ss_sales_price ELSE  null END) tue_sales,
+        SUM(CASE WHEN d.d_day_name='Wednesday' THEN ss.ss_sales_price ELSE null END) wed_sales,
+        SUM(CASE WHEN d.d_day_name='Thursday' THEN ss.ss_sales_price ELSE null END) thu_sales,
+        SUM(CASE WHEN d.d_day_name='Friday' THEN ss.ss_sales_price ELSE null END) fri_sales,
+        SUM(CASE WHEN d.d_day_name='Saturday' THEN ss.ss_sales_price ELSE null END) sat_sales
+ FROM store_sales ss,date_dim d
+ WHERE d.d_date_sk = ss.ss_sold_date_sk
+ GROUP BY d.d_week_seq,ss.ss_store_sk
  )
-  SELECT  s_store_name1,s_store_id1,d_week_seq1
-       ,sun_sales1/sun_sales2,mon_sales1/mon_sales2
-       ,tue_sales1/tue_sales2,wed_sales1/wed_sales2,thu_sales1/thu_sales2
-       ,fri_sales1/fri_sales2,sat_sales1/sat_sales2
+  SELECT  y.s_store_name1,y.s_store_id1,y.d_week_seq1
+       ,y.sun_sales1/x.sun_sales2,y.mon_sales1/x.mon_sales2
+       ,y.tue_sales1/x.tue_sales2,y.wed_sales1/x.wed_sales2,y.thu_sales1/x.thu_sales2
+       ,y.fri_sales1/x.fri_sales2,y.sat_sales1/x.sat_sales2
  FROM
- (SELECT s_store_name s_store_name1,wss.d_week_seq d_week_seq1
-        ,s_store_id s_store_id1,sun_sales sun_sales1
-        ,mon_sales mon_sales1,tue_sales tue_sales1
-        ,wed_sales wed_sales1,thu_sales thu_sales1
-        ,fri_sales fri_sales1,sat_sales sat_sales1
-  FROM wss,store,date_dim d
+ (SELECT s.s_store_name s_store_name1,wss.d_week_seq d_week_seq1
+        ,s.s_store_id s_store_id1,wss.sun_sales sun_sales1
+        ,wss.mon_sales mon_sales1,wss.tue_sales tue_sales1
+        ,wss.wed_sales wed_sales1,wss.thu_sales thu_sales1
+        ,wss.fri_sales fri_sales1,wss.sat_sales sat_sales1
+  FROM wss,store s,date_dim d
   WHERE d.d_week_seq = wss.d_week_seq AND
-        ss_store_sk = s_store_sk AND
-        d_month_seq >= 1185 AND d_month_seq <= 1185 + 11) y,
- (SELECT s_store_name s_store_name2,wss.d_week_seq d_week_seq2
-        ,s_store_id s_store_id2,sun_sales sun_sales2
-        ,mon_sales mon_sales2,tue_sales tue_sales2
-        ,wed_sales wed_sales2,thu_sales thu_sales2
-        ,fri_sales fri_sales2,sat_sales sat_sales2
-  FROM wss,store,date_dim d
+        wss.ss_store_sk = s.s_store_sk AND
+        d.d_month_seq >= 1185 AND d.d_month_seq <= 1185 + 11) y,
+ (SELECT s.s_store_name s_store_name2,wss.d_week_seq d_week_seq2
+        ,s.s_store_id s_store_id2,wss.sun_sales sun_sales2
+        ,wss.mon_sales mon_sales2,wss.tue_sales tue_sales2
+        ,wss.wed_sales wed_sales2,wss.thu_sales thu_sales2
+        ,wss.fri_sales fri_sales2,wss.sat_sales sat_sales2
+  FROM wss,store s,date_dim d
   WHERE d.d_week_seq = wss.d_week_seq AND
-        ss_store_sk = s_store_sk AND
-        d_month_seq >= 1185+ 12 AND d_month_seq <= 1185 + 23) x
-  WHERE s_store_id1=s_store_id2
-  AND d_week_seq1=d_week_seq2-52
- ORDER BY s_store_name1,s_store_id1,d_week_seq1
+        wss.ss_store_sk = s.s_store_sk AND
+        d.d_month_seq >= 1185+ 12 AND d.d_month_seq <= 1185 + 23) x
+  WHERE y.s_store_id1=x.s_store_id2
+  AND y.d_week_seq1=x.d_week_seq2-52
+ ORDER BY y.s_store_name1,y.s_store_id1,y.d_week_seq1
 LIMIT 100;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q62/q62.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q62/q62.3.query.sqlpp
index 4d45927..b328964 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q62/q62.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q62/q62.3.query.sqlpp
@@ -21,34 +21,34 @@
 USE tpcds;
 
 SELECT
-   SUBSTR(w_warehouse_name,1,20)
-  ,sm_type
-  ,web_name
-  ,SUM(CASE WHEN (ws_ship_date_sk - ws_sold_date_sk) <= 30 THEN 1 ELSE 0 END)  AS c30_days
-  ,SUM(CASE WHEN (ws_ship_date_sk - ws_sold_date_sk) > 30 AND
-                 (ws_ship_date_sk - ws_sold_date_sk) <= 60 THEN 1 ELSE 0 END )  AS c31_60_days
-  ,SUM(CASE WHEN (ws_ship_date_sk - ws_sold_date_sk) > 60 AND
-                 (ws_ship_date_sk - ws_sold_date_sk) <= 90 THEN 1 ELSE 0 END)  AS c61_90_days
-  ,SUM(CASE WHEN (ws_ship_date_sk - ws_sold_date_sk) > 90 AND
-                 (ws_ship_date_sk - ws_sold_date_sk) <= 120 THEN 1 ELSE 0 END)  AS c91_120_days
-  ,SUM(CASE WHEN (ws_ship_date_sk - ws_sold_date_sk)  > 120 THEN 1 ELSE 0 END)  AS gt120_days
+   SUBSTR(w.w_warehouse_name,1,20)
+  ,sm.sm_type
+  ,web.web_name
+  ,SUM(CASE WHEN (ws.ws_ship_date_sk - ws.ws_sold_date_sk) <= 30 THEN 1 ELSE 0 END)  AS c30_days
+  ,SUM(CASE WHEN (ws.ws_ship_date_sk - ws.ws_sold_date_sk) > 30 AND
+                 (ws.ws_ship_date_sk - ws.ws_sold_date_sk) <= 60 THEN 1 ELSE 0 END )  AS c31_60_days
+  ,SUM(CASE WHEN (ws.ws_ship_date_sk - ws.ws_sold_date_sk) > 60 AND
+                 (ws.ws_ship_date_sk - ws.ws_sold_date_sk) <= 90 THEN 1 ELSE 0 END)  AS c61_90_days
+  ,SUM(CASE WHEN (ws.ws_ship_date_sk - ws.ws_sold_date_sk) > 90 AND
+                 (ws.ws_ship_date_sk - ws.ws_sold_date_sk) <= 120 THEN 1 ELSE 0 END)  AS c91_120_days
+  ,SUM(CASE WHEN (ws.ws_ship_date_sk - ws.ws_sold_date_sk)  > 120 THEN 1 ELSE 0 END)  AS gt120_days
 FROM
-   web_sales
-  ,warehouse
-  ,ship_mode
-  ,web_site
-  ,date_dim
+   web_sales ws
+  ,warehouse w
+  ,ship_mode sm
+  ,web_site web
+  ,date_dim d
 WHERE
-    d_month_seq >= 1212 AND d_month_seq <= 1212 + 11
-AND ws_ship_date_sk   = d_date_sk
-AND ws_warehouse_sk   = w_warehouse_sk
-AND ws_ship_mode_sk   = sm_ship_mode_sk
-AND ws_web_site_sk    = web_site_sk
+    d.d_month_seq >= 1212 AND d.d_month_seq <= 1212 + 11
+AND ws.ws_ship_date_sk   = d.d_date_sk
+AND ws.ws_warehouse_sk   = w.w_warehouse_sk
+AND ws.ws_ship_mode_sk   = sm.sm_ship_mode_sk
+AND ws.ws_web_site_sk    = web.web_site_sk
 GROUP BY
-   SUBSTR(w_warehouse_name,1,20)
-  ,sm_type
-  ,web_name
-ORDER BY SUBSTR(w_warehouse_name,1,20)
+   SUBSTR(w.w_warehouse_name,1,20)
+  ,sm.sm_type
+  ,web.web_name
+ORDER BY SUBSTR(w.w_warehouse_name,1,20)
         ,sm_type
        ,web_name
 LIMIT 100;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q68/q68.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q68/q68.3.query.sqlpp
index 5e5833b..d227de9 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q68/q68.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q68/q68.3.query.sqlpp
@@ -20,20 +20,20 @@
 
 USE tpcds;
 
- SELECT  c_last_name
-       ,c_first_name
-       ,ca_city
-       ,bought_city
-       ,ss_ticket_number
-       ,extended_price
-       ,extended_tax
-       ,list_price
+ SELECT  customer.c_last_name
+       ,customer.c_first_name
+       ,current_addr.ca_city
+       ,dn.bought_city
+       ,dn.ss_ticket_number
+       ,dn.extended_price
+       ,dn.extended_tax
+       ,dn.list_price
  FROM (SELECT ss_ticket_number
              ,ss_customer_sk
              ,ca_city bought_city
-             ,sum(ss_ext_sales_price) extended_price
-             ,sum(ss_ext_list_price) list_price
-             ,sum(ss_ext_tax) extended_tax
+             ,sum(store_sales.ss_ext_sales_price) extended_price
+             ,sum(store_sales.ss_ext_list_price) list_price
+             ,sum(store_sales.ss_ext_tax) extended_tax
        FROM store_sales
            ,date_dim
            ,store
@@ -48,14 +48,14 @@
              household_demographics.hd_vehicle_count= 3)
         AND date_dim.d_year in [1999,1999+1,1999+2]
         AND store.s_city IN ['Midway','Fairview']
-        GROUP BY ss_ticket_number
-               ,ss_customer_sk
-               ,ss_addr_sk,ca_city) dn
+        GROUP BY store_sales.ss_ticket_number
+               ,store_sales.ss_customer_sk
+               ,store_sales.ss_addr_sk,customer_address.ca_city) dn
       ,customer
       ,customer_address current_addr
- WHERE ss_customer_sk = c_customer_sk
+ WHERE dn.ss_customer_sk = customer.c_customer_sk
    AND customer.c_current_addr_sk = current_addr.ca_address_sk
-   AND current_addr.ca_city != bought_city
- ORDER BY c_last_name
-         ,ss_ticket_number
+   AND current_addr.ca_city != dn.bought_city
+ ORDER BY customer.c_last_name
+         ,dn.ss_ticket_number
  LIMIT 100;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q73/q73.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q73/q73.3.query.sqlpp
index 0036755..304af8e 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q73/q73.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q73/q73.3.query.sqlpp
@@ -20,12 +20,12 @@
 
 USE tpcds;
 
-SELECT c_last_name
-       ,c_first_name
-       ,c_salutation
-       ,c_preferred_cust_flag
-       ,ss_ticket_number
-       ,cnt FROM
+SELECT c.c_last_name
+       ,c.c_first_name
+       ,c.c_salutation
+       ,c.c_preferred_cust_flag
+       ,dj.ss_ticket_number
+       ,dj.cnt FROM
    (SELECT ss_ticket_number
           ,ss_customer_sk
           ,len(djgrp) cnt
@@ -41,8 +41,8 @@
              household_demographics.hd_dep_count/ household_demographics.hd_vehicle_count ELSE null END) > 1
     AND date_dim.d_year in [1998,1998+1,1998+2]
     AND store.s_county in ['Williamson County','Williamson County','Williamson County','Williamson County']
-    GROUP BY ss_ticket_number,ss_customer_sk
-    GROUP AS djgrp) dj,customer
-    WHERE ss_customer_sk = c_customer_sk
-      AND cnt >= 1 AND cnt <= 5
-    ORDER BY cnt desc;
\ No newline at end of file
+    GROUP BY store_sales.ss_ticket_number,store_sales.ss_customer_sk
+    GROUP AS djgrp) dj,customer c
+    WHERE dj.ss_customer_sk = c.c_customer_sk
+      AND dj.cnt >= 1 AND dj.cnt <= 5
+    ORDER BY dj.cnt desc;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q79/q79.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q79/q79.3.query.sqlpp
index f9a9a5c..0bd5649 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q79/q79.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q79/q79.3.query.sqlpp
@@ -21,13 +21,13 @@
 USE tpcds;
 
 SELECT
-  c_last_name,c_first_name,substr(s_city,1,30),ss_ticket_number,amt,profit
+  c.c_last_name,c.c_first_name,substr(ms.s_city,1,30),ms.ss_ticket_number,ms.amt,ms.profit
   FROM
    (SELECT ss_ticket_number
           ,ss_customer_sk
           ,store.s_city
-          ,sum(ss_coupon_amt) amt
-          ,sum(ss_net_profit) profit
+          ,sum(store_sales.ss_coupon_amt) amt
+          ,sum(store_sales.ss_net_profit) profit
     FROM store_sales,date_dim,store,household_demographics
     WHERE store_sales.ss_sold_date_sk = date_dim.d_date_sk
     AND store_sales.ss_store_sk = store.s_store_sk
@@ -36,7 +36,7 @@
     AND date_dim.d_dow = 1
     AND date_dim.d_year IN [1998,1998+1,1998+2]
     AND store.s_number_employees >= 200 AND store.s_number_employees <= 295
-    group by ss_ticket_number,ss_customer_sk,ss_addr_sk,store.s_city) ms,customer
-    WHERE ss_customer_sk = c_customer_sk
- ORDER BY c_last_name,c_first_name,SUBSTR(s_city,1,30), profit
+    group by store_sales.ss_ticket_number,store_sales.ss_customer_sk,store_sales.ss_addr_sk,store.s_city) ms,customer c
+    WHERE ms.ss_customer_sk = c.c_customer_sk
+ ORDER BY c.c_last_name,c.c_first_name,SUBSTR(ms.s_city,1,30), ms.profit
  LIMIT 100;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q81/q81.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q81/q81.3.query.sqlpp
index 1dbe2ef..d3e4372 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q81/q81.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q81/q81.3.query.sqlpp
@@ -23,28 +23,28 @@
 WITH customer_total_return AS
  (SELECT cr_returning_customer_sk as ctr_customer_sk
         ,ca_state as ctr_state,
-  SUM(cr_return_amt_inc_tax) as ctr_total_return
-  FROM catalog_returns
-     ,date_dim
-     ,customer_address
- WHERE cr_returned_date_sk = d_date_sk
-   AND d_year =1998
-   AND cr_returning_addr_sk = ca_address_sk
- GROUP BY cr_returning_customer_sk
-         ,ca_state )
-  SELECT  c_customer_id,c_salutation,c_first_name,c_last_name,ca_street_number,ca_street_name
-                   ,ca_street_type,ca_suite_number,ca_city,ca_county,ca_state,ca_zip,ca_country,ca_gmt_offset
-                  ,ca_location_type,ctr_total_return
+  SUM(cr.cr_return_amt_inc_tax) as ctr_total_return
+  FROM catalog_returns cr
+     ,date_dim d
+     ,customer_address ca
+ WHERE cr.cr_returned_date_sk = d.d_date_sk
+   AND d.d_year =1998
+   AND cr.cr_returning_addr_sk = ca.ca_address_sk
+ GROUP BY cr.cr_returning_customer_sk
+         ,ca.ca_state )
+  SELECT  c.c_customer_id,c.c_salutation,c.c_first_name,c.c_last_name,ca.ca_street_number,ca.ca_street_name
+                   ,ca.ca_street_type,ca.ca_suite_number,ca.ca_city,ca.ca_county,ca.ca_state,ca.ca_zip,ca.ca_country,ca.ca_gmt_offset
+                  ,ca.ca_location_type,ctr1.ctr_total_return
  FROM customer_total_return ctr1
-     ,customer_address
-     ,customer
+     ,customer_address ca
+     ,customer c
  WHERE ctr1.ctr_total_return > (SELECT VALUE (AVG(ctr2.ctr_total_return)*1.2)
       FROM customer_total_return ctr2
                      WHERE ctr1.ctr_state = ctr2.ctr_state)[0]
-       AND ca_address_sk = c_current_addr_sk
-       AND ca_state = 'IL'
-       AND ctr1.ctr_customer_sk = c_customer_sk
- ORDER BY c_customer_id,c_salutation,c_first_name,c_last_name,ca_street_number,ca_street_name
-                   ,ca_street_type,ca_suite_number,ca_city,ca_county,ca_state,ca_zip,ca_country,ca_gmt_offset
-                  ,ca_location_type,ctr_total_return
+       AND ca.ca_address_sk = c.c_current_addr_sk
+       AND ca.ca_state = 'IL'
+       AND ctr1.ctr_customer_sk = c.c_customer_sk
+ ORDER BY c.c_customer_id,c.c_salutation,c.c_first_name,c.c_last_name,ca.ca_street_number,ca.ca_street_name
+                   ,ca.ca_street_type,ca.ca_suite_number,ca.ca_city,ca.ca_county,ca.ca_state,ca.ca_zip,ca.ca_country,ca.ca_gmt_offset
+                  ,ca.ca_location_type,ca.ctr_total_return
 LIMIT 100;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q82/q82.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q82/q82.3.query.sqlpp
index 7463682..a82b05f 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q82/q82.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q82/q82.3.query.sqlpp
@@ -23,14 +23,14 @@
 SELECT  i_item_id
        ,i_item_desc
        ,i_current_price
- FROM item, inventory, date_dim, store_sales
- WHERE i_current_price >= 30 AND i_current_price <= 30+30
- AND inv_item_sk = i_item_sk
- AND d_date_sk=inv_date_sk
- AND date(d_date) >= date('2002-05-30') AND date(d_date) <= date('2002-07-01')
- AND i_manufact_id in [437,129,727,663]
- AND inv_quantity_on_hand >= 100 AND inv_quantity_on_hand <= 500
- AND ss_item_sk = i_item_sk
- GROUP BY i_item_id,i_item_desc,i_current_price
+ FROM item i, inventory inv, date_dim d, store_sales ss
+ WHERE i.i_current_price >= 30 AND i.i_current_price <= 30+30
+ AND inv.inv_item_sk = i.i_item_sk
+ AND d.d_date_sk=inv.inv_date_sk
+ AND date(d.d_date) >= date('2002-05-30') AND date(d.d_date) <= date('2002-07-01')
+ AND i.i_manufact_id in [437,129,727,663]
+ AND inv.inv_quantity_on_hand >= 100 AND inv.inv_quantity_on_hand <= 500
+ AND ss.ss_item_sk = i.i_item_sk
+ GROUP BY i.i_item_id,i.i_item_desc,i.i_current_price
  ORDER BY i_item_id
  LIMIT 100;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q85/q85.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q85/q85.3.query.sqlpp
index 6330d9b..8ab3f25 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q85/q85.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q85/q85.3.query.sqlpp
@@ -21,19 +21,19 @@
 use tpcds;
 
 select  substr(r_reason_desc,1,20)
-       ,avg(ws_quantity)
-       ,avg(wr_refunded_cash)
-       ,avg(wr_fee)
- from web_sales, web_returns, web_page, customer_demographics cd1,
-      customer_demographics cd2, customer_address, date_dim, reason
- where ws_web_page_sk = wp_web_page_sk
-   and ws_item_sk = wr_item_sk
-   and ws_order_number = wr_order_number
-   and ws_sold_date_sk = d_date_sk and d_year = 1998
-   and cd1.cd_demo_sk = wr_refunded_cdemo_sk
-   and cd2.cd_demo_sk = wr_returning_cdemo_sk
-   and ca_address_sk = wr_refunded_addr_sk
-   and r_reason_sk = wr_reason_sk
+       ,avg(ws.ws_quantity)
+       ,avg(wr.wr_refunded_cash)
+       ,avg(wr.wr_fee)
+ from web_sales ws, web_returns wr, web_page wp, customer_demographics cd1,
+      customer_demographics cd2, customer_address ca, date_dim d, reason r
+ where ws.ws_web_page_sk = wp.wp_web_page_sk
+   and ws.ws_item_sk = wr.wr_item_sk
+   and ws.ws_order_number = wr.wr_order_number
+   and ws.ws_sold_date_sk = d.d_date_sk and d.d_year = 1998
+   and cd1.cd_demo_sk = wr.wr_refunded_cdemo_sk
+   and cd2.cd_demo_sk = wr.wr_returning_cdemo_sk
+   and ca.ca_address_sk = wr.wr_refunded_addr_sk
+   and r.r_reason_sk = wr.wr_reason_sk
    and
    (
     (
@@ -45,7 +45,7 @@
      and
      cd1.cd_education_status = cd2.cd_education_status
      and
-     ws_sales_price >= 100.00 and ws_sales_price <= 150.00
+     ws.ws_sales_price >= 100.00 and ws.ws_sales_price <= 150.00
     )
    or
     (
@@ -57,7 +57,7 @@
      and
      cd1.cd_education_status = cd2.cd_education_status
      and
-     ws_sales_price >= 50.00 and ws_sales_price <= 100.00
+     ws.ws_sales_price >= 50.00 and ws.ws_sales_price <= 100.00
     )
    or
     (
@@ -69,35 +69,35 @@
      and
      cd1.cd_education_status = cd2.cd_education_status
      and
-     ws_sales_price >= 150.00 and ws_sales_price <= 200.00
+     ws.ws_sales_price >= 150.00 and ws.ws_sales_price <= 200.00
     )
    )
    and
    (
     (
-     ca_country = 'United States'
+     ca.ca_country = 'United States'
      and
-     ca_state in ['KY', 'GA', 'NM']
-     and ws_net_profit >= 100 and ws_net_profit <= 200
+     ca.ca_state in ['KY', 'GA', 'NM']
+     and ws.ws_net_profit >= 100 and ws.ws_net_profit <= 200
     )
     or
     (
-     ca_country = 'United States'
+     ca.ca_country = 'United States'
      and
-     ca_state in ['MT', 'OR', 'IN']
-     and ws_net_profit >= 150 and ws_net_profit <= 300
+     ca.ca_state in ['MT', 'OR', 'IN']
+     and ws.ws_net_profit >= 150 and ws.ws_net_profit <= 300
     )
     or
     (
-     ca_country = 'United States'
+     ca.ca_country = 'United States'
      and
-     ca_state in ['WI', 'MO', 'WV']
-     and ws_net_profit >= 50 and ws_net_profit <= 250
+     ca.ca_state in ['WI', 'MO', 'WV']
+     and ws.ws_net_profit >= 50 and ws.ws_net_profit <= 250
     )
    )
-group by r_reason_desc
+group by r.r_reason_desc
 order by substr(r_reason_desc,1,20)
-        ,avg(ws_quantity)
-        ,avg(wr_refunded_cash)
-        ,avg(wr_fee)
+        ,avg(ws.ws_quantity)
+        ,avg(wr.wr_refunded_cash)
+        ,avg(wr.wr_fee)
 limit 100;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q91/q91.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q91/q91.3.query.sqlpp
index 9ce8ffe..29166c3 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q91/q91.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q91/q91.3.query.sqlpp
@@ -24,27 +24,27 @@
         cc_call_center_id Call_Center,
         cc_name Call_Center_Name,
         cc_manager Manager,
-        SUM(cr_net_loss) Returns_Loss
+        SUM(cr.cr_net_loss) Returns_Loss
 FROM
-        call_center,
-        catalog_returns,
-        date_dim,
-        customer,
-        customer_address,
-        customer_demographics,
-        household_demographics
+        call_center cc,
+        catalog_returns cr,
+        date_dim d,
+        customer c,
+        customer_address ca,
+        customer_demographics cd,
+        household_demographics hd
 WHERE
-        cr_call_center_sk       = cc_call_center_sk
-AND     cr_returned_date_sk     = d_date_sk
-AND     cr_returning_customer_sk= c_customer_sk
-AND     cd_demo_sk              = c_current_cdemo_sk
-AND     hd_demo_sk              = c_current_hdemo_sk
-AND     ca_address_sk           = c_current_addr_sk
-AND     d_year                  = 1999
-AND     d_moy                   = 11
-AND     ( (cd_marital_status       = 'M' AND cd_education_status     = 'Unknown')
-        OR (cd_marital_status       = 'W' AND cd_education_status     = 'Advanced Degree'))
-AND     hd_buy_potential like '0-500%'
-AND     ca_gmt_offset           = -7
-GROUP BY cc_call_center_id,cc_name,cc_manager,cd_marital_status,cd_education_status
-ORDER BY SUM(cr_net_loss) desc;
\ No newline at end of file
+        cr.cr_call_center_sk       = cc.cc_call_center_sk
+AND     cr.cr_returned_date_sk     = d.d_date_sk
+AND     cr.cr_returning_customer_sk= c.c_customer_sk
+AND     cd.cd_demo_sk              = c.c_current_cdemo_sk
+AND     hd.hd_demo_sk              = c.c_current_hdemo_sk
+AND     ca.ca_address_sk           = c.c_current_addr_sk
+AND     d.d_year                  = 1999
+AND     d.d_moy                   = 11
+AND     ( (cd.cd_marital_status       = 'M' AND cd.cd_education_status     = 'Unknown')
+        OR (cd.cd_marital_status       = 'W' AND cd.cd_education_status     = 'Advanced Degree'))
+AND     hd.hd_buy_potential like '0-500%'
+AND     ca.ca_gmt_offset           = -7
+GROUP BY cc.cc_call_center_id,cc.cc_name,cc.cc_manager,cd.cd_marital_status,cd.cd_education_status
+ORDER BY SUM(cr.cr_net_loss) desc;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q94/q94.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q94/q94.3.query.sqlpp
index 9de99d7..c30002f 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q94/q94.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q94/q94.3.query.sqlpp
@@ -22,24 +22,24 @@
 
 SELECT
    COUNT(wsnondup.ws_order_number) order_count,
-   SUM(ws_ext_ship_cost) total_shipping_cost,
-   SUM(ws_net_profit) total_net_profit
+   SUM(ws1.ws_ext_ship_cost) total_shipping_cost,
+   SUM(ws1.ws_net_profit) total_net_profit
 FROM
    (SELECT ws_order_number
     FROM web_sales
     GROUP BY ws_order_number) AS wsnondup,
    web_sales as ws1,
-   date_dim,
-   customer_address,
-   web_site
+   date_dim d,
+   customer_address ca,
+   web_site web
 WHERE
-    date(d_date) >= date('1999-05-01')
-AND date(d_date) <= date('1999-06-29')
-AND ws1.ws_ship_date_sk = d_date_sk
-AND ws1.ws_ship_addr_sk = ca_address_sk
-AND ca_state = 'TX'
-AND ws1.ws_web_site_sk = web_site_sk
-AND web_company_name = 'pri'
+    date(d.d_date) >= date('1999-05-01')
+AND date(d.d_date) <= date('1999-06-29')
+AND ws1.ws_ship_date_sk = d.d_date_sk
+AND ws1.ws_ship_addr_sk = ca.ca_address_sk
+AND ca.ca_state = 'TX'
+AND ws1.ws_web_site_sk = web.web_site_sk
+AND web.web_company_name = 'pri'
 AND EXISTS (SELECT *
             FROM web_sales ws2
             WHERE ws1.ws_order_number = ws2.ws_order_number
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q95/q95.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q95/q95.3.query.sqlpp
index e32122f..9e04780 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q95/q95.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q95/q95.3.query.sqlpp
@@ -32,27 +32,27 @@
  FROM
  (
  SELECT
-   distinct ws_order_number
-  ,ws_ext_ship_cost
-  ,ws_net_profit
+   distinct ws1.ws_order_number
+  ,ws1.ws_ext_ship_cost
+  ,ws1.ws_net_profit
 FROM
    web_sales ws1
-  ,date_dim
-  ,customer_address
-  ,web_site
+  ,date_dim d
+  ,customer_address ca
+  ,web_site web
 WHERE
-    date(d_date) >= date('1999-05-01')
-AND date(d_date) <= date('1999-06-30')
-AND ws1.ws_ship_date_sk = d_date_sk
-AND ws1.ws_ship_addr_sk = ca_address_sk
-AND ca_state = 'TX'
-AND ws1.ws_web_site_sk = web_site_sk
-AND web_company_name = 'pri'
-AND ws1.ws_order_number IN (SELECT VALUE ws_wh.ws_order_number
+    date(d.d_date) >= date('1999-05-01')
+AND date(d.d_date) <= date('1999-06-30')
+AND ws1.ws_ship_date_sk = d.d_date_sk
+AND ws1.ws_ship_addr_sk = ca.ca_address_sk
+AND ca.ca_state = 'TX'
+AND ws1.ws_web_site_sk = web.web_site_sk
+AND web.web_company_name = 'pri'
+AND ws1.ws_order_number IN (SELECT VALUE ws_order_number
                             FROM ws_wh)
-AND ws1.ws_order_number IN (SELECT VALUE wr_order_number
-                            FROM web_returns,ws_wh
-                            WHERE wr_order_number = ws_wh.ws_order_number)
+AND ws1.ws_order_number IN (SELECT VALUE wr.wr_order_number
+                            FROM web_returns wr,ws_wh
+                            WHERE wr.wr_order_number = ws_wh.ws_order_number)
 ) t1
 ORDER BY COUNT(ws_order_number)
 LIMIT 100;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q96/q96.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q96/q96.3.query.sqlpp
index 1fa8c67..b35f5c2 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q96/q96.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q96/q96.3.query.sqlpp
@@ -26,9 +26,9 @@
 FROM store_sales,
            household_demographics,
            time_dim, store
-WHERE ss_sold_time_sk = time_dim.t_time_sk
-    AND ss_hdemo_sk = household_demographics.hd_demo_sk
-    AND ss_store_sk = s_store_sk
+WHERE store_sales.ss_sold_time_sk = time_dim.t_time_sk
+    AND store_sales.ss_hdemo_sk = household_demographics.hd_demo_sk
+    AND store_sales.ss_store_sk = store.s_store_sk
     AND time_dim.t_hour = 8
     AND time_dim.t_minute >= 30
     AND household_demographics.hd_dep_count = 5
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q98/q98.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q98/q98.3.query.sqlpp
index 99d81e0..17038de 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q98/q98.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/q98/q98.3.query.sqlpp
@@ -33,35 +33,35 @@
         i_class,
         i_current_price,
         i_item_id,
-        SUM(ss_ext_sales_price) itemrevenue
+        SUM(ss.ss_ext_sales_price) itemrevenue
 FROM
-  store_sales,
-  item,
-  date_dim
+  store_sales ss,
+  item i,
+  date_dim d
 WHERE
-  ss_item_sk = i_item_sk
-  AND i_category IN ["Jewelry", "Sports", "Books"]
-  AND ss_sold_date_sk = d_date_sk
-  AND date(d_date) >= date('2001-01-12')
-  AND date(d_date) <= date('2001-02-11')
+  ss.ss_item_sk = i.i_item_sk
+  AND i.i_category IN ["Jewelry", "Sports", "Books"]
+  AND ss.ss_sold_date_sk = d.d_date_sk
+  AND date(d.d_date) >= date('2001-01-12')
+  AND date(d.d_date) <= date('2001-02-11')
 GROUP BY
-  i_item_id,
-  i_item_desc,
-  i_category,
-  i_class,
-  i_current_price
+  i.i_item_id,
+  i.i_item_desc,
+  i.i_category,
+  i.i_class,
+  i.i_current_price
 ) AS currpricetable
 JOIN
-(SELECT i_item_id, i_item_desc, i_category, i_class, SUM(ss_ext_sales_price) revrat
+(SELECT i_item_id, i_item_desc, i_category, i_class, SUM(ss.ss_ext_sales_price) revrat
   FROM
-  store_sales,
-  item
-  WHERE ss_item_sk = i_item_sk
+  store_sales ss,
+  item i
+  WHERE ss.ss_item_sk = i.i_item_sk
   GROUP BY
-     i_item_id,
-     i_item_desc,
-     i_category,
-     i_class
+     i.i_item_id,
+     i.i_item_desc,
+     i.i_category,
+     i.i_class
 ) AS revrattable
 ON  currpricetable.i_item_id = revrattable.i_item_id
 AND currpricetable.i_class = revrattable.i_class
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/query-ASTERIXDB-1602/query-ASTERIXDB-1602.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/query-ASTERIXDB-1602/query-ASTERIXDB-1602.3.query.sqlpp
index 95889bc..3a1b5c2 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/query-ASTERIXDB-1602/query-ASTERIXDB-1602.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpcds/query-ASTERIXDB-1602/query-ASTERIXDB-1602.3.query.sqlpp
@@ -33,7 +33,7 @@
              where d3.d_date in ['1900-01-02', '1900-01-12', '1900-01-15']
             )
         )
- group by i_item_id
+ group by item.i_item_id
 )
 
 select coll_count((
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-like/q13_customer_distribution/q13_customer_distribution.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-like/q13_customer_distribution/q13_customer_distribution.3.query.sqlpp
index 4823a39..a15ab14 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-like/q13_customer_distribution/q13_customer_distribution.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-like/q13_customer_distribution/q13_customer_distribution.3.query.sqlpp
@@ -41,6 +41,6 @@
 ) as gco
 group by gco.c_count as c_count
 group as g
-let  custdist = count(( select value gco from g ))
+let  custdist = coll_count(( select value gco from g ))
 order by custdist desc,c_count desc
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-like/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-like/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.query.sqlpp
index 3963de0..65293dc 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-like/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-like/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.query.sqlpp
@@ -78,6 +78,6 @@
 ) as t4
 group by t4.s_name as s_name
 group as g
-let  numwait = count(( from g select value t4 ))
+let  numwait = coll_count(( from g select value t4 ))
 order by numwait desc,s_name
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-like/query-issue601/query-issue601.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-like/query-issue601/query-issue601.3.query.sqlpp
index 3f3a50a..4689676 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-like/query-issue601/query-issue601.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-like/query-issue601/query-issue601.3.query.sqlpp
@@ -26,7 +26,7 @@
 use tpch;
 
 
-select element {'l_linenumber':l.l_linenumber,'count_order': count((from g select value g))}
+select element {'l_linenumber':l.l_linenumber,'count_order': coll_count((from g select value g))}
 from  LineItem as l
 group by l.l_linenumber
 group as g
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/nest_aggregate/nest_aggregate.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/nest_aggregate/nest_aggregate.3.query.sqlpp
index 6d0d928..ba3297f 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/nest_aggregate/nest_aggregate.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/nest_aggregate/nest_aggregate.3.query.sqlpp
@@ -29,11 +29,11 @@
 SELECT  Nation.n_nationkey AS nation_key,
         Nation.n_name AS name,
         (
-            SELECT orderdate AS order_date, sum(o_totalprice) AS sum_price
-            FROM  Orders,
-                  Customer
-            WHERE o_custkey = c_custkey AND c_nationkey = Nation.n_nationkey
-            GROUP BY o_orderdate AS orderdate
+            SELECT orderdate AS order_date, sum(o.o_totalprice) AS sum_price
+            FROM  Orders o,
+                  Customer c
+            WHERE o.o_custkey = c.c_custkey AND c.c_nationkey = Nation.n_nationkey
+            GROUP BY o.o_orderdate AS orderdate
             ORDER BY sum_price
             LIMIT 3
         ) AS aggregates
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/nest_aggregate2/nest_aggregate2.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/nest_aggregate2/nest_aggregate2.3.query.sqlpp
index 4a4cfc5..ae1dd27 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/nest_aggregate2/nest_aggregate2.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/nest_aggregate2/nest_aggregate2.3.query.sqlpp
@@ -31,11 +31,11 @@
         Nation.n_name AS name,
         (
             SELECT ELEMENT orderdate
-            FROM  Orders,
-                  Customer
-            WHERE o_custkey = c_custkey AND c_nationkey = Nation.n_nationkey
-            GROUP BY o_orderdate AS orderdate
-            ORDER BY sum(o_totalprice)
+            FROM  Orders o,
+                  Customer c
+            WHERE o.o_custkey = c.c_custkey AND c.c_nationkey = Nation.n_nationkey
+            GROUP BY o.o_orderdate AS orderdate
+            ORDER BY sum(o.o_totalprice)
             LIMIT 3
         ) AS aggregates
 from  Nation,
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q02_minimum_cost_supplier/q02_minimum_cost_supplier.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q02_minimum_cost_supplier/q02_minimum_cost_supplier.3.query.sqlpp
index e1704fe..1decc72 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q02_minimum_cost_supplier/q02_minimum_cost_supplier.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q02_minimum_cost_supplier/q02_minimum_cost_supplier.3.query.sqlpp
@@ -22,11 +22,11 @@
 
 WITH q2_minimum_cost_supplier_tmp1 AS
 (
- SELECT s_acctbal, s_name, n_name, p_partkey, ps_supplycost, p_mfgr, s_address, s_phone, s_comment
- FROM Nation JOIN Region ON n_regionkey = r_regionkey and r_name = 'EUROPE'
- JOIN Supplier ON s_nationkey = n_nationkey
- JOIN Partsupp ON s_suppkey = ps_suppkey
- JOIN Part ON p_partkey = ps_partkey AND p_type LIKE '%BRASS'
+ SELECT s.s_acctbal, s.s_name, n.n_name, p.p_partkey, ps.ps_supplycost, p.p_mfgr, s.s_address, s.s_phone, s.s_comment
+ FROM Nation n JOIN Region r ON n.n_regionkey = r.r_regionkey and r.r_name = 'EUROPE'
+ JOIN Supplier s ON s.s_nationkey = n.n_nationkey
+ JOIN Partsupp ps ON s.s_suppkey = ps.ps_suppkey
+ JOIN Part p ON p.p_partkey = ps.ps_partkey AND p.p_type LIKE '%BRASS'
 ),
 q2_minimum_cost_supplier_tmp2 AS
 (
@@ -35,10 +35,10 @@
   GROUP BY p_partkey
 )
 
-SELECT s_acctbal, s_name, n_name, t1.p_partkey, p_mfgr, s_address, s_phone, s_comment
+SELECT t1.s_acctbal, t1.s_name, t1.n_name, t1.p_partkey, t1.p_mfgr, t1.s_address, t1.s_phone, t1.s_comment
 FROM
   q2_minimum_cost_supplier_tmp1 t1 JOIN q2_minimum_cost_supplier_tmp2 t2
 ON
-  t1.p_partkey = t2.p_partkey AND ps_supplycost=ps_min_supplycost
-ORDER BY s_acctbal DESC, n_name, s_name, t1.p_partkey
+  t1.p_partkey = t2.p_partkey AND t1.ps_supplycost = t2.ps_min_supplycost
+ORDER BY t1.s_acctbal DESC, t1.n_name, t1.s_name, t1.p_partkey
 LIMIT 100;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q03_shipping_priority_nt/q03_shipping_priority_nt.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q03_shipping_priority_nt/q03_shipping_priority_nt.3.query.sqlpp
index c620bdc..f5dcb4a 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q03_shipping_priority_nt/q03_shipping_priority_nt.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q03_shipping_priority_nt/q03_shipping_priority_nt.3.query.sqlpp
@@ -21,15 +21,15 @@
 
 
 SELECT l_orderkey,
-       sum(l_extendedprice * (1 - l_discount)) AS revenue,
+       sum(l.l_extendedprice * (1 - l.l_discount)) AS revenue,
        o_orderdate,
        o_shippriority
-FROM  Customer,
-      Orders,
-      LineItem
-where c_mktsegment = 'BUILDING' AND c_custkey = o_custkey AND l_orderkey = o_orderkey AND o_orderdate < '1995-03-15' AND l_shipdate > '1995-03-15'
+FROM  Customer c,
+      Orders o,
+      LineItem l
+where c.c_mktsegment = 'BUILDING' AND c.c_custkey = o.o_custkey AND l.l_orderkey = o.o_orderkey AND o.o_orderdate < '1995-03-15' AND l.l_shipdate > '1995-03-15'
 /* +hash */
-GROUP BY l_orderkey, o_orderdate, o_shippriority
+GROUP BY l.l_orderkey, o.o_orderdate, o.o_shippriority
 ORDER BY revenue DESC,o_orderdate
 LIMIT 10
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q04_order_priority/q04_order_priority.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q04_order_priority/q04_order_priority.3.query.sqlpp
index e2e486d..c9457d5 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q04_order_priority/q04_order_priority.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q04_order_priority/q04_order_priority.3.query.sqlpp
@@ -27,11 +27,11 @@
     WHERE l_commitdate < l_receiptdate
 )
 
-SELECT o_orderpriority AS order_priority, count(Orders) AS count
-FROM Orders
-JOIN tmp
-ON l_orderkey = o_orderkey
-WHERE o_orderdate >= '1993-07-01' AND o_orderdate < '1993-10-01'
-GROUP BY o_orderpriority
+SELECT o_orderpriority AS order_priority, count(o) AS count
+FROM Orders o
+JOIN tmp t
+ON t.l_orderkey = o.o_orderkey
+WHERE o.o_orderdate >= '1993-07-01' AND o.o_orderdate < '1993-10-01'
+GROUP BY o.o_orderpriority
 ORDER BY o_orderpriority
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q05_local_supplier_volume/q05_local_supplier_volume.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q05_local_supplier_volume/q05_local_supplier_volume.3.query.sqlpp
index dce8e76..921810b 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q05_local_supplier_volume/q05_local_supplier_volume.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q05_local_supplier_volume/q05_local_supplier_volume.3.query.sqlpp
@@ -19,24 +19,24 @@
 
 USE tpch;
 
-SELECT n_name, sum(l_extendedprice * (1 - l_discount)) AS revenue
+SELECT n_name, sum(o1.l_extendedprice * (1 - o1.l_discount)) AS revenue
 FROM
-  Customer JOIN
-    ( SELECT n_name, l_extendedprice, l_discount, s_nationkey, o_custkey
-      FROM Orders JOIN
-      ( SELECT n_name, l_extendedprice, l_discount, l_orderkey, s_nationkey
-        FROM LineItem JOIN
-            (   SELECT n_name, s_suppkey, s_nationkey
-                FROM Supplier JOIN
-                (   SELECT n_name, n_nationkey
+  Customer c JOIN
+    ( SELECT l1.n_name, l1.l_extendedprice, l1.l_discount, l1.s_nationkey, o.o_custkey
+      FROM Orders o JOIN
+      ( SELECT s1.n_name, l.l_extendedprice, l.l_discount, l.l_orderkey, s1.s_nationkey
+        FROM LineItem l JOIN
+            (   SELECT n1.n_name, s.s_suppkey, s.s_nationkey
+                FROM Supplier s JOIN
+                (   SELECT n.n_name, n.n_nationkey
                     FROM Nation n JOIN Region r
-                    ON n_regionkey = r_regionkey
-                ) n1 ON s_nationkey = n_nationkey
+                    ON n.n_regionkey = r.r_regionkey
+                ) n1 ON s.s_nationkey = n1.n_nationkey
             ) s1
-        ON l_suppkey = s_suppkey
-      ) l1 ON l_orderkey = o_orderkey AND o_orderdate >= '1990-01-01'
-              AND o_orderdate < '1995-01-01'
+        ON l.l_suppkey = s1.s_suppkey
+      ) l1 ON l1.l_orderkey = o.o_orderkey AND o.o_orderdate >= '1990-01-01'
+              AND o.o_orderdate < '1995-01-01'
    ) o1
-ON c_nationkey = s_nationkey AND c_custkey = o_custkey
-GROUP BY n_name
+ON c.c_nationkey = o1.s_nationkey AND c.c_custkey = o1.o_custkey
+GROUP BY o1.n_name
 ORDER BY revenue DESC;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q07_volume_shipping/q07_volume_shipping.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q07_volume_shipping/q07_volume_shipping.3.query.sqlpp
index 0016fad..4166d0c 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q07_volume_shipping/q07_volume_shipping.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q07_volume_shipping/q07_volume_shipping.3.query.sqlpp
@@ -34,21 +34,21 @@
 SELECT supp_nation, cust_nation, l_year, sum(volume) AS revenue
 FROM
   (
-    SELECT supp_nation, cust_nation,
-      get_year(l_shipdate) AS l_year,
-       l_extendedprice * (1 - l_discount) AS volume
+    SELECT t.supp_nation, t.cust_nation,
+      get_year(l3.l_shipdate) AS l_year,
+       l3.l_extendedprice * (1 - l3.l_discount) AS volume
     FROM
       q7_volume_shipping_tmp t JOIN
-        (SELECT l_shipdate, l_extendedprice, l_discount, c_nationkey, s_nationkey
-         FROM Supplier JOIN
-           (SELECT l_shipdate, l_extendedprice, l_discount, l_suppkey, c_nationkey
-            FROM Customer JOIN
-              (SELECT l_shipdate, l_extendedprice, l_discount, l_suppkey, o_custkey
-               FROM Orders
-               JOIN LineItem ON o_orderkey = l_orderkey AND l_shipdate >= '1992-01-01'
-                    AND l_shipdate <= '1996-12-31'
-               ) l1 ON c_custkey = o_custkey
-            ) l2 ON s_suppkey = l_suppkey
+        (SELECT l2.l_shipdate, l2.l_extendedprice, l2.l_discount, l2.c_nationkey, s.s_nationkey
+         FROM Supplier s JOIN
+           (SELECT l1.l_shipdate, l1.l_extendedprice, l1.l_discount, l1.l_suppkey, c.c_nationkey
+            FROM Customer c JOIN
+              (SELECT l.l_shipdate, l.l_extendedprice, l.l_discount, l.l_suppkey, o.o_custkey
+               FROM Orders o
+               JOIN LineItem l ON o.o_orderkey = l.l_orderkey AND l.l_shipdate >= '1992-01-01'
+                    AND l.l_shipdate <= '1996-12-31'
+               ) l1 ON c.c_custkey = l1.o_custkey
+            ) l2 ON s.s_suppkey = l2.l_suppkey
          ) l3 ON t.c_nationkey = l3.c_nationkey AND t.s_nationkey = l3.s_nationkey
    ) shipping
 GROUP BY supp_nation, cust_nation, l_year
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q08_national_market_share/q08_national_market_share.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q08_national_market_share/q08_national_market_share.3.query.sqlpp
index ce91102..704ea1b 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q08_national_market_share/q08_national_market_share.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q08_national_market_share/q08_national_market_share.3.query.sqlpp
@@ -24,43 +24,43 @@
         SUM( CASE s_name = 'BRAZIL' WHEN true THEN revenue ELSE 0.0 END ) / SUM(revenue) AS mkt_share
 FROM  (
         SELECT o_year AS year,
-               l_extendedprice * (1 - l_discount) AS revenue,
-               n_name AS s_name
+               slnrcop.l_extendedprice * (1 - slnrcop.l_discount) AS revenue,
+               n.n_name AS s_name
         FROM  (
-                SELECT o_orderdate, l_discount, l_extendedprice, l_suppkey, s_nationkey
-                FROM  Supplier,
+                SELECT lnrcop.o_orderdate, lnrcop.l_discount, lnrcop.l_extendedprice, lnrcop.l_suppkey, s.s_nationkey
+                FROM  Supplier s,
                 (
-                  SELECT o_orderdate, l_discount, l_extendedprice, l_suppkey
+                  SELECT lnrco.o_orderdate, lnrco.l_discount, lnrco.l_extendedprice, lnrco.l_suppkey
                   FROM  (
-                         SELECT o_orderdate, l_partkey, l_discount, l_extendedprice, l_suppkey
-                         FROM  LineItem,
+                         SELECT nrco.o_orderdate, l.l_partkey, l.l_discount, l.l_extendedprice, l.l_suppkey
+                         FROM  LineItem l,
                                (
-                                SELECT o_orderdate, o_orderkey
-                                FROM  Orders,
+                                SELECT o.o_orderdate, o.o_orderkey
+                                FROM  Orders o,
                                       (
-                                        SELECT c_custkey
-                                        FROM  Customer,
+                                        SELECT c.c_custkey
+                                        FROM  Customer c,
                                               (
-                                                SELECT n_nationkey
-                                                FROM  Nation,
-                                                      Region
-                                                WHERE n_regionkey = r_regionkey AND r_name = 'AMERICA'
+                                                SELECT n.n_nationkey
+                                                FROM  Nation n,
+                                                      Region r
+                                                WHERE n.n_regionkey = r.r_regionkey AND r.r_name = 'AMERICA'
                                                 ) AS nr
-                                         WHERE c_nationkey = n_nationkey
+                                         WHERE c.c_nationkey = nr.n_nationkey
                                        ) AS nrc
-                                WHERE c_custkey = o_custkey
+                                WHERE nrc.c_custkey = o.o_custkey
                                 ) AS nrco
-                        WHERE l_orderkey = o_orderkey and o_orderdate >= '1995-01-01' and o_orderdate < '1996-12-31'
+                        WHERE l.l_orderkey = nrco.o_orderkey and nrco.o_orderdate >= '1995-01-01' and nrco.o_orderdate < '1996-12-31'
                         ) AS lnrco,
-                        Part
-                        WHERE p_partkey = l_partkey and p_type = 'ECONOMY ANODIZED STEEL'
+                        Part p
+                        WHERE p.p_partkey = lnrco.l_partkey and p.p_type = 'ECONOMY ANODIZED STEEL'
                     ) AS lnrcop
-                WHERE s_suppkey = l_suppkey
-                ) AS slnrcop,
-                Nation
-                LET o_year = GET_YEAR(o_orderdate)
-                WHERE s_nationkey = n_nationkey
-             ) as t
+                WHERE s.s_suppkey = lnrcop.l_suppkey
+            ) AS slnrcop,
+            Nation n
+        LET o_year = GET_YEAR(slnrcop.o_orderdate)
+        WHERE slnrcop.s_nationkey = n.n_nationkey
+    ) as t
 GROUP BY year
 ORDER BY year
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q09_product_type_profit_nt/q09_product_type_profit_nt.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q09_product_type_profit_nt/q09_product_type_profit_nt.3.query.sqlpp
index bcb3687..2e3bf7d 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q09_product_type_profit_nt/q09_product_type_profit_nt.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q09_product_type_profit_nt/q09_product_type_profit_nt.3.query.sqlpp
@@ -23,24 +23,24 @@
 SELECT nation, o_year, sum(amount) AS sum_profit
 FROM
   (
-    SELECT   n_name AS nation,
-             get_year(o_orderdate) AS o_year,
-             l_extendedprice * (1 - l_discount) -  ps_supplycost * l_quantity AS amount
+    SELECT   l3.n_name AS nation,
+             get_year(o.o_orderdate) AS o_year,
+             l3.l_extendedprice * (1 - l3.l_discount) -  l3.ps_supplycost * l3.l_quantity AS amount
     FROM
-      Orders JOIN
+      Orders o JOIN
       (
-       SELECT l_extendedprice, l_discount, l_quantity, l_orderkey, n_name, ps_supplycost
-       FROM Part JOIN
-         (SELECT l_extendedprice, l_discount, l_quantity, l_partkey, l_orderkey, n_name, ps_supplycost
-          FROM Partsupp join
-            (SELECT l_suppkey, l_extendedprice, l_discount, l_quantity, l_partkey, l_orderkey, n_name
+       SELECT l2.l_extendedprice, l2.l_discount, l2.l_quantity, l2.l_orderkey, l2.n_name, l2.ps_supplycost
+       FROM Part p JOIN
+         (SELECT l1.l_extendedprice, l1.l_discount, l1.l_quantity, l1.l_partkey, l1.l_orderkey, l1.n_name, ps.ps_supplycost
+          FROM Partsupp ps join
+            (SELECT l.l_suppkey, l.l_extendedprice, l.l_discount, l.l_quantity, l.l_partkey, l.l_orderkey, s1.n_name
              FROM
-               (SELECT s_suppkey, n_name
-                FROM Nation JOIN Supplier ON n_nationkey = s_nationkey
-               ) s1 JOIN LineItem ON s_suppkey = l_suppkey
-            ) l1 ON ps_suppkey = l_suppkey AND ps_partkey = l_partkey
-         ) l2 ON contains(p_name,'green') AND p_partkey = l_partkey
-     ) l3 ON o_orderkey = l_orderkey
+               (SELECT s.s_suppkey, n.n_name
+                FROM Nation n JOIN Supplier s ON n.n_nationkey = s.s_nationkey
+               ) s1 JOIN LineItem l ON s1.s_suppkey = l.l_suppkey
+            ) l1 ON ps.ps_suppkey = l1.l_suppkey AND ps.ps_partkey = l1.l_partkey
+         ) l2 ON contains(p.p_name,'green') AND p.p_partkey = l2.l_partkey
+     ) l3 ON o.o_orderkey = l3.l_orderkey
   ) profit
 GROUP BY nation, o_year
 ORDER BY nation, o_year desc;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q09_product_type_profit_parameter/q09_product_type_profit_parameter.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q09_product_type_profit_parameter/q09_product_type_profit_parameter.3.query.sqlpp
index d7ab8ec..9a8c03c 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q09_product_type_profit_parameter/q09_product_type_profit_parameter.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q09_product_type_profit_parameter/q09_product_type_profit_parameter.3.query.sqlpp
@@ -24,24 +24,24 @@
 SELECT nation, o_year, sum(amount) AS sum_profit
 FROM
   (
-    SELECT   n_name AS nation,
-             get_year(o_orderdate) AS o_year,
-             l_extendedprice * (1 - l_discount) -  ps_supplycost * l_quantity AS amount
+    SELECT   l3.n_name AS nation,
+             get_year(o.o_orderdate) AS o_year,
+             l3.l_extendedprice * (1 - l3.l_discount) -  l3.ps_supplycost * l3.l_quantity AS amount
     FROM
-      Orders JOIN
+      Orders o JOIN
       (
-       SELECT l_extendedprice, l_discount, l_quantity, l_orderkey, n_name, ps_supplycost
-       FROM Part JOIN
-         (SELECT l_extendedprice, l_discount, l_quantity, l_partkey, l_orderkey, n_name, ps_supplycost
-          FROM Partsupp join
-            (SELECT l_suppkey, l_extendedprice, l_discount, l_quantity, l_partkey, l_orderkey, n_name
+       SELECT l2.l_extendedprice, l2.l_discount, l2.l_quantity, l2.l_orderkey, l2.n_name, l2.ps_supplycost
+       FROM Part p JOIN
+         (SELECT l1.l_extendedprice, l1.l_discount, l1.l_quantity, l1.l_partkey, l1.l_orderkey, l1.n_name, ps.ps_supplycost
+          FROM Partsupp ps join
+            (SELECT l.l_suppkey, l.l_extendedprice, l.l_discount, l.l_quantity, l.l_partkey, l.l_orderkey, s1.n_name
              FROM
-               (SELECT s_suppkey, n_name
-                FROM Nation JOIN Supplier ON n_nationkey = s_nationkey
-               ) s1 JOIN LineItem ON s_suppkey = l_suppkey
-            ) l1 ON ps_suppkey = l_suppkey AND ps_partkey = l_partkey
-         ) l2 ON contains(p_name,'green') AND p_partkey = l_partkey
-     ) l3 ON o_orderkey = l_orderkey
+               (SELECT s.s_suppkey, n.n_name
+                FROM Nation n JOIN Supplier s ON n.n_nationkey = s.s_nationkey
+               ) s1 JOIN LineItem l ON s1.s_suppkey = l.l_suppkey
+            ) l1 ON ps.ps_suppkey = l1.l_suppkey AND ps.ps_partkey = l1.l_partkey
+         ) l2 ON contains(p.p_name,'green') AND p.p_partkey = l2.l_partkey
+     ) l3 ON o.o_orderkey = l3.l_orderkey
   ) profit
 GROUP BY nation, o_year
 ORDER BY nation, o_year desc;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q10_returned_item/q10_returned_item.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q10_returned_item/q10_returned_item.3.query.sqlpp
index ef499de..f2f15ae 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q10_returned_item/q10_returned_item.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q10_returned_item/q10_returned_item.3.query.sqlpp
@@ -24,17 +24,17 @@
        sum(l_extendedprice * (1 - l_discount)) AS revenue,
        c_acctbal, n_name, c_address, c_phone, c_comment
 FROM  (
-        SELECT c_custkey, c_name, c_acctbal, n_name, c_address, c_phone, c_comment, l_extendedprice, l_discount
-        FROM  LineItem,
+        SELECT ocn.c_custkey, ocn.c_name, ocn.c_acctbal, ocn.n_name, ocn.c_address, ocn.c_phone, ocn.c_comment, l.l_extendedprice, l.l_discount
+        FROM  LineItem l,
           (
-            SELECT  c_custkey, c_name, c_acctbal, n_name, c_address, c_phone, c_comment, o_orderkey
-            from  Orders,
-                  Customer,
-                  Nation
-            WHERE c_custkey = o_custkey AND o_orderdate >= '1993-10-01'
-                  AND o_orderdate < '1994-01-01' AND c_nationkey = n_nationkey
+            SELECT  c.c_custkey, c.c_name, c.c_acctbal, n.n_name, c.c_address, c.c_phone, c.c_comment, o.o_orderkey
+            from  Orders o,
+                  Customer c,
+                  Nation n
+            WHERE c.c_custkey = o.o_custkey AND o.o_orderdate >= '1993-10-01'
+                  AND o.o_orderdate < '1994-01-01' AND c.c_nationkey = n.n_nationkey
           ) AS ocn
-        WHERE l_orderkey = o_orderkey and l_returnflag = 'R'
+        WHERE l.l_orderkey = ocn.o_orderkey and l.l_returnflag = 'R'
       ) AS locn
 GROUP BY c_custkey, c_name, c_acctbal, c_phone, n_name, c_address, c_comment
 ORDER BY revenue DESC
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q10_returned_item_int64/q10_returned_item_int64.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q10_returned_item_int64/q10_returned_item_int64.3.query.sqlpp
index bd07d48..846954c 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q10_returned_item_int64/q10_returned_item_int64.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q10_returned_item_int64/q10_returned_item_int64.3.query.sqlpp
@@ -25,17 +25,17 @@
        sum(l_extendedprice * (1 - l_discount)) AS revenue,
        c_acctbal, n_name, c_address, c_phone, c_comment
 FROM  (
-        SELECT c_custkey, c_name, c_acctbal, n_name, c_address, c_phone, c_comment, l_extendedprice, l_discount
-        FROM  LineItem,
+        SELECT ocn.c_custkey, ocn.c_name, ocn.c_acctbal, ocn.n_name, ocn.c_address, ocn.c_phone, ocn.c_comment, l.l_extendedprice, l.l_discount
+        FROM  LineItem l,
           (
-            SELECT  c_custkey, c_name, c_acctbal, n_name, c_address, c_phone, c_comment, o_orderkey
-            from  Orders,
-                  Customer,
-                  Nation
-            WHERE c_custkey = o_custkey AND o_orderdate >= '1993-10-01'
-                  AND o_orderdate < '1994-01-01' AND c_nationkey = n_nationkey
+            SELECT  c.c_custkey, c.c_name, c.c_acctbal, n.n_name, c.c_address, c.c_phone, c.c_comment, o.o_orderkey
+            from  Orders o,
+                  Customer c,
+                  Nation n
+            WHERE c.c_custkey = o.o_custkey AND o.o_orderdate >= '1993-10-01'
+                  AND o.o_orderdate < '1994-01-01' AND c.c_nationkey = n.n_nationkey
           ) AS ocn
-        WHERE l_orderkey = o_orderkey and l_returnflag = 'R'
+        WHERE l.l_orderkey = ocn.o_orderkey and l.l_returnflag = 'R'
       ) AS locn
 GROUP BY c_custkey, c_name, c_acctbal, c_phone, n_name, c_address, c_comment
 ORDER BY revenue DESC
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q11_important_stock/q11_important_stock.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q11_important_stock/q11_important_stock.3.query.sqlpp
index b3a08e8..1b1c05a 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q11_important_stock/q11_important_stock.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q11_important_stock/q11_important_stock.3.query.sqlpp
@@ -21,30 +21,30 @@
 
 
 WITH sum as (
-      SELECT ELEMENT SUM(ps_supplycost * ps_availqty)
-      FROM  Partsupp,
+      SELECT ELEMENT SUM(ps.ps_supplycost * ps.ps_availqty)
+      FROM  Partsupp ps,
             (
-                SELECT s_suppkey
-                FROM  Supplier,
-                      Nation
-                WHERE s_nationkey = n_nationkey
+                SELECT s.s_suppkey
+                FROM  Supplier s,
+                      Nation n
+                WHERE s.s_nationkey = n.n_nationkey
             ) AS sn
-      WHERE ps_suppkey = s_suppkey
+      WHERE ps.ps_suppkey = sn.s_suppkey
 )[0]
 
 SELECT ps_partkey AS partkey, part_value
 FROM  (
-        SELECT ps_partkey,
-               sum(ps_supplycost * ps_availqty) AS part_value
-        FROM  Partsupp,
+        SELECT ps.ps_partkey,
+               sum(ps.ps_supplycost * ps.ps_availqty) AS part_value
+        FROM  Partsupp ps,
               (
-                SELECT s_suppkey
-                FROM  Supplier,
-                      Nation
-                WHERE s_nationkey = n_nationkey
+                SELECT s.s_suppkey
+                FROM  Supplier s,
+                      Nation n
+                WHERE s.s_nationkey = n.n_nationkey
               ) sn
-        WHERE ps_suppkey = s_suppkey
-        GROUP BY ps_partkey
+        WHERE ps.ps_suppkey = sn.s_suppkey
+        GROUP BY ps.ps_partkey
 ) t1
 WHERE part_value > sum * 0.00001
 ORDER BY part_value DESC
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q12_shipping/q12_shipping.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q12_shipping/q12_shipping.3.query.sqlpp
index 5d0378a..b1fdff2 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q12_shipping/q12_shipping.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q12_shipping/q12_shipping.3.query.sqlpp
@@ -21,13 +21,13 @@
 
 
 SELECT l_shipmode,
-       sum(CASE WHEN o_orderpriority = '1-URGENT' or o_orderpriority = '2-HIGH' THEN 1 ELSE 0 END) high_line_count,
-       sum(CASE o_orderpriority = '1-URGENT' or o_orderpriority = '2-HIGH' WHEN true THEN 0 ELSE 1 END) low_line_count
-FROM  LineItem,
-      Orders
-WHERE o_orderkey = l_orderkey AND l_commitdate < l_receiptdate AND
-      l_shipdate < l_commitdate AND l_receiptdate >= '1994-01-01' AND
-      l_receiptdate < '1995-01-01' AND (l_shipmode = 'MAIL' OR l_shipmode = 'SHIP')
-GROUP BY l_shipmode
+       sum(CASE WHEN o.o_orderpriority = '1-URGENT' or o.o_orderpriority = '2-HIGH' THEN 1 ELSE 0 END) high_line_count,
+       sum(CASE o.o_orderpriority = '1-URGENT' or o.o_orderpriority = '2-HIGH' WHEN true THEN 0 ELSE 1 END) low_line_count
+FROM  LineItem l,
+      Orders o
+WHERE o.o_orderkey = l.l_orderkey AND l.l_commitdate < l.l_receiptdate AND
+      l.l_shipdate < l.l_commitdate AND l.l_receiptdate >= '1994-01-01' AND
+      l.l_receiptdate < '1995-01-01' AND (l.l_shipmode = 'MAIL' OR l.l_shipmode = 'SHIP')
+GROUP BY l.l_shipmode
 ORDER BY l_shipmode
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q12_shipping_broadcast/q12_shipping_broadcast.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q12_shipping_broadcast/q12_shipping_broadcast.3.query.sqlpp
index 75b359c..28c9a9b 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q12_shipping_broadcast/q12_shipping_broadcast.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q12_shipping_broadcast/q12_shipping_broadcast.3.query.sqlpp
@@ -21,13 +21,13 @@
 
 
 SELECT l_shipmode,
-       sum(CASE WHEN o_orderpriority = '1-URGENT' or o_orderpriority = '2-HIGH' THEN 1 ELSE 0 END) high_line_count,
-       sum(CASE o_orderpriority = '1-URGENT' or o_orderpriority = '2-HIGH' WHEN true THEN 0 ELSE 1 END) low_line_count
-FROM  LineItem,
-      Orders
-WHERE l_orderkey /*+ bcast */ = o_orderkey AND l_commitdate < l_receiptdate AND
-      l_shipdate < l_commitdate AND l_receiptdate >= '1994-01-01' AND
-      l_receiptdate < '1995-01-01' AND (l_shipmode = 'MAIL' OR l_shipmode = 'SHIP')
-GROUP BY l_shipmode
+       sum(CASE WHEN o.o_orderpriority = '1-URGENT' or o.o_orderpriority = '2-HIGH' THEN 1 ELSE 0 END) high_line_count,
+       sum(CASE o.o_orderpriority = '1-URGENT' or o.o_orderpriority = '2-HIGH' WHEN true THEN 0 ELSE 1 END) low_line_count
+FROM  LineItem l,
+      Orders o
+WHERE l.l_orderkey /*+ bcast */ = o.o_orderkey AND l.l_commitdate < l.l_receiptdate AND
+      l.l_shipdate < l.l_commitdate AND l.l_receiptdate >= '1994-01-01' AND
+      l.l_receiptdate < '1995-01-01' AND (l.l_shipmode = 'MAIL' OR l.l_shipmode = 'SHIP')
+GROUP BY l.l_shipmode
 ORDER BY l_shipmode
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q13_customer_distribution/q13_customer_distribution.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q13_customer_distribution/q13_customer_distribution.3.query.sqlpp
index bd5f431..f8211c9 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q13_customer_distribution/q13_customer_distribution.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q13_customer_distribution/q13_customer_distribution.3.query.sqlpp
@@ -28,10 +28,10 @@
                            (
                             select element o_orderkey
                             from  Orders
-                            where c_custkey = o_custkey and o_comment NOT LIKE '%special%requests%'
+                            where c.c_custkey = o_custkey and o_comment NOT LIKE '%special%requests%'
                            )
                          ) AS o_orderkey_count
-                from  Customer
+                from  Customer c
         ) co
         GROUP BY c_custkey
 ) gco
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q14_promotion_effect/q14_promotion_effect.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q14_promotion_effect/q14_promotion_effect.3.query.sqlpp
index d359369..f6b80fc8 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q14_promotion_effect/q14_promotion_effect.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q14_promotion_effect/q14_promotion_effect.3.query.sqlpp
@@ -21,9 +21,9 @@
 
 
 SELECT ELEMENT 100.0 *
-     SUM( CASE WHEN p_type LIKE 'PROMO%' THEN l_extendedprice * (1 - l_discount) ELSE 0.0 END )
-     / SUM(l_extendedprice * (1 - l_discount))
-FROM  LineItem,
-      Part
-WHERE l_partkey = p_partkey AND l_shipdate >= '1995-09-01' AND l_shipdate < '1995-10-01'
+     SUM( CASE WHEN p.p_type LIKE 'PROMO%' THEN l.l_extendedprice * (1 - l.l_discount) ELSE 0.0 END )
+     / SUM(l.l_extendedprice * (1 - l.l_discount))
+FROM  LineItem l,
+      Part p
+WHERE l.l_partkey = p.p_partkey AND l.l_shipdate >= '1995-09-01' AND l.l_shipdate < '1995-10-01'
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q15_top_supplier/q15_top_supplier.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q15_top_supplier/q15_top_supplier.3.query.sqlpp
index 95a360e..ba35a74 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q15_top_supplier/q15_top_supplier.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q15_top_supplier/q15_top_supplier.3.query.sqlpp
@@ -33,13 +33,13 @@
       FROM revenue
 )[0]
 
-SELECT s_suppkey,
-       s_name,
-       s_address,
-       s_phone,
-       total_revenue
-FROM  Supplier,
-      revenue
-WHERE s_suppkey = supplier_no AND total_revenue < m + 0.000000001
-      AND total_revenue > m - 0.000000001
+SELECT s.s_suppkey,
+       s.s_name,
+       s.s_address,
+       s.s_phone,
+       r.total_revenue
+FROM  Supplier s,
+      revenue r
+WHERE s.s_suppkey = r.supplier_no AND r.total_revenue < m + 0.000000001
+      AND r.total_revenue > m - 0.000000001
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q16_parts_supplier_relationship/q16_parts_supplier_relationship.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q16_parts_supplier_relationship/q16_parts_supplier_relationship.3.query.sqlpp
index 5d9eef3..f253f86 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q16_parts_supplier_relationship/q16_parts_supplier_relationship.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q16_parts_supplier_relationship/q16_parts_supplier_relationship.3.query.sqlpp
@@ -22,16 +22,16 @@
 
 WITH tmp AS
 (
-    SELECT p_brand, p_type, p_size, ps_suppkey
+    SELECT psp.p_brand, psp.p_type, psp.p_size, psp.ps_suppkey
     FROM  (
-            SELECT p_brand, p_type, p_size, ps_suppkey
-            FROM  Partsupp,
-                  Part
-            WHERE p_partkey = ps_partkey AND p_brand != 'Brand#45' AND
-                  p_type NOT LIKE 'MEDIUM POLISHED%'
+            SELECT p.p_brand, p.p_type, p.p_size, ps.ps_suppkey
+            FROM  Partsupp ps,
+                  Part p
+            WHERE p.p_partkey = ps.ps_partkey AND p.p_brand != 'Brand#45' AND
+                  p.p_type NOT LIKE 'MEDIUM POLISHED%'
            ) AS psp,
-           Supplier
-    WHERE ps_suppkey = s_suppkey AND s_comment NOT LIKE '%Customer%Complaints%'
+           Supplier s
+    WHERE psp.ps_suppkey = s.s_suppkey AND s.s_comment NOT LIKE '%Customer%Complaints%'
 )
 
 SELECT p_brand, p_type, p_size, count(ps_suppkey) supplier_cnt
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q17_small_quantity_order_revenue/q17_small_quantity_order_revenue.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q17_small_quantity_order_revenue/q17_small_quantity_order_revenue.3.query.sqlpp
index e4f3299..569352f 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q17_small_quantity_order_revenue/q17_small_quantity_order_revenue.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q17_small_quantity_order_revenue/q17_small_quantity_order_revenue.3.query.sqlpp
@@ -27,10 +27,10 @@
     GROUP BY l_partkey
 )
 
-SELECT ELEMENT SUM(l_extendedprice) / 7.0
-FROM  tmp,
-      LineItem,
-      Part
-WHERE p_partkey = l_partkey AND p_container = 'MED BOX'
-            AND l_partkey = t_partkey AND l_quantity < t_avg_quantity
+SELECT ELEMENT SUM(l.l_extendedprice) / 7.0
+FROM  tmp t,
+      LineItem l,
+      Part p
+WHERE p.p_partkey = l.l_partkey AND p.p_container = 'MED BOX'
+            AND l.l_partkey = t.t_partkey AND l.l_quantity < t.t_avg_quantity
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q18_large_volume_customer/q18_large_volume_customer.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q18_large_volume_customer/q18_large_volume_customer.3.query.sqlpp
index 4f0561c..2b12cfd 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q18_large_volume_customer/q18_large_volume_customer.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q18_large_volume_customer/q18_large_volume_customer.3.query.sqlpp
@@ -27,14 +27,14 @@
 )
 
 SELECT c_name, c_custkey, o_orderkey, o_orderdate, o_totalprice,
-       sum(l_quantity) sum_quantity
-FROM  Customer,
-      Orders,
+       sum(l.l_quantity) sum_quantity
+FROM  Customer c,
+      Orders o,
       tmp t,
       LineItem l
-WHERE c_custkey = o_custkey AND o_orderkey = t.l_orderkey
-      AND t.l_orderkey = l.l_orderkey AND t_sum_quantity > 30
-GROUP BY c_name, c_custkey, o_orderkey, o_orderdate, o_totalprice
+WHERE c.c_custkey = o.o_custkey AND o.o_orderkey = t.l_orderkey
+      AND t.l_orderkey = l.l_orderkey AND t.t_sum_quantity > 30
+GROUP BY c.c_name, c.c_custkey, o.o_orderkey, o.o_orderdate, o.o_totalprice
 ORDER BY o_totalprice DESC,o_orderdate
 LIMIT 100
 ;
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q19_discounted_revenue/q19_discounted_revenue.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q19_discounted_revenue/q19_discounted_revenue.3.query.sqlpp
index 318e939..61f065a 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q19_discounted_revenue/q19_discounted_revenue.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q19_discounted_revenue/q19_discounted_revenue.3.query.sqlpp
@@ -21,35 +21,35 @@
 
 set `import-private-functions` `true`;
 
-SELECT ELEMENT SUM(l_extendedprice * (1 - l_discount))
-FROM LineItem
-JOIN Part
-ON p_partkey = l_partkey
+SELECT ELEMENT SUM(l.l_extendedprice * (1 - l.l_discount))
+FROM LineItem l
+JOIN Part p
+ON p.p_partkey = l.l_partkey
   WHERE
   (
-    p_brand = 'Brand#12'
-    AND regexp_contains(p_container, 'SM CASE||SM BOX||SM PACK||SM PKG')
-    AND l_quantity >= 1 and l_quantity <= 11
-    AND p_size >= 1 and p_size <= 5
-    AND regexp_contains(l_shipmode, 'AIR||AIR REG')
-    AND l_shipinstruct = 'DELIVER IN PERSON'
+    p.p_brand = 'Brand#12'
+    AND regexp_contains(p.p_container, 'SM CASE||SM BOX||SM PACK||SM PKG')
+    AND l.l_quantity >= 1 and l.l_quantity <= 11
+    AND p.p_size >= 1 and p.p_size <= 5
+    AND regexp_contains(l.l_shipmode, 'AIR||AIR REG')
+    AND l.l_shipinstruct = 'DELIVER IN PERSON'
   )
   OR
   (
-    p_brand = 'Brand#23'
-    AND regexp_contains(p_container, 'MED BAG||MED BOX||MED PKG||MED PACK')
-    AND l_quantity >= 10 and l_quantity <= 20
-    AND p_size >= 1 and p_size <= 10
-    AND regexp_contains(l_shipmode, 'AIR||AIR REG')
-    AND l_shipinstruct = 'DELIVER IN PERSON'
+    p.p_brand = 'Brand#23'
+    AND regexp_contains(p.p_container, 'MED BAG||MED BOX||MED PKG||MED PACK')
+    AND l.l_quantity >= 10 and l.l_quantity <= 20
+    AND p.p_size >= 1 and p.p_size <= 10
+    AND regexp_contains(l.l_shipmode, 'AIR||AIR REG')
+    AND l.l_shipinstruct = 'DELIVER IN PERSON'
   )
   OR
   (
-    p_brand = 'Brand#34'
-    AND regexp_contains(p_container, 'LG CASE||LG BOX||LG PACK||LG PKG')
-    AND l_quantity >= 20 and l_quantity <= 30
-    AND p_size >= 1 and p_size <= 15
-    AND regexp_contains(l_shipmode, 'AIR||AIR REG')
-    AND l_shipinstruct = 'DELIVER IN PERSON'
+    p.p_brand = 'Brand#34'
+    AND regexp_contains(p.p_container, 'LG CASE||LG BOX||LG PACK||LG PKG')
+    AND l.l_quantity >= 20 and l.l_quantity <= 30
+    AND p.p_size >= 1 and p.p_size <= 15
+    AND regexp_contains(l.l_shipmode, 'AIR||AIR REG')
+    AND l.l_shipinstruct = 'DELIVER IN PERSON'
   )
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q20_potential_part_promotion/q20_potential_part_promotion.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q20_potential_part_promotion/q20_potential_part_promotion.3.query.sqlpp
index 2c138e8..0d28df3 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q20_potential_part_promotion/q20_potential_part_promotion.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q20_potential_part_promotion/q20_potential_part_promotion.3.query.sqlpp
@@ -34,12 +34,12 @@
 ,
 q20_tmp3 AS
 (
-  SELECT ps_suppkey, ps_availqty, sum_quantity
-  FROM Partsupp
-  JOIN q20_tmp1
-  ON ps_partkey = p_partkey
-  JOIN q20_tmp2
-  ON ps_partkey = l_partkey and ps_suppkey = l_suppkey
+  SELECT ps.ps_suppkey, ps.ps_availqty, t2.sum_quantity
+  FROM Partsupp ps
+  JOIN q20_tmp1 t1
+  ON ps.ps_partkey = t1.p_partkey
+  JOIN q20_tmp2 t2
+  ON ps.ps_partkey = t2.l_partkey and ps.ps_suppkey = t2.l_suppkey
 )
 ,
 q20_tmp4 AS
@@ -50,10 +50,10 @@
   GROUP BY ps_suppkey
 )
 
-SELECT s_name, s_address
-FROM Supplier
-JOIN Nation
-ON s_nationkey = n_nationkey
-JOIN q20_tmp4
-ON s_suppkey = ps_suppkey
-ORDER BY s_name;
+SELECT s.s_name, s.s_address
+FROM Supplier s
+JOIN Nation n
+ON s.s_nationkey = n.n_nationkey
+JOIN q20_tmp4 t4
+ON s.s_suppkey = t4.ps_suppkey
+ORDER BY s.s_name;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.query.sqlpp
index 62a6d9d..13ea032 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.query.sqlpp
@@ -48,22 +48,22 @@
 
 SELECT s_name, count(t4) AS numwait
 FROM  (
-    SELECT s_name, l_suppkey, t2.l_orderkey, count_suppkey, max_suppkey
+    SELECT t3.s_name, t3.l_suppkey, t2.l_orderkey, t2.count_suppkey, t2.max_suppkey
     FROM  (
-            SELECT s_name, t1.l_orderkey AS l_orderkey, l_suppkey
+            SELECT ns.s_name, t1.l_orderkey AS l_orderkey, l.l_suppkey
             FROM  LineItem l,
                   (
-                        SELECT s_name, s_suppkey
-                        FROM Nation,
-                             Supplier
-                        WHERE s_nationkey = n_nationkey
+                        SELECT s.s_name, s.s_suppkey
+                        FROM Nation n,
+                             Supplier s
+                        WHERE s.s_nationkey = n.n_nationkey
                    ) AS ns,
-                   Orders,
+                   Orders o,
                    tmp1 AS t1
-            WHERE s_suppkey = l_suppkey AND l_receiptdate > l_commitdate
-                  AND o_orderkey = t1.l_orderkey AND l.l_orderkey = t1.l_orderkey
+            WHERE ns.s_suppkey = l.l_suppkey AND l.l_receiptdate > l.l_commitdate
+                  AND o.o_orderkey = t1.l_orderkey AND l.l_orderkey = t1.l_orderkey
           ) AS t3
-     JOIN tmp2 AS t2 ON count_suppkey >= 0 AND t3.l_orderkey = t2.l_orderkey
+     JOIN tmp2 AS t2 ON t2.count_suppkey >= 0 AND t3.l_orderkey = t2.l_orderkey
 ) AS t4
 GROUP BY s_name
 ORDER BY numwait DESC, s_name
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue562/query-issue562.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue562/query-issue562.3.query.sqlpp
index afd3db5..4a23a50 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue562/query-issue562.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue562/query-issue562.3.query.sqlpp
@@ -28,8 +28,8 @@
 
 WITH q22_customer_tmp AS
 (
-    SELECT c_acctbal, c_custkey, phone_substr AS cntrycode
-    FROM  Customer
+    SELECT c.c_acctbal, c.c_custkey, phone_substr AS cntrycode
+    FROM  Customer c
     LET  phone_substr = substring(c_phone,1,2)
     WHERE phone_substr = '13' OR phone_substr = '31' OR phone_substr = '23' OR phone_substr = '29'
           OR phone_substr = '30' OR phone_substr = '18' OR phone_substr = '17'
@@ -40,7 +40,7 @@
 WHERE coll_count((
                 SELECT ELEMENT Orders
                 FROM  Orders
-                WHERE c_custkey = o_custkey
+                WHERE ct.c_custkey = o_custkey
             )) = 0
 GROUP BY cntrycode
 ORDER BY cntrycode
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue638/query-issue638.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue638/query-issue638.3.query.sqlpp
index 5854816..cb6eca7 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue638/query-issue638.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue638/query-issue638.3.query.sqlpp
@@ -29,24 +29,24 @@
 SELECT nation, o_year, sum(amount) AS sum_profit
 FROM
   (
-    SELECT   n_name AS nation,
-             GET_YEAR(o_orderdate) AS o_year,
-             l_extendedprice * (1 - l_discount) -  ps_supplycost * l_quantity AS amount
+    SELECT   l3.n_name AS nation,
+             GET_YEAR(o.o_orderdate) AS o_year,
+             l3.l_extendedprice * (1 - l3.l_discount) -  l3.ps_supplycost * l3.l_quantity AS amount
     FROM
       Orders o JOIN
       (
-       SELECT l_extendedprice, l_discount, l_quantity, l_orderkey, n_name, ps_supplycost
+       SELECT l2.l_extendedprice, l2.l_discount, l2.l_quantity, l2.l_orderkey, l2.n_name, l2.ps_supplycost
        FROM Part p JOIN
-         (SELECT l_extendedprice, l_discount, l_quantity, l_partkey, l_orderkey, n_name, ps_supplycost
+         (SELECT l1.l_extendedprice, l1.l_discount, l1.l_quantity, l1.l_partkey, l1.l_orderkey, l1.n_name, ps.ps_supplycost
           FROM Partsupp ps join
-            (SELECT l_suppkey, l_extendedprice, l_discount, l_quantity, l_partkey, l_orderkey, n_name
+            (SELECT l.l_suppkey, l.l_extendedprice, l.l_discount, l.l_quantity, l.l_partkey, l.l_orderkey, s1.n_name
              FROM
-               (SELECT s_suppkey, n_name
-                FROM Nation n join Supplier s ON n_nationkey = s_nationkey
-               ) s1 JOIN LineItem l ON s_suppkey = l_suppkey
-            ) l1 ON ps_suppkey = l_suppkey and ps_partkey = l_partkey
-         ) l2 ON contains(p_name,'green') AND p_partkey = l_partkey
-     ) l3 ON o_orderkey = l_orderkey
+               (SELECT s.s_suppkey, n.n_name
+                FROM Nation n join Supplier s ON n.n_nationkey = s.s_nationkey
+               ) s1 JOIN LineItem l ON s1.s_suppkey = l.l_suppkey
+            ) l1 ON ps.ps_suppkey = l1.l_suppkey and ps.ps_partkey = l1.l_partkey
+         ) l2 ON contains(p.p_name,'green') AND p.p_partkey = l2.l_partkey
+     ) l3 ON o.o_orderkey = l3.l_orderkey
   ) profit
 GROUP BY nation, o_year
 ORDER BY nation, o_year desc;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue785-2/query-issue785-2.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue785-2/query-issue785-2.3.query.sqlpp
index 9254656..609ad06 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue785-2/query-issue785-2.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue785-2/query-issue785-2.3.query.sqlpp
@@ -33,19 +33,19 @@
       WHERE nation.n_nationkey = sn.n_nationkey
 ),
 X as (
-      SELECT nation_key, orderdate AS order_date, sum(o_totalprice) AS sum_price
-      FROM  t,
-            Customer,
-            Orders
-      WHERE o_custkey = c_custkey and c_nationkey = n_nationkey
-      GROUP BY o_orderdate AS orderdate, n_nationkey AS nation_key
+      SELECT nation_key, orderdate AS order_date, sum(o.o_totalprice) AS sum_price
+      FROM  t n,
+            Customer c,
+            Orders o
+      WHERE o.o_custkey = c.c_custkey and c.c_nationkey = n.n_nationkey
+      GROUP BY o.o_orderdate AS orderdate, n.n_nationkey AS nation_key
 )
 
 SELECT nation_key,
        (
             SELECT g.X.order_date AS orderdate, g.X.sum_price
             FROM  g // the X here refers to implicit variable X defined in the outer FROM.
-            ORDER BY sum_price desc
+            ORDER BY g.X.sum_price desc
             LIMIT 3
         ) AS sum_price
 FROM  X
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue785/query-issue785.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue785/query-issue785.3.query.sqlpp
index 8d4460a..541b3ec 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue785/query-issue785.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue785/query-issue785.3.query.sqlpp
@@ -36,12 +36,12 @@
             LIMIT 3
         ) AS sum_price
 FROM  (
-        SELECT nation_key, orderdate AS order_date, sum(o_totalprice) AS sum_price
-        FROM  Nation,
-              Customer,
-              Orders AS orders
-        WHERE o_custkey = c_custkey AND c_nationkey = n_nationkey
-        GROUP BY o_orderdate as orderdate, n_nationkey as nation_key
+        SELECT nation_key, orderdate AS order_date, sum(o.o_totalprice) AS sum_price
+        FROM  Nation n,
+              Customer c,
+              Orders o
+        WHERE o.o_custkey = c.c_custkey AND c.c_nationkey = n.n_nationkey
+        GROUP BY o.o_orderdate as orderdate, n.n_nationkey as nation_key
 ) AS x
 GROUP BY nation_key
 GROUP AS g
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue786/query-issue786.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue786/query-issue786.3.query.sqlpp
index a9fc808..5eda643 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue786/query-issue786.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-sql-sugar/query-issue786/query-issue786.3.query.sqlpp
@@ -29,11 +29,11 @@
 SELECT  nation.n_nationkey AS nation_key,
         nation.n_name AS name,
         (
-            SELECT orderdate AS order_date, sum(o_totalprice) AS sum_price
-            FROM  Orders,
-                  Customer
-            WHERE o_custkey = c_custkey AND c_nationkey = nation.n_nationkey
-            GROUP BY o_orderdate as orderdate
+            SELECT orderdate AS order_date, sum(o.o_totalprice) AS sum_price
+            FROM  Orders o,
+                  Customer c
+            WHERE o.o_custkey = c.c_custkey AND c.c_nationkey = nation.n_nationkey
+            GROUP BY o.o_orderdate as orderdate
             ORDER BY sum_price DESC
             LIMIT 3
         ) AS aggregates
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-with-index/q13_customer_distribution/q13_customer_distribution.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-with-index/q13_customer_distribution/q13_customer_distribution.3.query.sqlpp
index 4823a39..0c0bdaa 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-with-index/q13_customer_distribution/q13_customer_distribution.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-with-index/q13_customer_distribution/q13_customer_distribution.3.query.sqlpp
@@ -41,6 +41,6 @@
 ) as gco
 group by gco.c_count as c_count
 group as g
-let  custdist = count(( select value gco from g ))
+let  custdist = count(gco)
 order by custdist desc,c_count desc
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-with-index/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-with-index/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.query.sqlpp
index 3963de0..65293dc 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-with-index/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-with-index/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.query.sqlpp
@@ -78,6 +78,6 @@
 ) as t4
 group by t4.s_name as s_name
 group as g
-let  numwait = count(( from g select value t4 ))
+let  numwait = coll_count(( from g select value t4 ))
 order by numwait desc,s_name
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-with-index/query-issue601/query-issue601.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-with-index/query-issue601/query-issue601.3.query.sqlpp
index 3f3a50a..4689676 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-with-index/query-issue601/query-issue601.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch-with-index/query-issue601/query-issue601.3.query.sqlpp
@@ -26,7 +26,7 @@
 use tpch;
 
 
-select element {'l_linenumber':l.l_linenumber,'count_order': count((from g select value g))}
+select element {'l_linenumber':l.l_linenumber,'count_order': coll_count((from g select value g))}
 from  LineItem as l
 group by l.l_linenumber
 group as g
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch/q13_customer_distribution/q13_customer_distribution.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch/q13_customer_distribution/q13_customer_distribution.3.query.sqlpp
index 4823a39..0c0bdaa 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch/q13_customer_distribution/q13_customer_distribution.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch/q13_customer_distribution/q13_customer_distribution.3.query.sqlpp
@@ -41,6 +41,6 @@
 ) as gco
 group by gco.c_count as c_count
 group as g
-let  custdist = count(( select value gco from g ))
+let  custdist = count(gco)
 order by custdist desc,c_count desc
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.query.sqlpp
index 3963de0..65293dc 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.query.sqlpp
@@ -78,6 +78,6 @@
 ) as t4
 group by t4.s_name as s_name
 group as g
-let  numwait = count(( from g select value t4 ))
+let  numwait = coll_count(( from g select value t4 ))
 order by numwait desc,s_name
 ;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch/query-issue601/query-issue601.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch/query-issue601/query-issue601.3.query.sqlpp
index 3f3a50a..4689676 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch/query-issue601/query-issue601.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/tpch/query-issue601/query-issue601.3.query.sqlpp
@@ -26,7 +26,7 @@
 use tpch;
 
 
-select element {'l_linenumber':l.l_linenumber,'count_order': count((from g select value g))}
+select element {'l_linenumber':l.l_linenumber,'count_order': coll_count((from g select value g))}
 from  LineItem as l
 group by l.l_linenumber
 group as g
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.1.ddl.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_order_by_5/union_orderby_5.1.ddl.sqlpp
similarity index 100%
rename from asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.1.ddl.sqlpp
rename to asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_order_by_5/union_orderby_5.1.ddl.sqlpp
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.2.update.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_order_by_5/union_orderby_5.2.update.sqlpp
similarity index 100%
rename from asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.2.update.sqlpp
rename to asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_order_by_5/union_orderby_5.2.update.sqlpp
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_order_by_5/union_orderby_5.3.query.sqlpp
similarity index 91%
rename from asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp
rename to asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_order_by_5/union_orderby_5.3.query.sqlpp
index bd68de8..b527e71 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_negative_2/union_negative_2.3.query.sqlpp
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/union/union_order_by_5/union_orderby_5.3.query.sqlpp
@@ -27,4 +27,4 @@
 UNION ALL
 SELECT t.name id
 FROM FacebookUsers AS t
-ORDER BY t.id; // There is certainly no field called "t" in the union all results.
+ORDER BY t.id, id; // There is certainly no field called "t" in the union all results.
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results/dapd/q2-7/q2-7.1.adm b/asterixdb/asterix-app/src/test/resources/runtimets/results/dapd/q2-7/q2-7.1.adm
index 5839a99..5adf5db 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results/dapd/q2-7/q2-7.1.adm
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results/dapd/q2-7/q2-7.1.adm
@@ -1,2 +1,2 @@
-{ "sig_id": 14, "total_count": 3, "chapter_breakdown": [ { "chapter_name": "Laguna Beach", "$2": [ { "e": { "Event": { "event_id": 1023, "name": "Art Opening: Southern Orange County Beaches", "organizers": {{ { "name": "Jane Smith" } }}, "sponsoring_sigs": [ { "sig_id": 14, "chapter_name": "San Clemente" }, { "sig_id": 14, "chapter_name": "Laguna Beach" } ], "interest_keywords": {{ "art", "landscape", "nature", "vernissage" }}, "start_time": datetime("2011-02-24T02:00:00.000Z"), "end_time": datetime("2011-02-24T05:00:00.000Z") }, "sponsor": { "sig_id": 14, "chapter_name": "Laguna Beach" } } }, { "e": { "Event": { "event_id": 1042, "name": "Orange County Landmarks", "organizers": {{ { "name": "John Smith" } }}, "sponsoring_sigs": [ { "sig_id": 14, "chapter_name": "Laguna Beach" } ], "interest_keywords": {{ "architecture", "photography" }}, "price": 10.0, "start_time": datetime("2011-02-24T01:00:00.000Z"), "end_time": datetime("2011-02-24T03:00:00.000Z") }, "sponsor": { "sig_id": 14, "chapter_name": "Laguna Beach" } } } ] }, { "chapter_name": "San Clemente", "$2": [ { "e": { "Event": { "event_id": 1023, "name": "Art Opening: Southern Orange County Beaches", "organizers": {{ { "name": "Jane Smith" } }}, "sponsoring_sigs": [ { "sig_id": 14, "chapter_name": "San Clemente" }, { "sig_id": 14, "chapter_name": "Laguna Beach" } ], "interest_keywords": {{ "art", "landscape", "nature", "vernissage" }}, "start_time": datetime("2011-02-24T02:00:00.000Z"), "end_time": datetime("2011-02-24T05:00:00.000Z") }, "sponsor": { "sig_id": 14, "chapter_name": "San Clemente" } } } ] } ] }
-{ "sig_id": 31, "total_count": 1, "chapter_breakdown": [ { "chapter_name": "Huntington Beach", "$2": [ { "e": { "Event": { "event_id": 941, "name": "Intro to Scuba Diving", "organizers": {{ { "name": "Joseph Surfer", "affiliation": "Huntington Beach Scuba Assoc." } }}, "sponsoring_sigs": [ { "sig_id": 31, "chapter_name": "Huntington Beach" } ], "interest_keywords": {{ "scuba", "diving", "aquatics" }}, "price": 40.0, "start_time": datetime("2010-10-16T17:00:00.000Z"), "end_time": datetime("2010-10-16T20:00:00.000Z") }, "sponsor": { "sig_id": 31, "chapter_name": "Huntington Beach" } } } ] } ] }
+{ "sig_id": 14, "total_count": 3, "chapter_breakdown": [ { "chapter_name": "Laguna Beach", "$1": [ { "e": { "Event": { "event_id": 1023, "name": "Art Opening: Southern Orange County Beaches", "organizers": {{ { "name": "Jane Smith" } }}, "sponsoring_sigs": [ { "sig_id": 14, "chapter_name": "San Clemente" }, { "sig_id": 14, "chapter_name": "Laguna Beach" } ], "interest_keywords": {{ "art", "landscape", "nature", "vernissage" }}, "start_time": datetime("2011-02-24T02:00:00.000Z"), "end_time": datetime("2011-02-24T05:00:00.000Z") }, "sponsor": { "sig_id": 14, "chapter_name": "Laguna Beach" } } }, { "e": { "Event": { "event_id": 1042, "name": "Orange County Landmarks", "organizers": {{ { "name": "John Smith" } }}, "sponsoring_sigs": [ { "sig_id": 14, "chapter_name": "Laguna Beach" } ], "interest_keywords": {{ "architecture", "photography" }}, "price": 10.0, "start_time": datetime("2011-02-24T01:00:00.000Z"), "end_time": datetime("2011-02-24T03:00:00.000Z") }, "sponsor": { "sig_id": 14, "chapter_name": "Laguna Beach" } } } ] }, { "chapter_name": "San Clemente", "$1": [ { "e": { "Event": { "event_id": 1023, "name": "Art Opening: Southern Orange County Beaches", "organizers": {{ { "name": "Jane Smith" } }}, "sponsoring_sigs": [ { "sig_id": 14, "chapter_name": "San Clemente" }, { "sig_id": 14, "chapter_name": "Laguna Beach" } ], "interest_keywords": {{ "art", "landscape", "nature", "vernissage" }}, "start_time": datetime("2011-02-24T02:00:00.000Z"), "end_time": datetime("2011-02-24T05:00:00.000Z") }, "sponsor": { "sig_id": 14, "chapter_name": "San Clemente" } } } ] } ] }
+{ "sig_id": 31, "total_count": 1, "chapter_breakdown": [ { "chapter_name": "Huntington Beach", "$1": [ { "e": { "Event": { "event_id": 941, "name": "Intro to Scuba Diving", "organizers": {{ { "name": "Joseph Surfer", "affiliation": "Huntington Beach Scuba Assoc." } }}, "sponsoring_sigs": [ { "sig_id": 31, "chapter_name": "Huntington Beach" } ], "interest_keywords": {{ "scuba", "diving", "aquatics" }}, "price": 40.0, "start_time": datetime("2010-10-16T17:00:00.000Z"), "end_time": datetime("2010-10-16T20:00:00.000Z") }, "sponsor": { "sig_id": 31, "chapter_name": "Huntington Beach" } } } ] } ] }
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results/explain/explain_field_access/explain_field_access.1.adm b/asterixdb/asterix-app/src/test/resources/runtimets/results/explain/explain_field_access/explain_field_access.1.adm
index 5f6b71d..5f25e64 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results/explain/explain_field_access/explain_field_access.1.adm
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results/explain/explain_field_access/explain_field_access.1.adm
@@ -1,44 +1,44 @@
-distribute result [$$17]
+distribute result [$$36]
 -- DISTRIBUTE_RESULT  |PARTITIONED|
   exchange
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-    project ([$$17])
+    project ([$$36])
     -- STREAM_PROJECT  |PARTITIONED|
-      assign [$$17] <- [{"deptId": $#1, "star_cost": $$20}]
+      assign [$$36] <- [{"deptId": $#1, "star_cost": $$39}]
       -- ASSIGN  |PARTITIONED|
         exchange
         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-          group by ([$#1 := $$25]) decor ([]) {
-                    aggregate [$$20] <- [agg-sql-sum($$24)]
+          group by ([$#1 := $$44]) decor ([]) {
+                    aggregate [$$39] <- [agg-sql-sum($$43)]
                     -- AGGREGATE  |LOCAL|
                       nested tuple source
                       -- NESTED_TUPLE_SOURCE  |LOCAL|
                  }
-          -- SORT_GROUP_BY[$$25]  |PARTITIONED|
+          -- SORT_GROUP_BY[$$44]  |PARTITIONED|
             exchange
-            -- HASH_PARTITION_EXCHANGE [$$25]  |PARTITIONED|
-              group by ([$$25 := $$18]) decor ([]) {
-                        aggregate [$$24] <- [agg-local-sql-sum($$15)]
+            -- HASH_PARTITION_EXCHANGE [$$44]  |PARTITIONED|
+              group by ([$$44 := $$37]) decor ([]) {
+                        aggregate [$$43] <- [agg-local-sql-sum($$34)]
                         -- AGGREGATE  |LOCAL|
                           nested tuple source
                           -- NESTED_TUPLE_SOURCE  |LOCAL|
                      }
-              -- SORT_GROUP_BY[$$18]  |PARTITIONED|
+              -- SORT_GROUP_BY[$$37]  |PARTITIONED|
                 exchange
                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                  project ([$$15, $$18])
+                  project ([$$34, $$37])
                   -- STREAM_PROJECT  |PARTITIONED|
-                    assign [$$18] <- [substring($$22.getField("department_id"), 1)]
+                    assign [$$37] <- [substring($$41.getField("department_id"), 1)]
                     -- ASSIGN  |PARTITIONED|
-                      project ([$$15, $$22])
+                      project ([$$34, $$41])
                       -- STREAM_PROJECT  |PARTITIONED|
-                        assign [$$15, $$22] <- [$$e.getField("salary"), $$e.getField("dept")]
+                        assign [$$34, $$41] <- [$$e.getField("salary"), $$e.getField("dept")]
                         -- ASSIGN  |PARTITIONED|
                           project ([$$e])
                           -- STREAM_PROJECT  |PARTITIONED|
                             exchange
                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                              data-scan []<-[$$19, $$e] <- gby.Employee
+                              data-scan []<-[$$38, $$e] <- gby.Employee
                               -- DATASOURCE_SCAN  |PARTITIONED|
                                 exchange
                                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results/explain/explain_field_access_closed/explain_field_access_closed.1.adm b/asterixdb/asterix-app/src/test/resources/runtimets/results/explain/explain_field_access_closed/explain_field_access_closed.1.adm
index c984482..92df490 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results/explain/explain_field_access_closed/explain_field_access_closed.1.adm
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results/explain/explain_field_access_closed/explain_field_access_closed.1.adm
@@ -1,40 +1,40 @@
-distribute result [$$16]
+distribute result [$$35]
 -- DISTRIBUTE_RESULT  |PARTITIONED|
   exchange
   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-    project ([$$16])
+    project ([$$35])
     -- STREAM_PROJECT  |PARTITIONED|
-      assign [$$16] <- [{"deptId": $#1, "star_cost": $$19}]
+      assign [$$35] <- [{"deptId": $#1, "star_cost": $$38}]
       -- ASSIGN  |PARTITIONED|
         exchange
         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-          group by ([$#1 := $$23]) decor ([]) {
-                    aggregate [$$19] <- [agg-sql-sum($$22)]
+          group by ([$#1 := $$42]) decor ([]) {
+                    aggregate [$$38] <- [agg-sql-sum($$41)]
                     -- AGGREGATE  |LOCAL|
                       nested tuple source
                       -- NESTED_TUPLE_SOURCE  |LOCAL|
                  }
-          -- SORT_GROUP_BY[$$23]  |PARTITIONED|
+          -- SORT_GROUP_BY[$$42]  |PARTITIONED|
             exchange
-            -- HASH_PARTITION_EXCHANGE [$$23]  |PARTITIONED|
-              group by ([$$23 := $$17]) decor ([]) {
-                        aggregate [$$22] <- [agg-local-sql-sum($$14)]
+            -- HASH_PARTITION_EXCHANGE [$$42]  |PARTITIONED|
+              group by ([$$42 := $$36]) decor ([]) {
+                        aggregate [$$41] <- [agg-local-sql-sum($$33)]
                         -- AGGREGATE  |LOCAL|
                           nested tuple source
                           -- NESTED_TUPLE_SOURCE  |LOCAL|
                      }
-              -- SORT_GROUP_BY[$$17]  |PARTITIONED|
+              -- SORT_GROUP_BY[$$36]  |PARTITIONED|
                 exchange
                 -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                  project ([$$14, $$17])
+                  project ([$$33, $$36])
                   -- STREAM_PROJECT  |PARTITIONED|
-                    assign [$$17, $$14] <- [substring($$e.getField(1), 1), $$e.getField(2)]
+                    assign [$$36, $$33] <- [substring($$e.getField(1), 1), $$e.getField(2)]
                     -- ASSIGN  |PARTITIONED|
                       project ([$$e])
                       -- STREAM_PROJECT  |PARTITIONED|
                         exchange
                         -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                          data-scan []<-[$$18, $$e] <- gby.Employee
+                          data-scan []<-[$$37, $$e] <- gby.Employee
                           -- DATASOURCE_SCAN  |PARTITIONED|
                             exchange
                             -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results/misc/query-ASTERIXDB-1577/query-ASTERIXDB-1577.3.adm b/asterixdb/asterix-app/src/test/resources/runtimets/results/misc/query-ASTERIXDB-1577/query-ASTERIXDB-1577.3.adm
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results/misc/query-ASTERIXDB-1577/query-ASTERIXDB-1577.3.adm
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results/rebalance/single_dataset_with_index/single_dataset_with_index.13.adm b/asterixdb/asterix-app/src/test/resources/runtimets/results/rebalance/single_dataset_with_index/single_dataset_with_index.13.adm
index a76e980..2a155f9 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results/rebalance/single_dataset_with_index/single_dataset_with_index.13.adm
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results/rebalance/single_dataset_with_index/single_dataset_with_index.13.adm
@@ -5,28 +5,28 @@
     project ([$$l])
     -- STREAM_PROJECT  |PARTITIONED|
       exchange
-      -- SORT_MERGE_EXCHANGE [$$7(ASC), $$8(ASC) ]  |PARTITIONED|
+      -- SORT_MERGE_EXCHANGE [$$14(ASC), $$15(ASC) ]  |PARTITIONED|
         select (eq($$l.getField(10), "1994-01-20"))
         -- STREAM_SELECT  |PARTITIONED|
           exchange
           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-            unnest-map [$$7, $$8, $$l] <- index-search("LineItem", 0, "tpch", "LineItem", FALSE, FALSE, 2, $$15, $$16, 2, $$15, $$16, TRUE, TRUE, TRUE)
+            unnest-map [$$14, $$15, $$l] <- index-search("LineItem", 0, "tpch", "LineItem", FALSE, FALSE, 2, $$22, $$23, 2, $$22, $$23, TRUE, TRUE, TRUE)
             -- BTREE_SEARCH  |PARTITIONED|
               exchange
               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                order (ASC, $$15) (ASC, $$16)
-                -- STABLE_SORT [$$15(ASC), $$16(ASC)]  |PARTITIONED|
+                order (ASC, $$22) (ASC, $$23)
+                -- STABLE_SORT [$$22(ASC), $$23(ASC)]  |PARTITIONED|
                   exchange
                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                    project ([$$15, $$16])
+                    project ([$$22, $$23])
                     -- STREAM_PROJECT  |PARTITIONED|
                       exchange
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                        unnest-map [$$14, $$15, $$16] <- index-search("lineitem_shipdateIx", 0, "tpch", "LineItem", FALSE, FALSE, 1, $$12, 1, $$13, TRUE, TRUE, TRUE)
+                        unnest-map [$$21, $$22, $$23] <- index-search("lineitem_shipdateIx", 0, "tpch", "LineItem", FALSE, FALSE, 1, $$19, 1, $$20, TRUE, TRUE, TRUE)
                         -- BTREE_SEARCH  |PARTITIONED|
                           exchange
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                            assign [$$12, $$13] <- ["1994-01-20", "1994-01-20"]
+                            assign [$$19, $$20] <- ["1994-01-20", "1994-01-20"]
                             -- ASSIGN  |PARTITIONED|
                               empty-tuple-source
                               -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results/rebalance/single_dataset_with_index/single_dataset_with_index.8.adm b/asterixdb/asterix-app/src/test/resources/runtimets/results/rebalance/single_dataset_with_index/single_dataset_with_index.8.adm
index a76e980..2a155f9 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results/rebalance/single_dataset_with_index/single_dataset_with_index.8.adm
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results/rebalance/single_dataset_with_index/single_dataset_with_index.8.adm
@@ -5,28 +5,28 @@
     project ([$$l])
     -- STREAM_PROJECT  |PARTITIONED|
       exchange
-      -- SORT_MERGE_EXCHANGE [$$7(ASC), $$8(ASC) ]  |PARTITIONED|
+      -- SORT_MERGE_EXCHANGE [$$14(ASC), $$15(ASC) ]  |PARTITIONED|
         select (eq($$l.getField(10), "1994-01-20"))
         -- STREAM_SELECT  |PARTITIONED|
           exchange
           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-            unnest-map [$$7, $$8, $$l] <- index-search("LineItem", 0, "tpch", "LineItem", FALSE, FALSE, 2, $$15, $$16, 2, $$15, $$16, TRUE, TRUE, TRUE)
+            unnest-map [$$14, $$15, $$l] <- index-search("LineItem", 0, "tpch", "LineItem", FALSE, FALSE, 2, $$22, $$23, 2, $$22, $$23, TRUE, TRUE, TRUE)
             -- BTREE_SEARCH  |PARTITIONED|
               exchange
               -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                order (ASC, $$15) (ASC, $$16)
-                -- STABLE_SORT [$$15(ASC), $$16(ASC)]  |PARTITIONED|
+                order (ASC, $$22) (ASC, $$23)
+                -- STABLE_SORT [$$22(ASC), $$23(ASC)]  |PARTITIONED|
                   exchange
                   -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                    project ([$$15, $$16])
+                    project ([$$22, $$23])
                     -- STREAM_PROJECT  |PARTITIONED|
                       exchange
                       -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                        unnest-map [$$14, $$15, $$16] <- index-search("lineitem_shipdateIx", 0, "tpch", "LineItem", FALSE, FALSE, 1, $$12, 1, $$13, TRUE, TRUE, TRUE)
+                        unnest-map [$$21, $$22, $$23] <- index-search("lineitem_shipdateIx", 0, "tpch", "LineItem", FALSE, FALSE, 1, $$19, 1, $$20, TRUE, TRUE, TRUE)
                         -- BTREE_SEARCH  |PARTITIONED|
                           exchange
                           -- ONE_TO_ONE_EXCHANGE  |PARTITIONED|
-                            assign [$$12, $$13] <- ["1994-01-20", "1994-01-20"]
+                            assign [$$19, $$20] <- ["1994-01-20", "1994-01-20"]
                             -- ASSIGN  |PARTITIONED|
                               empty-tuple-source
                               -- EMPTY_TUPLE_SOURCE  |PARTITIONED|
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results/resolution/groupby_rename_with_sugar/groupby_rename_with_sugar.3.adm b/asterixdb/asterix-app/src/test/resources/runtimets/results/resolution/groupby_rename_with_sugar/groupby_rename_with_sugar.3.adm
new file mode 100644
index 0000000..d575d7f
--- /dev/null
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results/resolution/groupby_rename_with_sugar/groupby_rename_with_sugar.3.adm
@@ -0,0 +1,3 @@
+{ "g": [ { "ord": { "oid": 100, "pid": 0, "amount": 1 } }, { "ord": { "oid": 104, "pid": 0, "amount": 6 } } ], "pid": 0, "s": 7 }
+{ "g": [ { "ord": { "oid": 101, "pid": 1, "amount": 2 } }, { "ord": { "oid": 103, "pid": 1, "amount": 4 } } ], "pid": 1, "s": 6 }
+{ "g": [ { "ord": { "oid": 102, "pid": 2, "amount": 3 } } ], "pid": 2, "s": 3 }
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results/resolution/order_1/order_1.3.adm b/asterixdb/asterix-app/src/test/resources/runtimets/results/resolution/order_1/order_1.3.adm
new file mode 100644
index 0000000..c9e3657
--- /dev/null
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results/resolution/order_1/order_1.3.adm
@@ -0,0 +1,4 @@
+100
+101
+103
+104
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results/union/union_orderby_5/union_orderby_5.1.adm b/asterixdb/asterix-app/src/test/resources/runtimets/results/union/union_orderby_5/union_orderby_5.1.adm
new file mode 100644
index 0000000..6286610
--- /dev/null
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results/union/union_orderby_5/union_orderby_5.1.adm
@@ -0,0 +1,35 @@
+{ "id": 1 }
+{ "id": 1 }
+{ "id": 2 }
+{ "id": 2 }
+{ "id": 3 }
+{ "id": 3 }
+{ "id": 4 }
+{ "id": 4 }
+{ "id": 5 }
+{ "id": 5 }
+{ "id": 6 }
+{ "id": 6 }
+{ "id": 7 }
+{ "id": 7 }
+{ "id": 8 }
+{ "id": 8 }
+{ "id": 9 }
+{ "id": 9 }
+{ "id": 10 }
+{ "id": 10 }
+{ "id": 11 }
+{ "id": 12 }
+{ "id": 13 }
+{ "id": 14 }
+{ "id": 15 }
+{ "id": "BramHatch" }
+{ "id": "EmoryUnk" }
+{ "id": "IsbelDull" }
+{ "id": "MargaritaStoddard" }
+{ "id": "NicholasStroh" }
+{ "id": "NilaMilliron" }
+{ "id": "SuzannaTillson" }
+{ "id": "VonKemble" }
+{ "id": "WillisWynne" }
+{ "id": "WoodrowNehling" }
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/big-object/big_object_groupby/big_object_groupby.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/big-object/big_object_groupby/big_object_groupby.3.ast
index 5a85eb5..64a6455 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/big-object/big_object_groupby/big_object_groupby.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/big-object/big_object_groupby/big_object_groupby.3.ast
@@ -13,10 +13,9 @@
     :
     (
       SELECT ELEMENT [
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [i]
-        Variable [ Name=$partkey ]
+      FunctionCall asterix.field-access-by-name@2[
         Variable [ Name=$g ]
+        LiteralExpr [STRING] [i]
       ]
       ]
       FROM [        Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/dapd/q2/q2.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/dapd/q2/q2.3.ast
index 33df02e..809eb1d 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/dapd/q2/q2.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/dapd/q2/q2.3.ast
@@ -51,7 +51,7 @@
       LiteralExpr [LONG] [1]
       ]
       FROM [        Variable [ Name=$es ]
-        AS Variable [ Name=#1 ]
+        AS Variable [ Name=#2 ]
       ]
     )
   ]
@@ -76,7 +76,7 @@
               Field=e
             ]
             ]
-            FROM [              Variable [ Name=#2 ]
+            FROM [              Variable [ Name=#1 ]
               AS Variable [ Name=#3 ]
             ]
           )
@@ -97,7 +97,7 @@
         ]
         Field=chapter_name
       ]
-      GROUP AS Variable [ Name=#2 ]
+      GROUP AS Variable [ Name=#1 ]
       (
         e:=Variable [ Name=$e ]
       )
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/flwor/at06/at06.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/flwor/at06/at06.3.ast
index 851c946..295e8db 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/flwor/at06/at06.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/flwor/at06/at06.3.ast
@@ -54,14 +54,7 @@
       (
         LiteralExpr [STRING] [partkey]
         :
-        FieldAccessor [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [i]
-            Variable [ Name=$g ]
-            Variable [ Name=$l_partkey ]
-          ]
-          Field=l_partkey
-        ]
+        Variable [ Name=$l_partkey ]
       )
     ]
     ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-1_2.1.1/dblp-1_2.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-1_2.1.1/dblp-1_2.3.ast
index da5057d..0bce814 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-1_2.1.1/dblp-1_2.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-1_2.1.1/dblp-1_2.3.ast
@@ -31,19 +31,16 @@
   (
     paper:=Variable [ Name=$paper ]
     token:=Variable [ Name=$token ]
+    id:=Variable [ Name=$id ]
   )
 
 Orderby
   FunctionCall asterix.sql-count@1[
     (
       SELECT ELEMENT [
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [id]
-        Variable [ Name=$token ]
-        Variable [ Name=$paper ]
-        Variable [ Name=$tokenGroupped ]
-        Variable [ Name=#1 ]
+      FieldAccessor [
         Variable [ Name=#2 ]
+        Field=id
       ]
       ]
       FROM [        Variable [ Name=#1 ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-1_2.1/dblp-1_2.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-1_2.1/dblp-1_2.3.ast
index da5057d..0bce814 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-1_2.1/dblp-1_2.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-1_2.1/dblp-1_2.3.ast
@@ -31,19 +31,16 @@
   (
     paper:=Variable [ Name=$paper ]
     token:=Variable [ Name=$token ]
+    id:=Variable [ Name=$id ]
   )
 
 Orderby
   FunctionCall asterix.sql-count@1[
     (
       SELECT ELEMENT [
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [id]
-        Variable [ Name=$token ]
-        Variable [ Name=$paper ]
-        Variable [ Name=$tokenGroupped ]
-        Variable [ Name=#1 ]
+      FieldAccessor [
         Variable [ Name=#2 ]
+        Field=id
       ]
       ]
       FROM [        Variable [ Name=#1 ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-1_2/dblp-1_2.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-1_2/dblp-1_2.3.ast
index 82bc1af..6c993a7 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-1_2/dblp-1_2.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-1_2/dblp-1_2.3.ast
@@ -31,19 +31,16 @@
   (
     paper:=Variable [ Name=$paper ]
     token:=Variable [ Name=$token ]
+    paperid:=Variable [ Name=$paperid ]
   )
 
 Orderby
   FunctionCall asterix.sql-count@1[
     (
       SELECT ELEMENT [
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [paperid]
-        Variable [ Name=$token ]
-        Variable [ Name=$paper ]
-        Variable [ Name=$tokenGroupped ]
-        Variable [ Name=#1 ]
+      FieldAccessor [
         Variable [ Name=#2 ]
+        Field=paperid
       ]
       ]
       FROM [        Variable [ Name=#1 ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2.1_5.3.1/dblp-2.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2.1_5.3.1/dblp-2.3.ast
index 41f326c..7f0f199 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2.1_5.3.1/dblp-2.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2.1_5.3.1/dblp-2.3.ast
@@ -26,15 +26,13 @@
   AS Variable [ Name=$paperDBLP ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensDBLP]
-      Variable [ Name=$paperDBLP ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
-      FunctionCall asterix.resolve@-1[
+      FunctionCall asterix.dataset@1[
         LiteralExpr [STRING] [lenDBLP]
-        Variable [ Name=$paperDBLP ]
       ]
       LiteralExpr [FLOAT] [0.5]
     ]
@@ -100,25 +98,16 @@
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$lenDBLP ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokenGroupped ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=#1 ]
+              FieldAccessor [
                 Variable [ Name=#2 ]
-                Variable [ Name=$idDBLP ]
+                Field=id
               ]
               ]
               FROM [                Variable [ Name=#1 ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2.2/dblp-2.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2.2/dblp-2.3.ast
index 0670274..eb4a457 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2.2/dblp-2.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2.2/dblp-2.3.ast
@@ -26,16 +26,14 @@
   AS Variable [ Name=$paperDBLP ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensDBLP]
-      Variable [ Name=$paperDBLP ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_2/dblp-2_2.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_2/dblp-2_2.3.ast
index aa31821..8b01dd1 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_2/dblp-2_2.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_2/dblp-2_2.3.ast
@@ -68,21 +68,16 @@
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$token ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokenGroupped ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=#1 ]
+              FieldAccessor [
                 Variable [ Name=#2 ]
+                Field=id
               ]
               ]
               FROM [                Variable [ Name=#1 ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_3/dblp-2_3.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_3/dblp-2_3.3.ast
index 2bc4c27..aa90364 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_3/dblp-2_3.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_3/dblp-2_3.3.ast
@@ -71,22 +71,16 @@
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$token ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokenGroupped ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=#1 ]
+              FieldAccessor [
                 Variable [ Name=#2 ]
-                Variable [ Name=$idDBLP ]
+                Field=id
               ]
               ]
               FROM [                Variable [ Name=#1 ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_4/dblp-2_4.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_4/dblp-2_4.3.ast
index 79263fe..119cb92 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_4/dblp-2_4.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_4/dblp-2_4.3.ast
@@ -74,23 +74,16 @@
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokenGroupped ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=#1 ]
+              FieldAccessor [
                 Variable [ Name=#2 ]
-                Variable [ Name=$idDBLP ]
+                Field=id
               ]
               ]
               FROM [                Variable [ Name=#1 ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5.1/dblp-2_5.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5.1/dblp-2_5.3.ast
index 6285071..8bf8081 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5.1/dblp-2_5.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5.1/dblp-2_5.3.ast
@@ -84,24 +84,16 @@
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$lenDBLP ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokenGrouped ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=#1 ]
+              FieldAccessor [
                 Variable [ Name=#2 ]
-                Variable [ Name=$idDBLP ]
+                Field=id
               ]
               ]
               FROM [                Variable [ Name=#1 ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5.2/dblp-2_5.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5.2/dblp-2_5.3.ast
index 6285071..8bf8081 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5.2/dblp-2_5.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5.2/dblp-2_5.3.ast
@@ -84,24 +84,16 @@
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$lenDBLP ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokenGrouped ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=#1 ]
+              FieldAccessor [
                 Variable [ Name=#2 ]
-                Variable [ Name=$idDBLP ]
+                Field=id
               ]
               ]
               FROM [                Variable [ Name=#1 ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5.3.1/dblp-2_5.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5.3.1/dblp-2_5.3.ast
index 6285071..8bf8081 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5.3.1/dblp-2_5.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5.3.1/dblp-2_5.3.ast
@@ -84,24 +84,16 @@
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$lenDBLP ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokenGrouped ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=#1 ]
+              FieldAccessor [
                 Variable [ Name=#2 ]
-                Variable [ Name=$idDBLP ]
+                Field=id
               ]
               ]
               FROM [                Variable [ Name=#1 ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5.3/dblp-2_5.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5.3/dblp-2_5.3.ast
index 6285071..8bf8081 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5.3/dblp-2_5.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5.3/dblp-2_5.3.ast
@@ -84,24 +84,16 @@
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$lenDBLP ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokenGrouped ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=#1 ]
+              FieldAccessor [
                 Variable [ Name=#2 ]
-                Variable [ Name=$idDBLP ]
+                Field=id
               ]
               ]
               FROM [                Variable [ Name=#1 ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5/dblp-2_5.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5/dblp-2_5.3.ast
index 93a6318..57865ba 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5/dblp-2_5.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-2_5/dblp-2_5.3.ast
@@ -84,24 +84,16 @@
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$lenDBLP ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokenGroupped ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=#1 ]
+              FieldAccessor [
                 Variable [ Name=#2 ]
-                Variable [ Name=$idDBLP ]
+                Field=id
               ]
               ]
               FROM [                Variable [ Name=#1 ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-3_1.1/dblp-3_1.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-3_1.1/dblp-3_1.3.ast
index cda779d..630f9b0 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-3_1.1/dblp-3_1.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-3_1.1/dblp-3_1.3.ast
@@ -40,20 +40,7 @@
         LiteralExpr [STRING] [sim]
         :
         IndexAccessor [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [sim]
-            Variable [ Name=#5 ]
-            Variable [ Name=$lenLeft ]
-            Variable [ Name=$idLeft ]
-            Variable [ Name=$lenRight ]
-            Variable [ Name=$tokensLeft ]
-            Variable [ Name=$prefixTokenRight ]
-            Variable [ Name=$tokensRight ]
-            Variable [ Name=$paperLeft ]
-            Variable [ Name=$paperRight ]
-            Variable [ Name=$idRight ]
-            Variable [ Name=$prefixTokenLeft ]
-          ]
+          Variable [ Name=$sim ]
           Index:           LiteralExpr [LONG] [0]
         ]
       )
@@ -65,15 +52,13 @@
       AS Variable [ Name=$paperLeft ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensLeft]
-          Variable [ Name=$paperLeft ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
-          FunctionCall asterix.resolve@-1[
+          FunctionCall asterix.dataset@1[
             LiteralExpr [STRING] [lenLeft]
-            Variable [ Name=$paperLeft ]
           ]
           LiteralExpr [FLOAT] [0.5]
         ]
@@ -86,19 +71,13 @@
       AS Variable [ Name=$paperRight ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensRight]
-          Variable [ Name=$paperLeft ]
-          Variable [ Name=$paperRight ]
-          Variable [ Name=$prefixTokenLeft ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
-          FunctionCall asterix.resolve@-1[
+          FunctionCall asterix.dataset@1[
             LiteralExpr [STRING] [lenRight]
-            Variable [ Name=$paperLeft ]
-            Variable [ Name=$paperRight ]
-            Variable [ Name=$prefixTokenLeft ]
           ]
           LiteralExpr [FLOAT] [0.5]
         ]
@@ -150,7 +129,7 @@
               Variable [ Name=$tokenGroupped ]
               :=
               Variable [ Name=$token ]
-              GROUP AS Variable [ Name=#1 ]
+              GROUP AS Variable [ Name=#2 ]
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
@@ -161,12 +140,12 @@
                 (
                   SELECT ELEMENT [
                   FieldAccessor [
-                    Variable [ Name=#2 ]
+                    Variable [ Name=#4 ]
                     Field=paper
                   ]
                   ]
-                  FROM [                    Variable [ Name=#1 ]
-                    AS Variable [ Name=#2 ]
+                  FROM [                    Variable [ Name=#2 ]
+                    AS Variable [ Name=#4 ]
                   ]
                 )
               ]
@@ -246,12 +225,12 @@
                 (
                   SELECT ELEMENT [
                   FieldAccessor [
-                    Variable [ Name=#4 ]
+                    Variable [ Name=#5 ]
                     Field=paper
                   ]
                   ]
                   FROM [                    Variable [ Name=#3 ]
-                    AS Variable [ Name=#4 ]
+                    AS Variable [ Name=#5 ]
                   ]
                 )
               ]
@@ -326,12 +305,20 @@
         Variable [ Name=$paperRight ]
         Field=id
       ]
-      GROUP AS Variable [ Name=#5 ]
+      Variable [ Name=$sim ]
+      :=
+      Variable [ Name=$sim ]
+      GROUP AS Variable [ Name=#1 ]
       (
         paperLeft:=Variable [ Name=$paperLeft ]
         prefixTokenLeft:=Variable [ Name=$prefixTokenLeft ]
         paperRight:=Variable [ Name=$paperRight ]
         prefixTokenRight:=Variable [ Name=$prefixTokenRight ]
+        lenLeft:=Variable [ Name=$lenLeft ]
+        tokensLeft:=Variable [ Name=$tokensLeft ]
+        lenRight:=Variable [ Name=$lenRight ]
+        tokensRight:=Variable [ Name=$tokensRight ]
+        sim:=Variable [ Name=$sim ]
       )
 
   )
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-3_1.2/dblp-3_1.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-3_1.2/dblp-3_1.3.ast
index cda779d..630f9b0 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-3_1.2/dblp-3_1.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-3_1.2/dblp-3_1.3.ast
@@ -40,20 +40,7 @@
         LiteralExpr [STRING] [sim]
         :
         IndexAccessor [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [sim]
-            Variable [ Name=#5 ]
-            Variable [ Name=$lenLeft ]
-            Variable [ Name=$idLeft ]
-            Variable [ Name=$lenRight ]
-            Variable [ Name=$tokensLeft ]
-            Variable [ Name=$prefixTokenRight ]
-            Variable [ Name=$tokensRight ]
-            Variable [ Name=$paperLeft ]
-            Variable [ Name=$paperRight ]
-            Variable [ Name=$idRight ]
-            Variable [ Name=$prefixTokenLeft ]
-          ]
+          Variable [ Name=$sim ]
           Index:           LiteralExpr [LONG] [0]
         ]
       )
@@ -65,15 +52,13 @@
       AS Variable [ Name=$paperLeft ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensLeft]
-          Variable [ Name=$paperLeft ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
-          FunctionCall asterix.resolve@-1[
+          FunctionCall asterix.dataset@1[
             LiteralExpr [STRING] [lenLeft]
-            Variable [ Name=$paperLeft ]
           ]
           LiteralExpr [FLOAT] [0.5]
         ]
@@ -86,19 +71,13 @@
       AS Variable [ Name=$paperRight ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensRight]
-          Variable [ Name=$paperLeft ]
-          Variable [ Name=$paperRight ]
-          Variable [ Name=$prefixTokenLeft ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
-          FunctionCall asterix.resolve@-1[
+          FunctionCall asterix.dataset@1[
             LiteralExpr [STRING] [lenRight]
-            Variable [ Name=$paperLeft ]
-            Variable [ Name=$paperRight ]
-            Variable [ Name=$prefixTokenLeft ]
           ]
           LiteralExpr [FLOAT] [0.5]
         ]
@@ -150,7 +129,7 @@
               Variable [ Name=$tokenGroupped ]
               :=
               Variable [ Name=$token ]
-              GROUP AS Variable [ Name=#1 ]
+              GROUP AS Variable [ Name=#2 ]
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
@@ -161,12 +140,12 @@
                 (
                   SELECT ELEMENT [
                   FieldAccessor [
-                    Variable [ Name=#2 ]
+                    Variable [ Name=#4 ]
                     Field=paper
                   ]
                   ]
-                  FROM [                    Variable [ Name=#1 ]
-                    AS Variable [ Name=#2 ]
+                  FROM [                    Variable [ Name=#2 ]
+                    AS Variable [ Name=#4 ]
                   ]
                 )
               ]
@@ -246,12 +225,12 @@
                 (
                   SELECT ELEMENT [
                   FieldAccessor [
-                    Variable [ Name=#4 ]
+                    Variable [ Name=#5 ]
                     Field=paper
                   ]
                   ]
                   FROM [                    Variable [ Name=#3 ]
-                    AS Variable [ Name=#4 ]
+                    AS Variable [ Name=#5 ]
                   ]
                 )
               ]
@@ -326,12 +305,20 @@
         Variable [ Name=$paperRight ]
         Field=id
       ]
-      GROUP AS Variable [ Name=#5 ]
+      Variable [ Name=$sim ]
+      :=
+      Variable [ Name=$sim ]
+      GROUP AS Variable [ Name=#1 ]
       (
         paperLeft:=Variable [ Name=$paperLeft ]
         prefixTokenLeft:=Variable [ Name=$prefixTokenLeft ]
         paperRight:=Variable [ Name=$paperRight ]
         prefixTokenRight:=Variable [ Name=$prefixTokenRight ]
+        lenLeft:=Variable [ Name=$lenLeft ]
+        tokensLeft:=Variable [ Name=$tokensLeft ]
+        lenRight:=Variable [ Name=$lenRight ]
+        tokensRight:=Variable [ Name=$tokensRight ]
+        sim:=Variable [ Name=$sim ]
       )
 
   )
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-3_1/dblp-3_1.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-3_1/dblp-3_1.3.ast
index 196972b..9af07aa 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-3_1/dblp-3_1.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-3_1/dblp-3_1.3.ast
@@ -50,20 +50,7 @@
         LiteralExpr [STRING] [sim]
         :
         IndexAccessor [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [sim]
-            Variable [ Name=#5 ]
-            Variable [ Name=$lenLeft ]
-            Variable [ Name=$idLeft ]
-            Variable [ Name=$lenRight ]
-            Variable [ Name=$tokensLeft ]
-            Variable [ Name=$prefixTokenRight ]
-            Variable [ Name=$tokensRight ]
-            Variable [ Name=$paperLeft ]
-            Variable [ Name=$paperRight ]
-            Variable [ Name=$idRight ]
-            Variable [ Name=$prefixTokenLeft ]
-          ]
+          Variable [ Name=$sim ]
           Index:           LiteralExpr [LONG] [0]
         ]
       )
@@ -75,17 +62,13 @@
       AS Variable [ Name=$paperLeft ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensLeft]
-          Variable [ Name=$paperLeft ]
-          Variable [ Name=$paperRight ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
-          FunctionCall asterix.resolve@-1[
+          FunctionCall asterix.dataset@1[
             LiteralExpr [STRING] [lenLeft]
-            Variable [ Name=$paperLeft ]
-            Variable [ Name=$paperRight ]
           ]
           LiteralExpr [FLOAT] [0.5]
         ]
@@ -98,19 +81,13 @@
       AS Variable [ Name=$paperRight ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensRight]
-          Variable [ Name=$paperLeft ]
-          Variable [ Name=$paperRight ]
-          Variable [ Name=$prefixTokenLeft ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
-          FunctionCall asterix.resolve@-1[
+          FunctionCall asterix.dataset@1[
             LiteralExpr [STRING] [lenRight]
-            Variable [ Name=$paperLeft ]
-            Variable [ Name=$paperRight ]
-            Variable [ Name=$prefixTokenLeft ]
           ]
           LiteralExpr [FLOAT] [0.5]
         ]
@@ -162,7 +139,7 @@
               Variable [ Name=$tokenGroupped ]
               :=
               Variable [ Name=$token ]
-              GROUP AS Variable [ Name=#1 ]
+              GROUP AS Variable [ Name=#2 ]
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
@@ -173,12 +150,12 @@
                 (
                   SELECT ELEMENT [
                   FieldAccessor [
-                    Variable [ Name=#2 ]
+                    Variable [ Name=#4 ]
                     Field=paper
                   ]
                   ]
-                  FROM [                    Variable [ Name=#1 ]
-                    AS Variable [ Name=#2 ]
+                  FROM [                    Variable [ Name=#2 ]
+                    AS Variable [ Name=#4 ]
                   ]
                 )
               ]
@@ -258,12 +235,12 @@
                 (
                   SELECT ELEMENT [
                   FieldAccessor [
-                    Variable [ Name=#4 ]
+                    Variable [ Name=#5 ]
                     Field=paper
                   ]
                   ]
                   FROM [                    Variable [ Name=#3 ]
-                    AS Variable [ Name=#4 ]
+                    AS Variable [ Name=#5 ]
                   ]
                 )
               ]
@@ -338,12 +315,20 @@
         Variable [ Name=$paperRight ]
         Field=id
       ]
-      GROUP AS Variable [ Name=#5 ]
+      Variable [ Name=$sim ]
+      :=
+      Variable [ Name=$sim ]
+      GROUP AS Variable [ Name=#1 ]
       (
         paperLeft:=Variable [ Name=$paperLeft ]
         prefixTokenLeft:=Variable [ Name=$prefixTokenLeft ]
         paperRight:=Variable [ Name=$paperRight ]
         prefixTokenRight:=Variable [ Name=$prefixTokenRight ]
+        lenLeft:=Variable [ Name=$lenLeft ]
+        tokensLeft:=Variable [ Name=$tokensLeft ]
+        lenRight:=Variable [ Name=$lenRight ]
+        tokensRight:=Variable [ Name=$tokensRight ]
+        sim:=Variable [ Name=$sim ]
       )
 
   )
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_1/dblp-csx-2_1.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_1/dblp-csx-2_1.3.ast
index 0318cb3..2fe46a5 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_1/dblp-csx-2_1.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_1/dblp-csx-2_1.3.ast
@@ -29,16 +29,14 @@
   AS Variable [ Name=$paperDBLP ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensDBLP]
-      Variable [ Name=$paperDBLP ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
@@ -52,20 +50,14 @@
   AS Variable [ Name=$paperCSX ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensCSX]
-      Variable [ Name=$prefixTokenDBLP ]
-      Variable [ Name=$paperDBLP ]
-      Variable [ Name=$paperCSX ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensCSX]
-          Variable [ Name=$prefixTokenDBLP ]
-          Variable [ Name=$paperDBLP ]
-          Variable [ Name=$paperCSX ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
@@ -108,7 +100,7 @@
           Variable [ Name=$tokenGroupped ]
           :=
           Variable [ Name=$token ]
-          GROUP AS Variable [ Name=#1 ]
+          GROUP AS Variable [ Name=#2 ]
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
@@ -119,12 +111,12 @@
             (
               SELECT ELEMENT [
               FieldAccessor [
-                Variable [ Name=#2 ]
+                Variable [ Name=#4 ]
                 Field=paper
               ]
               ]
-              FROM [                Variable [ Name=#1 ]
-                AS Variable [ Name=#2 ]
+              FROM [                Variable [ Name=#2 ]
+                AS Variable [ Name=#4 ]
               ]
             )
           ]
@@ -194,12 +186,12 @@
             (
               SELECT ELEMENT [
               FieldAccessor [
-                Variable [ Name=#4 ]
+                Variable [ Name=#5 ]
                 Field=paper
               ]
               ]
               FROM [                Variable [ Name=#3 ]
-                AS Variable [ Name=#4 ]
+                AS Variable [ Name=#5 ]
               ]
             )
           ]
@@ -277,12 +269,15 @@
   Variable [ Name=$sim ]
   :=
   Variable [ Name=$sim ]
-  GROUP AS Variable [ Name=#5 ]
+  GROUP AS Variable [ Name=#1 ]
   (
     paperDBLP:=Variable [ Name=$paperDBLP ]
     prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
     paperCSX:=Variable [ Name=$paperCSX ]
     prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+    tokensDBLP:=Variable [ Name=$tokensDBLP ]
+    tokensCSX:=Variable [ Name=$tokensCSX ]
+    sim:=Variable [ Name=$sim ]
   )
 
 Orderby
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_2/dblp-csx-2_2.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_2/dblp-csx-2_2.3.ast
index 05d6767..0b82baa 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_2/dblp-csx-2_2.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_2/dblp-csx-2_2.3.ast
@@ -29,16 +29,14 @@
   AS Variable [ Name=$paperDBLP ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensDBLP]
-      Variable [ Name=$paperDBLP ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
@@ -52,20 +50,14 @@
   AS Variable [ Name=$paperCSX ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensCSX]
-      Variable [ Name=$prefixTokenDBLP ]
-      Variable [ Name=$paperDBLP ]
-      Variable [ Name=$paperCSX ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensCSX]
-          Variable [ Name=$prefixTokenDBLP ]
-          Variable [ Name=$paperDBLP ]
-          Variable [ Name=$paperCSX ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
@@ -114,32 +106,24 @@
           Variable [ Name=$tokenGroupped ]
           :=
           Variable [ Name=$token ]
-          GROUP AS Variable [ Name=#1 ]
+          GROUP AS Variable [ Name=#2 ]
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$prefixTokenCSX ]
-                Variable [ Name=$token ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokenGroupped ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=$paperCSX ]
-                Variable [ Name=#1 ]
-                Variable [ Name=#2 ]
+              FieldAccessor [
+                Variable [ Name=#4 ]
+                Field=id
               ]
               ]
-              FROM [                Variable [ Name=#1 ]
-                AS Variable [ Name=#2 ]
+              FROM [                Variable [ Name=#2 ]
+                AS Variable [ Name=#4 ]
               ]
             )
           ]
@@ -208,29 +192,20 @@
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=#4 ]
-                Variable [ Name=$prefixTokenCSX ]
-                Variable [ Name=$token ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokenGroupped ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$tokensDBLP ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=$paperCSX ]
-                Variable [ Name=#3 ]
+              FieldAccessor [
+                Variable [ Name=#5 ]
+                Field=id
               ]
               ]
               FROM [                Variable [ Name=#3 ]
-                AS Variable [ Name=#4 ]
+                AS Variable [ Name=#5 ]
               ]
             )
           ]
@@ -308,12 +283,15 @@
   Variable [ Name=$sim ]
   :=
   Variable [ Name=$sim ]
-  GROUP AS Variable [ Name=#5 ]
+  GROUP AS Variable [ Name=#1 ]
   (
     paperDBLP:=Variable [ Name=$paperDBLP ]
     prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
     paperCSX:=Variable [ Name=$paperCSX ]
     prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+    tokensDBLP:=Variable [ Name=$tokensDBLP ]
+    tokensCSX:=Variable [ Name=$tokensCSX ]
+    sim:=Variable [ Name=$sim ]
   )
 
 Orderby
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_3/dblp-csx-2_3.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_3/dblp-csx-2_3.3.ast
index b6dfb5d..d51effa 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_3/dblp-csx-2_3.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_3/dblp-csx-2_3.3.ast
@@ -29,16 +29,14 @@
   AS Variable [ Name=$paperDBLP ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensDBLP]
-      Variable [ Name=$paperDBLP ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
@@ -52,20 +50,14 @@
   AS Variable [ Name=$paperCSX ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensCSX]
-      Variable [ Name=$prefixTokenDBLP ]
-      Variable [ Name=$paperDBLP ]
-      Variable [ Name=$paperCSX ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensCSX]
-          Variable [ Name=$prefixTokenDBLP ]
-          Variable [ Name=$paperDBLP ]
-          Variable [ Name=$paperCSX ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
@@ -120,33 +112,24 @@
           Variable [ Name=$tokenGroupped ]
           :=
           Variable [ Name=$token ]
-          GROUP AS Variable [ Name=#1 ]
+          GROUP AS Variable [ Name=#2 ]
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$prefixTokenCSX ]
-                Variable [ Name=$token ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokenGroupped ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=$paperCSX ]
-                Variable [ Name=#1 ]
-                Variable [ Name=#2 ]
-                Variable [ Name=$idDBLP ]
+              FieldAccessor [
+                Variable [ Name=#4 ]
+                Field=id
               ]
               ]
-              FROM [                Variable [ Name=#1 ]
-                AS Variable [ Name=#2 ]
+              FROM [                Variable [ Name=#2 ]
+                AS Variable [ Name=#4 ]
               ]
             )
           ]
@@ -221,31 +204,20 @@
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokensDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=$idCSX ]
-                Variable [ Name=$idDBLP ]
-                Variable [ Name=#3 ]
-                Variable [ Name=#4 ]
-                Variable [ Name=$prefixTokenCSX ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokenGroupped ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$paperCSX ]
+              FieldAccessor [
+                Variable [ Name=#5 ]
+                Field=id
               ]
               ]
               FROM [                Variable [ Name=#3 ]
-                AS Variable [ Name=#4 ]
+                AS Variable [ Name=#5 ]
               ]
             )
           ]
@@ -317,12 +289,17 @@
   Variable [ Name=$sim ]
   :=
   Variable [ Name=$sim ]
-  GROUP AS Variable [ Name=#5 ]
+  GROUP AS Variable [ Name=#1 ]
   (
     paperDBLP:=Variable [ Name=$paperDBLP ]
     prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
     paperCSX:=Variable [ Name=$paperCSX ]
     prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+    idDBLP:=Variable [ Name=$idDBLP ]
+    tokensDBLP:=Variable [ Name=$tokensDBLP ]
+    idCSX:=Variable [ Name=$idCSX ]
+    tokensCSX:=Variable [ Name=$tokensCSX ]
+    sim:=Variable [ Name=$sim ]
   )
 
 Orderby
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_4/dblp-csx-2_4.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_4/dblp-csx-2_4.3.ast
index 4f16623..f727028 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_4/dblp-csx-2_4.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_4/dblp-csx-2_4.3.ast
@@ -29,16 +29,14 @@
   AS Variable [ Name=$paperDBLP ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensDBLP]
-      Variable [ Name=$paperDBLP ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
@@ -52,20 +50,14 @@
   AS Variable [ Name=$paperCSX ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensCSX]
-      Variable [ Name=$prefixTokenDBLP ]
-      Variable [ Name=$paperDBLP ]
-      Variable [ Name=$paperCSX ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensCSX]
-          Variable [ Name=$prefixTokenDBLP ]
-          Variable [ Name=$paperDBLP ]
-          Variable [ Name=$paperCSX ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
@@ -123,34 +115,24 @@
           Variable [ Name=$tokenGroupped ]
           :=
           Variable [ Name=$token ]
-          GROUP AS Variable [ Name=#1 ]
+          GROUP AS Variable [ Name=#2 ]
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$prefixTokenCSX ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokenGroupped ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=$paperCSX ]
-                Variable [ Name=#1 ]
-                Variable [ Name=#2 ]
-                Variable [ Name=$idDBLP ]
+              FieldAccessor [
+                Variable [ Name=#4 ]
+                Field=id
               ]
               ]
-              FROM [                Variable [ Name=#1 ]
-                AS Variable [ Name=#2 ]
+              FROM [                Variable [ Name=#2 ]
+                AS Variable [ Name=#4 ]
               ]
             )
           ]
@@ -228,33 +210,20 @@
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokensDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=$idCSX ]
-                Variable [ Name=$idDBLP ]
-                Variable [ Name=#3 ]
-                Variable [ Name=#4 ]
-                Variable [ Name=$prefixTokenCSX ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokensUnrankedCSX ]
-                Variable [ Name=$tokenGroupped ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$paperCSX ]
+              FieldAccessor [
+                Variable [ Name=#5 ]
+                Field=id
               ]
               ]
               FROM [                Variable [ Name=#3 ]
-                AS Variable [ Name=#4 ]
+                AS Variable [ Name=#5 ]
               ]
             )
           ]
@@ -316,12 +285,19 @@
   Variable [ Name=$sim ]
   :=
   Variable [ Name=$sim ]
-  GROUP AS Variable [ Name=#5 ]
+  GROUP AS Variable [ Name=#1 ]
   (
     paperDBLP:=Variable [ Name=$paperDBLP ]
     prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
     paperCSX:=Variable [ Name=$paperCSX ]
     prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+    idDBLP:=Variable [ Name=$idDBLP ]
+    tokensUnrankedDBLP:=Variable [ Name=$tokensUnrankedDBLP ]
+    tokensDBLP:=Variable [ Name=$tokensDBLP ]
+    idCSX:=Variable [ Name=$idCSX ]
+    tokensUnrankedCSX:=Variable [ Name=$tokensUnrankedCSX ]
+    tokensCSX:=Variable [ Name=$tokensCSX ]
+    sim:=Variable [ Name=$sim ]
   )
 
 Orderby
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5.1/dblp-csx-2_5.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5.1/dblp-csx-2_5.3.ast
index ec2346b..e4318eb 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5.1/dblp-csx-2_5.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5.1/dblp-csx-2_5.3.ast
@@ -17,22 +17,7 @@
     LiteralExpr [STRING] [sim]
     :
     IndexAccessor [
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [sim]
-        Variable [ Name=$lenDBLP ]
-        Variable [ Name=$tokensUnrankedDBLP ]
-        Variable [ Name=$tokensDBLP ]
-        Variable [ Name=$idCSX ]
-        Variable [ Name=$idDBLP ]
-        Variable [ Name=$prefixTokenCSX ]
-        Variable [ Name=#5 ]
-        Variable [ Name=$tokensUnrankedCSX ]
-        Variable [ Name=$prefixTokenDBLP ]
-        Variable [ Name=$lenCSX ]
-        Variable [ Name=$tokensCSX ]
-        Variable [ Name=$paperDBLP ]
-        Variable [ Name=$paperCSX ]
-      ]
+      Variable [ Name=$sim ]
       Index:       LiteralExpr [LONG] [0]
     ]
   )
@@ -44,16 +29,14 @@
   AS Variable [ Name=$paperDBLP ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensDBLP]
-      Variable [ Name=$paperDBLP ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
@@ -67,20 +50,14 @@
   AS Variable [ Name=$paperCSX ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensCSX]
-      Variable [ Name=$prefixTokenDBLP ]
-      Variable [ Name=$paperDBLP ]
-      Variable [ Name=$paperCSX ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensCSX]
-          Variable [ Name=$prefixTokenDBLP ]
-          Variable [ Name=$paperDBLP ]
-          Variable [ Name=$paperCSX ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
@@ -143,35 +120,24 @@
           Variable [ Name=$tokenGrouped ]
           :=
           Variable [ Name=$token ]
-          GROUP AS Variable [ Name=#1 ]
+          GROUP AS Variable [ Name=#2 ]
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$lenDBLP ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=#1 ]
-                Variable [ Name=#2 ]
-                Variable [ Name=$idDBLP ]
-                Variable [ Name=$prefixTokenCSX ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokenGrouped ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$paperCSX ]
+              FieldAccessor [
+                Variable [ Name=#4 ]
+                Field=id
               ]
               ]
-              FROM [                Variable [ Name=#1 ]
-                AS Variable [ Name=#2 ]
+              FROM [                Variable [ Name=#2 ]
+                AS Variable [ Name=#4 ]
               ]
             )
           ]
@@ -254,35 +220,20 @@
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$lenDBLP ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokensDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=$idCSX ]
-                Variable [ Name=$idDBLP ]
-                Variable [ Name=#3 ]
-                Variable [ Name=#4 ]
-                Variable [ Name=$prefixTokenCSX ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokensUnrankedCSX ]
-                Variable [ Name=$tokenGrouped ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$lenCSX ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$paperCSX ]
+              FieldAccessor [
+                Variable [ Name=#5 ]
+                Field=id
               ]
               ]
               FROM [                Variable [ Name=#3 ]
-                AS Variable [ Name=#4 ]
+                AS Variable [ Name=#5 ]
               ]
             )
           ]
@@ -337,12 +288,24 @@
   Variable [ Name=$idCSX ]
   :=
   Variable [ Name=$idCSX ]
-  GROUP AS Variable [ Name=#5 ]
+  Variable [ Name=$sim ]
+  :=
+  Variable [ Name=$sim ]
+  GROUP AS Variable [ Name=#1 ]
   (
     paperDBLP:=Variable [ Name=$paperDBLP ]
     prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
     paperCSX:=Variable [ Name=$paperCSX ]
     prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+    idDBLP:=Variable [ Name=$idDBLP ]
+    tokensUnrankedDBLP:=Variable [ Name=$tokensUnrankedDBLP ]
+    lenDBLP:=Variable [ Name=$lenDBLP ]
+    tokensDBLP:=Variable [ Name=$tokensDBLP ]
+    idCSX:=Variable [ Name=$idCSX ]
+    tokensUnrankedCSX:=Variable [ Name=$tokensUnrankedCSX ]
+    lenCSX:=Variable [ Name=$lenCSX ]
+    tokensCSX:=Variable [ Name=$tokensCSX ]
+    sim:=Variable [ Name=$sim ]
   )
 
 Orderby
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5.2/dblp-csx-2_5.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5.2/dblp-csx-2_5.3.ast
index ec2346b..e4318eb 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5.2/dblp-csx-2_5.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5.2/dblp-csx-2_5.3.ast
@@ -17,22 +17,7 @@
     LiteralExpr [STRING] [sim]
     :
     IndexAccessor [
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [sim]
-        Variable [ Name=$lenDBLP ]
-        Variable [ Name=$tokensUnrankedDBLP ]
-        Variable [ Name=$tokensDBLP ]
-        Variable [ Name=$idCSX ]
-        Variable [ Name=$idDBLP ]
-        Variable [ Name=$prefixTokenCSX ]
-        Variable [ Name=#5 ]
-        Variable [ Name=$tokensUnrankedCSX ]
-        Variable [ Name=$prefixTokenDBLP ]
-        Variable [ Name=$lenCSX ]
-        Variable [ Name=$tokensCSX ]
-        Variable [ Name=$paperDBLP ]
-        Variable [ Name=$paperCSX ]
-      ]
+      Variable [ Name=$sim ]
       Index:       LiteralExpr [LONG] [0]
     ]
   )
@@ -44,16 +29,14 @@
   AS Variable [ Name=$paperDBLP ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensDBLP]
-      Variable [ Name=$paperDBLP ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
@@ -67,20 +50,14 @@
   AS Variable [ Name=$paperCSX ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensCSX]
-      Variable [ Name=$prefixTokenDBLP ]
-      Variable [ Name=$paperDBLP ]
-      Variable [ Name=$paperCSX ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensCSX]
-          Variable [ Name=$prefixTokenDBLP ]
-          Variable [ Name=$paperDBLP ]
-          Variable [ Name=$paperCSX ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
@@ -143,35 +120,24 @@
           Variable [ Name=$tokenGrouped ]
           :=
           Variable [ Name=$token ]
-          GROUP AS Variable [ Name=#1 ]
+          GROUP AS Variable [ Name=#2 ]
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$lenDBLP ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=#1 ]
-                Variable [ Name=#2 ]
-                Variable [ Name=$idDBLP ]
-                Variable [ Name=$prefixTokenCSX ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokenGrouped ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$paperCSX ]
+              FieldAccessor [
+                Variable [ Name=#4 ]
+                Field=id
               ]
               ]
-              FROM [                Variable [ Name=#1 ]
-                AS Variable [ Name=#2 ]
+              FROM [                Variable [ Name=#2 ]
+                AS Variable [ Name=#4 ]
               ]
             )
           ]
@@ -254,35 +220,20 @@
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$lenDBLP ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokensDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=$idCSX ]
-                Variable [ Name=$idDBLP ]
-                Variable [ Name=#3 ]
-                Variable [ Name=#4 ]
-                Variable [ Name=$prefixTokenCSX ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokensUnrankedCSX ]
-                Variable [ Name=$tokenGrouped ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$lenCSX ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$paperCSX ]
+              FieldAccessor [
+                Variable [ Name=#5 ]
+                Field=id
               ]
               ]
               FROM [                Variable [ Name=#3 ]
-                AS Variable [ Name=#4 ]
+                AS Variable [ Name=#5 ]
               ]
             )
           ]
@@ -337,12 +288,24 @@
   Variable [ Name=$idCSX ]
   :=
   Variable [ Name=$idCSX ]
-  GROUP AS Variable [ Name=#5 ]
+  Variable [ Name=$sim ]
+  :=
+  Variable [ Name=$sim ]
+  GROUP AS Variable [ Name=#1 ]
   (
     paperDBLP:=Variable [ Name=$paperDBLP ]
     prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
     paperCSX:=Variable [ Name=$paperCSX ]
     prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+    idDBLP:=Variable [ Name=$idDBLP ]
+    tokensUnrankedDBLP:=Variable [ Name=$tokensUnrankedDBLP ]
+    lenDBLP:=Variable [ Name=$lenDBLP ]
+    tokensDBLP:=Variable [ Name=$tokensDBLP ]
+    idCSX:=Variable [ Name=$idCSX ]
+    tokensUnrankedCSX:=Variable [ Name=$tokensUnrankedCSX ]
+    lenCSX:=Variable [ Name=$lenCSX ]
+    tokensCSX:=Variable [ Name=$tokensCSX ]
+    sim:=Variable [ Name=$sim ]
   )
 
 Orderby
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5.3.1/dblp-csx-2_5.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5.3.1/dblp-csx-2_5.3.ast
index 79cfac1..0509a90 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5.3.1/dblp-csx-2_5.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5.3.1/dblp-csx-2_5.3.ast
@@ -29,16 +29,14 @@
   AS Variable [ Name=$paperDBLP ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensDBLP]
-      Variable [ Name=$paperDBLP ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
@@ -52,20 +50,14 @@
   AS Variable [ Name=$paperCSX ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensCSX]
-      Variable [ Name=$prefixTokenDBLP ]
-      Variable [ Name=$paperDBLP ]
-      Variable [ Name=$paperCSX ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensCSX]
-          Variable [ Name=$prefixTokenDBLP ]
-          Variable [ Name=$paperDBLP ]
-          Variable [ Name=$paperCSX ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
@@ -128,35 +120,24 @@
           Variable [ Name=$tokenGroupped ]
           :=
           Variable [ Name=$token ]
-          GROUP AS Variable [ Name=#1 ]
+          GROUP AS Variable [ Name=#2 ]
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$lenDBLP ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=#1 ]
-                Variable [ Name=#2 ]
-                Variable [ Name=$idDBLP ]
-                Variable [ Name=$prefixTokenCSX ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokenGroupped ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$paperCSX ]
+              FieldAccessor [
+                Variable [ Name=#4 ]
+                Field=id
               ]
               ]
-              FROM [                Variable [ Name=#1 ]
-                AS Variable [ Name=#2 ]
+              FROM [                Variable [ Name=#2 ]
+                AS Variable [ Name=#4 ]
               ]
             )
           ]
@@ -239,35 +220,20 @@
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$lenDBLP ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokensDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=$idCSX ]
-                Variable [ Name=$idDBLP ]
-                Variable [ Name=#3 ]
-                Variable [ Name=#4 ]
-                Variable [ Name=$prefixTokenCSX ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokensUnrankedCSX ]
-                Variable [ Name=$tokenGroupped ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$lenCSX ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$paperCSX ]
+              FieldAccessor [
+                Variable [ Name=#5 ]
+                Field=id
               ]
               ]
               FROM [                Variable [ Name=#3 ]
-                AS Variable [ Name=#4 ]
+                AS Variable [ Name=#5 ]
               ]
             )
           ]
@@ -325,12 +291,21 @@
   Variable [ Name=$sim ]
   :=
   Variable [ Name=$sim ]
-  GROUP AS Variable [ Name=#5 ]
+  GROUP AS Variable [ Name=#1 ]
   (
     paperDBLP:=Variable [ Name=$paperDBLP ]
     prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
     paperCSX:=Variable [ Name=$paperCSX ]
     prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+    idDBLP:=Variable [ Name=$idDBLP ]
+    tokensUnrankedDBLP:=Variable [ Name=$tokensUnrankedDBLP ]
+    lenDBLP:=Variable [ Name=$lenDBLP ]
+    tokensDBLP:=Variable [ Name=$tokensDBLP ]
+    idCSX:=Variable [ Name=$idCSX ]
+    tokensUnrankedCSX:=Variable [ Name=$tokensUnrankedCSX ]
+    lenCSX:=Variable [ Name=$lenCSX ]
+    tokensCSX:=Variable [ Name=$tokensCSX ]
+    sim:=Variable [ Name=$sim ]
   )
 
 Orderby
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5.3/dblp-csx-2_5.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5.3/dblp-csx-2_5.3.ast
index ec2346b..e4318eb 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5.3/dblp-csx-2_5.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5.3/dblp-csx-2_5.3.ast
@@ -17,22 +17,7 @@
     LiteralExpr [STRING] [sim]
     :
     IndexAccessor [
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [sim]
-        Variable [ Name=$lenDBLP ]
-        Variable [ Name=$tokensUnrankedDBLP ]
-        Variable [ Name=$tokensDBLP ]
-        Variable [ Name=$idCSX ]
-        Variable [ Name=$idDBLP ]
-        Variable [ Name=$prefixTokenCSX ]
-        Variable [ Name=#5 ]
-        Variable [ Name=$tokensUnrankedCSX ]
-        Variable [ Name=$prefixTokenDBLP ]
-        Variable [ Name=$lenCSX ]
-        Variable [ Name=$tokensCSX ]
-        Variable [ Name=$paperDBLP ]
-        Variable [ Name=$paperCSX ]
-      ]
+      Variable [ Name=$sim ]
       Index:       LiteralExpr [LONG] [0]
     ]
   )
@@ -44,16 +29,14 @@
   AS Variable [ Name=$paperDBLP ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensDBLP]
-      Variable [ Name=$paperDBLP ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
@@ -67,20 +50,14 @@
   AS Variable [ Name=$paperCSX ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensCSX]
-      Variable [ Name=$prefixTokenDBLP ]
-      Variable [ Name=$paperDBLP ]
-      Variable [ Name=$paperCSX ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensCSX]
-          Variable [ Name=$prefixTokenDBLP ]
-          Variable [ Name=$paperDBLP ]
-          Variable [ Name=$paperCSX ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
@@ -143,35 +120,24 @@
           Variable [ Name=$tokenGrouped ]
           :=
           Variable [ Name=$token ]
-          GROUP AS Variable [ Name=#1 ]
+          GROUP AS Variable [ Name=#2 ]
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$lenDBLP ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=#1 ]
-                Variable [ Name=#2 ]
-                Variable [ Name=$idDBLP ]
-                Variable [ Name=$prefixTokenCSX ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokenGrouped ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$paperCSX ]
+              FieldAccessor [
+                Variable [ Name=#4 ]
+                Field=id
               ]
               ]
-              FROM [                Variable [ Name=#1 ]
-                AS Variable [ Name=#2 ]
+              FROM [                Variable [ Name=#2 ]
+                AS Variable [ Name=#4 ]
               ]
             )
           ]
@@ -254,35 +220,20 @@
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$lenDBLP ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokensDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=$idCSX ]
-                Variable [ Name=$idDBLP ]
-                Variable [ Name=#3 ]
-                Variable [ Name=#4 ]
-                Variable [ Name=$prefixTokenCSX ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokensUnrankedCSX ]
-                Variable [ Name=$tokenGrouped ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$lenCSX ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$paperCSX ]
+              FieldAccessor [
+                Variable [ Name=#5 ]
+                Field=id
               ]
               ]
               FROM [                Variable [ Name=#3 ]
-                AS Variable [ Name=#4 ]
+                AS Variable [ Name=#5 ]
               ]
             )
           ]
@@ -337,12 +288,24 @@
   Variable [ Name=$idCSX ]
   :=
   Variable [ Name=$idCSX ]
-  GROUP AS Variable [ Name=#5 ]
+  Variable [ Name=$sim ]
+  :=
+  Variable [ Name=$sim ]
+  GROUP AS Variable [ Name=#1 ]
   (
     paperDBLP:=Variable [ Name=$paperDBLP ]
     prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
     paperCSX:=Variable [ Name=$paperCSX ]
     prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+    idDBLP:=Variable [ Name=$idDBLP ]
+    tokensUnrankedDBLP:=Variable [ Name=$tokensUnrankedDBLP ]
+    lenDBLP:=Variable [ Name=$lenDBLP ]
+    tokensDBLP:=Variable [ Name=$tokensDBLP ]
+    idCSX:=Variable [ Name=$idCSX ]
+    tokensUnrankedCSX:=Variable [ Name=$tokensUnrankedCSX ]
+    lenCSX:=Variable [ Name=$lenCSX ]
+    tokensCSX:=Variable [ Name=$tokensCSX ]
+    sim:=Variable [ Name=$sim ]
   )
 
 Orderby
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5/dblp-csx-2_5.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5/dblp-csx-2_5.3.ast
index 79cfac1..0509a90 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5/dblp-csx-2_5.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-2_5/dblp-csx-2_5.3.ast
@@ -29,16 +29,14 @@
   AS Variable [ Name=$paperDBLP ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensDBLP]
-      Variable [ Name=$paperDBLP ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
@@ -52,20 +50,14 @@
   AS Variable [ Name=$paperCSX ]
 ,
   FunctionCall fuzzyjoin.subset-collection@3[
-    FunctionCall asterix.resolve@-1[
+    FunctionCall asterix.dataset@1[
       LiteralExpr [STRING] [tokensCSX]
-      Variable [ Name=$prefixTokenDBLP ]
-      Variable [ Name=$paperDBLP ]
-      Variable [ Name=$paperCSX ]
     ]
     LiteralExpr [LONG] [0]
     FunctionCall fuzzyjoin.prefix-len-jaccard@2[
       FunctionCall fuzzyjoin.len@1[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensCSX]
-          Variable [ Name=$prefixTokenDBLP ]
-          Variable [ Name=$paperDBLP ]
-          Variable [ Name=$paperCSX ]
         ]
       ]
       LiteralExpr [FLOAT] [0.5]
@@ -128,35 +120,24 @@
           Variable [ Name=$tokenGroupped ]
           :=
           Variable [ Name=$token ]
-          GROUP AS Variable [ Name=#1 ]
+          GROUP AS Variable [ Name=#2 ]
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$lenDBLP ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=#1 ]
-                Variable [ Name=#2 ]
-                Variable [ Name=$idDBLP ]
-                Variable [ Name=$prefixTokenCSX ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokenGroupped ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$paperCSX ]
+              FieldAccessor [
+                Variable [ Name=#4 ]
+                Field=id
               ]
               ]
-              FROM [                Variable [ Name=#1 ]
-                AS Variable [ Name=#2 ]
+              FROM [                Variable [ Name=#2 ]
+                AS Variable [ Name=#4 ]
               ]
             )
           ]
@@ -239,35 +220,20 @@
           (
             paper:=Variable [ Name=$paper ]
             token:=Variable [ Name=$token ]
+            id:=Variable [ Name=$id ]
           )
 
         Orderby
           FunctionCall asterix.sql-count@1[
             (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [id]
-                Variable [ Name=$lenDBLP ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$paper ]
-                Variable [ Name=$tokensDBLP ]
-                Variable [ Name=$tokenUnranked ]
-                Variable [ Name=$idCSX ]
-                Variable [ Name=$idDBLP ]
-                Variable [ Name=#3 ]
-                Variable [ Name=#4 ]
-                Variable [ Name=$prefixTokenCSX ]
-                Variable [ Name=$token ]
-                Variable [ Name=$tokensUnrankedCSX ]
-                Variable [ Name=$tokenGroupped ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$lenCSX ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$paperCSX ]
+              FieldAccessor [
+                Variable [ Name=#5 ]
+                Field=id
               ]
               ]
               FROM [                Variable [ Name=#3 ]
-                AS Variable [ Name=#4 ]
+                AS Variable [ Name=#5 ]
               ]
             )
           ]
@@ -325,12 +291,21 @@
   Variable [ Name=$sim ]
   :=
   Variable [ Name=$sim ]
-  GROUP AS Variable [ Name=#5 ]
+  GROUP AS Variable [ Name=#1 ]
   (
     paperDBLP:=Variable [ Name=$paperDBLP ]
     prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
     paperCSX:=Variable [ Name=$paperCSX ]
     prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+    idDBLP:=Variable [ Name=$idDBLP ]
+    tokensUnrankedDBLP:=Variable [ Name=$tokensUnrankedDBLP ]
+    lenDBLP:=Variable [ Name=$lenDBLP ]
+    tokensDBLP:=Variable [ Name=$tokensDBLP ]
+    idCSX:=Variable [ Name=$idCSX ]
+    tokensUnrankedCSX:=Variable [ Name=$tokensUnrankedCSX ]
+    lenCSX:=Variable [ Name=$lenCSX ]
+    tokensCSX:=Variable [ Name=$tokensCSX ]
+    sim:=Variable [ Name=$sim ]
   )
 
 Orderby
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_1/dblp-csx-3_1.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_1/dblp-csx-3_1.3.ast
index 26e2200..21fb6cb 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_1/dblp-csx-3_1.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_1/dblp-csx-3_1.3.ast
@@ -52,16 +52,14 @@
       AS Variable [ Name=$paperDBLP ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
           FunctionCall fuzzyjoin.len@1[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensDBLP]
-              Variable [ Name=$paperDBLP ]
             ]
           ]
           LiteralExpr [FLOAT] [0.5]
@@ -75,20 +73,14 @@
       AS Variable [ Name=$paperCSX ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensCSX]
-          Variable [ Name=$prefixTokenDBLP ]
-          Variable [ Name=$paperDBLP ]
-          Variable [ Name=$paperCSX ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
           FunctionCall fuzzyjoin.len@1[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensCSX]
-              Variable [ Name=$prefixTokenDBLP ]
-              Variable [ Name=$paperDBLP ]
-              Variable [ Name=$paperCSX ]
             ]
           ]
           LiteralExpr [FLOAT] [0.5]
@@ -131,7 +123,7 @@
               Variable [ Name=$tokenGroupped ]
               :=
               Variable [ Name=$token ]
-              GROUP AS Variable [ Name=#1 ]
+              GROUP AS Variable [ Name=#2 ]
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
@@ -142,12 +134,12 @@
                 (
                   SELECT ELEMENT [
                   FieldAccessor [
-                    Variable [ Name=#2 ]
+                    Variable [ Name=#4 ]
                     Field=paper
                   ]
                   ]
-                  FROM [                    Variable [ Name=#1 ]
-                    AS Variable [ Name=#2 ]
+                  FROM [                    Variable [ Name=#2 ]
+                    AS Variable [ Name=#4 ]
                   ]
                 )
               ]
@@ -217,12 +209,12 @@
                 (
                   SELECT ELEMENT [
                   FieldAccessor [
-                    Variable [ Name=#4 ]
+                    Variable [ Name=#5 ]
                     Field=paper
                   ]
                   ]
                   FROM [                    Variable [ Name=#3 ]
-                    AS Variable [ Name=#4 ]
+                    AS Variable [ Name=#5 ]
                   ]
                 )
               ]
@@ -300,12 +292,15 @@
       Variable [ Name=$sim ]
       :=
       Variable [ Name=$sim ]
-      GROUP AS Variable [ Name=#5 ]
+      GROUP AS Variable [ Name=#1 ]
       (
         paperDBLP:=Variable [ Name=$paperDBLP ]
         prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
         paperCSX:=Variable [ Name=$paperCSX ]
         prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+        tokensDBLP:=Variable [ Name=$tokensDBLP ]
+        tokensCSX:=Variable [ Name=$tokensCSX ]
+        sim:=Variable [ Name=$sim ]
       )
 
   )
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_2/dblp-csx-3_2.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_2/dblp-csx-3_2.3.ast
index b1c130b..7d5acad 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_2/dblp-csx-3_2.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_2/dblp-csx-3_2.3.ast
@@ -52,16 +52,14 @@
       AS Variable [ Name=$paperDBLP ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
           FunctionCall fuzzyjoin.len@1[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensDBLP]
-              Variable [ Name=$paperDBLP ]
             ]
           ]
           LiteralExpr [FLOAT] [0.5]
@@ -75,20 +73,14 @@
       AS Variable [ Name=$paperCSX ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensCSX]
-          Variable [ Name=$prefixTokenDBLP ]
-          Variable [ Name=$paperDBLP ]
-          Variable [ Name=$paperCSX ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
           FunctionCall fuzzyjoin.len@1[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensCSX]
-              Variable [ Name=$prefixTokenDBLP ]
-              Variable [ Name=$paperDBLP ]
-              Variable [ Name=$paperCSX ]
             ]
           ]
           LiteralExpr [FLOAT] [0.5]
@@ -137,32 +129,24 @@
               Variable [ Name=$tokenGroupped ]
               :=
               Variable [ Name=$token ]
-              GROUP AS Variable [ Name=#1 ]
+              GROUP AS Variable [ Name=#2 ]
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
+                id:=Variable [ Name=$id ]
               )
 
             Orderby
               FunctionCall asterix.sql-count@1[
                 (
                   SELECT ELEMENT [
-                  FunctionCall asterix.resolve@-1[
-                    LiteralExpr [STRING] [id]
-                    Variable [ Name=$prefixTokenCSX ]
-                    Variable [ Name=$token ]
-                    Variable [ Name=$paper ]
-                    Variable [ Name=$tokenGroupped ]
-                    Variable [ Name=$prefixTokenDBLP ]
-                    Variable [ Name=$paperDBLP ]
-                    Variable [ Name=$tokenUnranked ]
-                    Variable [ Name=$paperCSX ]
-                    Variable [ Name=#1 ]
-                    Variable [ Name=#2 ]
+                  FieldAccessor [
+                    Variable [ Name=#4 ]
+                    Field=id
                   ]
                   ]
-                  FROM [                    Variable [ Name=#1 ]
-                    AS Variable [ Name=#2 ]
+                  FROM [                    Variable [ Name=#2 ]
+                    AS Variable [ Name=#4 ]
                   ]
                 )
               ]
@@ -231,29 +215,20 @@
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
+                id:=Variable [ Name=$id ]
               )
 
             Orderby
               FunctionCall asterix.sql-count@1[
                 (
                   SELECT ELEMENT [
-                  FunctionCall asterix.resolve@-1[
-                    LiteralExpr [STRING] [id]
-                    Variable [ Name=#4 ]
-                    Variable [ Name=$prefixTokenCSX ]
-                    Variable [ Name=$token ]
-                    Variable [ Name=$paper ]
-                    Variable [ Name=$tokenGroupped ]
-                    Variable [ Name=$prefixTokenDBLP ]
-                    Variable [ Name=$tokensDBLP ]
-                    Variable [ Name=$paperDBLP ]
-                    Variable [ Name=$tokenUnranked ]
-                    Variable [ Name=$paperCSX ]
-                    Variable [ Name=#3 ]
+                  FieldAccessor [
+                    Variable [ Name=#5 ]
+                    Field=id
                   ]
                   ]
                   FROM [                    Variable [ Name=#3 ]
-                    AS Variable [ Name=#4 ]
+                    AS Variable [ Name=#5 ]
                   ]
                 )
               ]
@@ -331,12 +306,15 @@
       Variable [ Name=$sim ]
       :=
       Variable [ Name=$sim ]
-      GROUP AS Variable [ Name=#5 ]
+      GROUP AS Variable [ Name=#1 ]
       (
         paperDBLP:=Variable [ Name=$paperDBLP ]
         prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
         paperCSX:=Variable [ Name=$paperCSX ]
         prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+        tokensDBLP:=Variable [ Name=$tokensDBLP ]
+        tokensCSX:=Variable [ Name=$tokensCSX ]
+        sim:=Variable [ Name=$sim ]
       )
 
   )
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_3/dblp-csx-3_3.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_3/dblp-csx-3_3.3.ast
index c17294b..8dffafe 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_3/dblp-csx-3_3.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_3/dblp-csx-3_3.3.ast
@@ -52,16 +52,14 @@
       AS Variable [ Name=$paperDBLP ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
           FunctionCall fuzzyjoin.len@1[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensDBLP]
-              Variable [ Name=$paperDBLP ]
             ]
           ]
           LiteralExpr [FLOAT] [0.5]
@@ -75,20 +73,14 @@
       AS Variable [ Name=$paperCSX ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensCSX]
-          Variable [ Name=$prefixTokenDBLP ]
-          Variable [ Name=$paperDBLP ]
-          Variable [ Name=$paperCSX ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
           FunctionCall fuzzyjoin.len@1[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensCSX]
-              Variable [ Name=$prefixTokenDBLP ]
-              Variable [ Name=$paperDBLP ]
-              Variable [ Name=$paperCSX ]
             ]
           ]
           LiteralExpr [FLOAT] [0.5]
@@ -143,33 +135,24 @@
               Variable [ Name=$tokenGroupped ]
               :=
               Variable [ Name=$token ]
-              GROUP AS Variable [ Name=#1 ]
+              GROUP AS Variable [ Name=#2 ]
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
+                id:=Variable [ Name=$id ]
               )
 
             Orderby
               FunctionCall asterix.sql-count@1[
                 (
                   SELECT ELEMENT [
-                  FunctionCall asterix.resolve@-1[
-                    LiteralExpr [STRING] [id]
-                    Variable [ Name=$prefixTokenCSX ]
-                    Variable [ Name=$token ]
-                    Variable [ Name=$paper ]
-                    Variable [ Name=$tokenGroupped ]
-                    Variable [ Name=$prefixTokenDBLP ]
-                    Variable [ Name=$paperDBLP ]
-                    Variable [ Name=$tokenUnranked ]
-                    Variable [ Name=$paperCSX ]
-                    Variable [ Name=#1 ]
-                    Variable [ Name=#2 ]
-                    Variable [ Name=$idDBLP ]
+                  FieldAccessor [
+                    Variable [ Name=#4 ]
+                    Field=id
                   ]
                   ]
-                  FROM [                    Variable [ Name=#1 ]
-                    AS Variable [ Name=#2 ]
+                  FROM [                    Variable [ Name=#2 ]
+                    AS Variable [ Name=#4 ]
                   ]
                 )
               ]
@@ -244,31 +227,20 @@
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
+                id:=Variable [ Name=$id ]
               )
 
             Orderby
               FunctionCall asterix.sql-count@1[
                 (
                   SELECT ELEMENT [
-                  FunctionCall asterix.resolve@-1[
-                    LiteralExpr [STRING] [id]
-                    Variable [ Name=$paper ]
-                    Variable [ Name=$tokensDBLP ]
-                    Variable [ Name=$tokenUnranked ]
-                    Variable [ Name=$idCSX ]
-                    Variable [ Name=$idDBLP ]
-                    Variable [ Name=#3 ]
-                    Variable [ Name=#4 ]
-                    Variable [ Name=$prefixTokenCSX ]
-                    Variable [ Name=$token ]
-                    Variable [ Name=$tokenGroupped ]
-                    Variable [ Name=$prefixTokenDBLP ]
-                    Variable [ Name=$paperDBLP ]
-                    Variable [ Name=$paperCSX ]
+                  FieldAccessor [
+                    Variable [ Name=#5 ]
+                    Field=id
                   ]
                   ]
                   FROM [                    Variable [ Name=#3 ]
-                    AS Variable [ Name=#4 ]
+                    AS Variable [ Name=#5 ]
                   ]
                 )
               ]
@@ -340,12 +312,17 @@
       Variable [ Name=$sim ]
       :=
       Variable [ Name=$sim ]
-      GROUP AS Variable [ Name=#5 ]
+      GROUP AS Variable [ Name=#1 ]
       (
         paperDBLP:=Variable [ Name=$paperDBLP ]
         prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
         paperCSX:=Variable [ Name=$paperCSX ]
         prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+        idDBLP:=Variable [ Name=$idDBLP ]
+        tokensDBLP:=Variable [ Name=$tokensDBLP ]
+        idCSX:=Variable [ Name=$idCSX ]
+        tokensCSX:=Variable [ Name=$tokensCSX ]
+        sim:=Variable [ Name=$sim ]
       )
 
   )
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_4/dblp-csx-3_4.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_4/dblp-csx-3_4.3.ast
index 9403a30..f25d0b8 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_4/dblp-csx-3_4.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_4/dblp-csx-3_4.3.ast
@@ -52,16 +52,14 @@
       AS Variable [ Name=$paperDBLP ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
           FunctionCall fuzzyjoin.len@1[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensDBLP]
-              Variable [ Name=$paperDBLP ]
             ]
           ]
           LiteralExpr [FLOAT] [0.5]
@@ -75,20 +73,14 @@
       AS Variable [ Name=$paperCSX ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensCSX]
-          Variable [ Name=$prefixTokenDBLP ]
-          Variable [ Name=$paperDBLP ]
-          Variable [ Name=$paperCSX ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
           FunctionCall fuzzyjoin.len@1[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensCSX]
-              Variable [ Name=$prefixTokenDBLP ]
-              Variable [ Name=$paperDBLP ]
-              Variable [ Name=$paperCSX ]
             ]
           ]
           LiteralExpr [FLOAT] [0.5]
@@ -146,34 +138,24 @@
               Variable [ Name=$tokenGroupped ]
               :=
               Variable [ Name=$token ]
-              GROUP AS Variable [ Name=#1 ]
+              GROUP AS Variable [ Name=#2 ]
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
+                id:=Variable [ Name=$id ]
               )
 
             Orderby
               FunctionCall asterix.sql-count@1[
                 (
                   SELECT ELEMENT [
-                  FunctionCall asterix.resolve@-1[
-                    LiteralExpr [STRING] [id]
-                    Variable [ Name=$prefixTokenCSX ]
-                    Variable [ Name=$token ]
-                    Variable [ Name=$tokensUnrankedDBLP ]
-                    Variable [ Name=$paper ]
-                    Variable [ Name=$tokenGroupped ]
-                    Variable [ Name=$prefixTokenDBLP ]
-                    Variable [ Name=$paperDBLP ]
-                    Variable [ Name=$tokenUnranked ]
-                    Variable [ Name=$paperCSX ]
-                    Variable [ Name=#1 ]
-                    Variable [ Name=#2 ]
-                    Variable [ Name=$idDBLP ]
+                  FieldAccessor [
+                    Variable [ Name=#4 ]
+                    Field=id
                   ]
                   ]
-                  FROM [                    Variable [ Name=#1 ]
-                    AS Variable [ Name=#2 ]
+                  FROM [                    Variable [ Name=#2 ]
+                    AS Variable [ Name=#4 ]
                   ]
                 )
               ]
@@ -251,33 +233,20 @@
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
+                id:=Variable [ Name=$id ]
               )
 
             Orderby
               FunctionCall asterix.sql-count@1[
                 (
                   SELECT ELEMENT [
-                  FunctionCall asterix.resolve@-1[
-                    LiteralExpr [STRING] [id]
-                    Variable [ Name=$tokensUnrankedDBLP ]
-                    Variable [ Name=$paper ]
-                    Variable [ Name=$tokensDBLP ]
-                    Variable [ Name=$tokenUnranked ]
-                    Variable [ Name=$idCSX ]
-                    Variable [ Name=$idDBLP ]
-                    Variable [ Name=#3 ]
-                    Variable [ Name=#4 ]
-                    Variable [ Name=$prefixTokenCSX ]
-                    Variable [ Name=$token ]
-                    Variable [ Name=$tokensUnrankedCSX ]
-                    Variable [ Name=$tokenGroupped ]
-                    Variable [ Name=$prefixTokenDBLP ]
-                    Variable [ Name=$paperDBLP ]
-                    Variable [ Name=$paperCSX ]
+                  FieldAccessor [
+                    Variable [ Name=#5 ]
+                    Field=id
                   ]
                   ]
                   FROM [                    Variable [ Name=#3 ]
-                    AS Variable [ Name=#4 ]
+                    AS Variable [ Name=#5 ]
                   ]
                 )
               ]
@@ -339,12 +308,19 @@
       Variable [ Name=$sim ]
       :=
       Variable [ Name=$sim ]
-      GROUP AS Variable [ Name=#5 ]
+      GROUP AS Variable [ Name=#1 ]
       (
         paperDBLP:=Variable [ Name=$paperDBLP ]
         prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
         paperCSX:=Variable [ Name=$paperCSX ]
         prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+        idDBLP:=Variable [ Name=$idDBLP ]
+        tokensUnrankedDBLP:=Variable [ Name=$tokensUnrankedDBLP ]
+        tokensDBLP:=Variable [ Name=$tokensDBLP ]
+        idCSX:=Variable [ Name=$idCSX ]
+        tokensUnrankedCSX:=Variable [ Name=$tokensUnrankedCSX ]
+        tokensCSX:=Variable [ Name=$tokensCSX ]
+        sim:=Variable [ Name=$sim ]
       )
 
   )
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.1/dblp-csx-3_5.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.1/dblp-csx-3_5.3.ast
index 74a82c9..5794d99 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.1/dblp-csx-3_5.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.1/dblp-csx-3_5.3.ast
@@ -40,22 +40,7 @@
         LiteralExpr [STRING] [sim]
         :
         IndexAccessor [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [sim]
-            Variable [ Name=$lenDBLP ]
-            Variable [ Name=$tokensUnrankedDBLP ]
-            Variable [ Name=$tokensDBLP ]
-            Variable [ Name=$idCSX ]
-            Variable [ Name=$idDBLP ]
-            Variable [ Name=$prefixTokenCSX ]
-            Variable [ Name=#5 ]
-            Variable [ Name=$tokensUnrankedCSX ]
-            Variable [ Name=$prefixTokenDBLP ]
-            Variable [ Name=$lenCSX ]
-            Variable [ Name=$tokensCSX ]
-            Variable [ Name=$paperDBLP ]
-            Variable [ Name=$paperCSX ]
-          ]
+          Variable [ Name=$sim ]
           Index:           LiteralExpr [LONG] [0]
         ]
       )
@@ -67,16 +52,14 @@
       AS Variable [ Name=$paperDBLP ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
           FunctionCall fuzzyjoin.len@1[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensDBLP]
-              Variable [ Name=$paperDBLP ]
             ]
           ]
           LiteralExpr [FLOAT] [0.5]
@@ -90,20 +73,14 @@
       AS Variable [ Name=$paperCSX ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensCSX]
-          Variable [ Name=$prefixTokenDBLP ]
-          Variable [ Name=$paperDBLP ]
-          Variable [ Name=$paperCSX ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
           FunctionCall fuzzyjoin.len@1[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensCSX]
-              Variable [ Name=$prefixTokenDBLP ]
-              Variable [ Name=$paperDBLP ]
-              Variable [ Name=$paperCSX ]
             ]
           ]
           LiteralExpr [FLOAT] [0.5]
@@ -166,35 +143,24 @@
               Variable [ Name=$tokenGrouped ]
               :=
               Variable [ Name=$token ]
-              GROUP AS Variable [ Name=#1 ]
+              GROUP AS Variable [ Name=#2 ]
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
+                id:=Variable [ Name=$id ]
               )
 
             Orderby
               FunctionCall asterix.sql-count@1[
                 (
                   SELECT ELEMENT [
-                  FunctionCall asterix.resolve@-1[
-                    LiteralExpr [STRING] [id]
-                    Variable [ Name=$lenDBLP ]
-                    Variable [ Name=$tokensUnrankedDBLP ]
-                    Variable [ Name=$paper ]
-                    Variable [ Name=$tokenUnranked ]
-                    Variable [ Name=#1 ]
-                    Variable [ Name=#2 ]
-                    Variable [ Name=$idDBLP ]
-                    Variable [ Name=$prefixTokenCSX ]
-                    Variable [ Name=$token ]
-                    Variable [ Name=$tokenGrouped ]
-                    Variable [ Name=$prefixTokenDBLP ]
-                    Variable [ Name=$paperDBLP ]
-                    Variable [ Name=$paperCSX ]
+                  FieldAccessor [
+                    Variable [ Name=#4 ]
+                    Field=id
                   ]
                   ]
-                  FROM [                    Variable [ Name=#1 ]
-                    AS Variable [ Name=#2 ]
+                  FROM [                    Variable [ Name=#2 ]
+                    AS Variable [ Name=#4 ]
                   ]
                 )
               ]
@@ -277,35 +243,20 @@
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
+                id:=Variable [ Name=$id ]
               )
 
             Orderby
               FunctionCall asterix.sql-count@1[
                 (
                   SELECT ELEMENT [
-                  FunctionCall asterix.resolve@-1[
-                    LiteralExpr [STRING] [id]
-                    Variable [ Name=$lenDBLP ]
-                    Variable [ Name=$tokensUnrankedDBLP ]
-                    Variable [ Name=$paper ]
-                    Variable [ Name=$tokensDBLP ]
-                    Variable [ Name=$tokenUnranked ]
-                    Variable [ Name=$idCSX ]
-                    Variable [ Name=$idDBLP ]
-                    Variable [ Name=#3 ]
-                    Variable [ Name=#4 ]
-                    Variable [ Name=$prefixTokenCSX ]
-                    Variable [ Name=$token ]
-                    Variable [ Name=$tokensUnrankedCSX ]
-                    Variable [ Name=$tokenGrouped ]
-                    Variable [ Name=$prefixTokenDBLP ]
-                    Variable [ Name=$lenCSX ]
-                    Variable [ Name=$paperDBLP ]
-                    Variable [ Name=$paperCSX ]
+                  FieldAccessor [
+                    Variable [ Name=#5 ]
+                    Field=id
                   ]
                   ]
                   FROM [                    Variable [ Name=#3 ]
-                    AS Variable [ Name=#4 ]
+                    AS Variable [ Name=#5 ]
                   ]
                 )
               ]
@@ -360,12 +311,24 @@
       Variable [ Name=$idCSX ]
       :=
       Variable [ Name=$idCSX ]
-      GROUP AS Variable [ Name=#5 ]
+      Variable [ Name=$sim ]
+      :=
+      Variable [ Name=$sim ]
+      GROUP AS Variable [ Name=#1 ]
       (
         paperDBLP:=Variable [ Name=$paperDBLP ]
         prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
         paperCSX:=Variable [ Name=$paperCSX ]
         prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+        idDBLP:=Variable [ Name=$idDBLP ]
+        tokensUnrankedDBLP:=Variable [ Name=$tokensUnrankedDBLP ]
+        lenDBLP:=Variable [ Name=$lenDBLP ]
+        tokensDBLP:=Variable [ Name=$tokensDBLP ]
+        idCSX:=Variable [ Name=$idCSX ]
+        tokensUnrankedCSX:=Variable [ Name=$tokensUnrankedCSX ]
+        lenCSX:=Variable [ Name=$lenCSX ]
+        tokensCSX:=Variable [ Name=$tokensCSX ]
+        sim:=Variable [ Name=$sim ]
       )
 
   )
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.2/dblp-csx-3_5.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.2/dblp-csx-3_5.3.ast
index 74a82c9..5794d99 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.2/dblp-csx-3_5.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.2/dblp-csx-3_5.3.ast
@@ -40,22 +40,7 @@
         LiteralExpr [STRING] [sim]
         :
         IndexAccessor [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [sim]
-            Variable [ Name=$lenDBLP ]
-            Variable [ Name=$tokensUnrankedDBLP ]
-            Variable [ Name=$tokensDBLP ]
-            Variable [ Name=$idCSX ]
-            Variable [ Name=$idDBLP ]
-            Variable [ Name=$prefixTokenCSX ]
-            Variable [ Name=#5 ]
-            Variable [ Name=$tokensUnrankedCSX ]
-            Variable [ Name=$prefixTokenDBLP ]
-            Variable [ Name=$lenCSX ]
-            Variable [ Name=$tokensCSX ]
-            Variable [ Name=$paperDBLP ]
-            Variable [ Name=$paperCSX ]
-          ]
+          Variable [ Name=$sim ]
           Index:           LiteralExpr [LONG] [0]
         ]
       )
@@ -67,16 +52,14 @@
       AS Variable [ Name=$paperDBLP ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
           FunctionCall fuzzyjoin.len@1[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensDBLP]
-              Variable [ Name=$paperDBLP ]
             ]
           ]
           LiteralExpr [FLOAT] [0.5]
@@ -90,20 +73,14 @@
       AS Variable [ Name=$paperCSX ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensCSX]
-          Variable [ Name=$prefixTokenDBLP ]
-          Variable [ Name=$paperDBLP ]
-          Variable [ Name=$paperCSX ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
           FunctionCall fuzzyjoin.len@1[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensCSX]
-              Variable [ Name=$prefixTokenDBLP ]
-              Variable [ Name=$paperDBLP ]
-              Variable [ Name=$paperCSX ]
             ]
           ]
           LiteralExpr [FLOAT] [0.5]
@@ -166,35 +143,24 @@
               Variable [ Name=$tokenGrouped ]
               :=
               Variable [ Name=$token ]
-              GROUP AS Variable [ Name=#1 ]
+              GROUP AS Variable [ Name=#2 ]
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
+                id:=Variable [ Name=$id ]
               )
 
             Orderby
               FunctionCall asterix.sql-count@1[
                 (
                   SELECT ELEMENT [
-                  FunctionCall asterix.resolve@-1[
-                    LiteralExpr [STRING] [id]
-                    Variable [ Name=$lenDBLP ]
-                    Variable [ Name=$tokensUnrankedDBLP ]
-                    Variable [ Name=$paper ]
-                    Variable [ Name=$tokenUnranked ]
-                    Variable [ Name=#1 ]
-                    Variable [ Name=#2 ]
-                    Variable [ Name=$idDBLP ]
-                    Variable [ Name=$prefixTokenCSX ]
-                    Variable [ Name=$token ]
-                    Variable [ Name=$tokenGrouped ]
-                    Variable [ Name=$prefixTokenDBLP ]
-                    Variable [ Name=$paperDBLP ]
-                    Variable [ Name=$paperCSX ]
+                  FieldAccessor [
+                    Variable [ Name=#4 ]
+                    Field=id
                   ]
                   ]
-                  FROM [                    Variable [ Name=#1 ]
-                    AS Variable [ Name=#2 ]
+                  FROM [                    Variable [ Name=#2 ]
+                    AS Variable [ Name=#4 ]
                   ]
                 )
               ]
@@ -277,35 +243,20 @@
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
+                id:=Variable [ Name=$id ]
               )
 
             Orderby
               FunctionCall asterix.sql-count@1[
                 (
                   SELECT ELEMENT [
-                  FunctionCall asterix.resolve@-1[
-                    LiteralExpr [STRING] [id]
-                    Variable [ Name=$lenDBLP ]
-                    Variable [ Name=$tokensUnrankedDBLP ]
-                    Variable [ Name=$paper ]
-                    Variable [ Name=$tokensDBLP ]
-                    Variable [ Name=$tokenUnranked ]
-                    Variable [ Name=$idCSX ]
-                    Variable [ Name=$idDBLP ]
-                    Variable [ Name=#3 ]
-                    Variable [ Name=#4 ]
-                    Variable [ Name=$prefixTokenCSX ]
-                    Variable [ Name=$token ]
-                    Variable [ Name=$tokensUnrankedCSX ]
-                    Variable [ Name=$tokenGrouped ]
-                    Variable [ Name=$prefixTokenDBLP ]
-                    Variable [ Name=$lenCSX ]
-                    Variable [ Name=$paperDBLP ]
-                    Variable [ Name=$paperCSX ]
+                  FieldAccessor [
+                    Variable [ Name=#5 ]
+                    Field=id
                   ]
                   ]
                   FROM [                    Variable [ Name=#3 ]
-                    AS Variable [ Name=#4 ]
+                    AS Variable [ Name=#5 ]
                   ]
                 )
               ]
@@ -360,12 +311,24 @@
       Variable [ Name=$idCSX ]
       :=
       Variable [ Name=$idCSX ]
-      GROUP AS Variable [ Name=#5 ]
+      Variable [ Name=$sim ]
+      :=
+      Variable [ Name=$sim ]
+      GROUP AS Variable [ Name=#1 ]
       (
         paperDBLP:=Variable [ Name=$paperDBLP ]
         prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
         paperCSX:=Variable [ Name=$paperCSX ]
         prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+        idDBLP:=Variable [ Name=$idDBLP ]
+        tokensUnrankedDBLP:=Variable [ Name=$tokensUnrankedDBLP ]
+        lenDBLP:=Variable [ Name=$lenDBLP ]
+        tokensDBLP:=Variable [ Name=$tokensDBLP ]
+        idCSX:=Variable [ Name=$idCSX ]
+        tokensUnrankedCSX:=Variable [ Name=$tokensUnrankedCSX ]
+        lenCSX:=Variable [ Name=$lenCSX ]
+        tokensCSX:=Variable [ Name=$tokensCSX ]
+        sim:=Variable [ Name=$sim ]
       )
 
   )
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.3.1/dblp-csx-3_5.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.3.1/dblp-csx-3_5.3.ast
index 74a82c9..5794d99 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.3.1/dblp-csx-3_5.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.3.1/dblp-csx-3_5.3.ast
@@ -40,22 +40,7 @@
         LiteralExpr [STRING] [sim]
         :
         IndexAccessor [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [sim]
-            Variable [ Name=$lenDBLP ]
-            Variable [ Name=$tokensUnrankedDBLP ]
-            Variable [ Name=$tokensDBLP ]
-            Variable [ Name=$idCSX ]
-            Variable [ Name=$idDBLP ]
-            Variable [ Name=$prefixTokenCSX ]
-            Variable [ Name=#5 ]
-            Variable [ Name=$tokensUnrankedCSX ]
-            Variable [ Name=$prefixTokenDBLP ]
-            Variable [ Name=$lenCSX ]
-            Variable [ Name=$tokensCSX ]
-            Variable [ Name=$paperDBLP ]
-            Variable [ Name=$paperCSX ]
-          ]
+          Variable [ Name=$sim ]
           Index:           LiteralExpr [LONG] [0]
         ]
       )
@@ -67,16 +52,14 @@
       AS Variable [ Name=$paperDBLP ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
           FunctionCall fuzzyjoin.len@1[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensDBLP]
-              Variable [ Name=$paperDBLP ]
             ]
           ]
           LiteralExpr [FLOAT] [0.5]
@@ -90,20 +73,14 @@
       AS Variable [ Name=$paperCSX ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensCSX]
-          Variable [ Name=$prefixTokenDBLP ]
-          Variable [ Name=$paperDBLP ]
-          Variable [ Name=$paperCSX ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
           FunctionCall fuzzyjoin.len@1[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensCSX]
-              Variable [ Name=$prefixTokenDBLP ]
-              Variable [ Name=$paperDBLP ]
-              Variable [ Name=$paperCSX ]
             ]
           ]
           LiteralExpr [FLOAT] [0.5]
@@ -166,35 +143,24 @@
               Variable [ Name=$tokenGrouped ]
               :=
               Variable [ Name=$token ]
-              GROUP AS Variable [ Name=#1 ]
+              GROUP AS Variable [ Name=#2 ]
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
+                id:=Variable [ Name=$id ]
               )
 
             Orderby
               FunctionCall asterix.sql-count@1[
                 (
                   SELECT ELEMENT [
-                  FunctionCall asterix.resolve@-1[
-                    LiteralExpr [STRING] [id]
-                    Variable [ Name=$lenDBLP ]
-                    Variable [ Name=$tokensUnrankedDBLP ]
-                    Variable [ Name=$paper ]
-                    Variable [ Name=$tokenUnranked ]
-                    Variable [ Name=#1 ]
-                    Variable [ Name=#2 ]
-                    Variable [ Name=$idDBLP ]
-                    Variable [ Name=$prefixTokenCSX ]
-                    Variable [ Name=$token ]
-                    Variable [ Name=$tokenGrouped ]
-                    Variable [ Name=$prefixTokenDBLP ]
-                    Variable [ Name=$paperDBLP ]
-                    Variable [ Name=$paperCSX ]
+                  FieldAccessor [
+                    Variable [ Name=#4 ]
+                    Field=id
                   ]
                   ]
-                  FROM [                    Variable [ Name=#1 ]
-                    AS Variable [ Name=#2 ]
+                  FROM [                    Variable [ Name=#2 ]
+                    AS Variable [ Name=#4 ]
                   ]
                 )
               ]
@@ -277,35 +243,20 @@
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
+                id:=Variable [ Name=$id ]
               )
 
             Orderby
               FunctionCall asterix.sql-count@1[
                 (
                   SELECT ELEMENT [
-                  FunctionCall asterix.resolve@-1[
-                    LiteralExpr [STRING] [id]
-                    Variable [ Name=$lenDBLP ]
-                    Variable [ Name=$tokensUnrankedDBLP ]
-                    Variable [ Name=$paper ]
-                    Variable [ Name=$tokensDBLP ]
-                    Variable [ Name=$tokenUnranked ]
-                    Variable [ Name=$idCSX ]
-                    Variable [ Name=$idDBLP ]
-                    Variable [ Name=#3 ]
-                    Variable [ Name=#4 ]
-                    Variable [ Name=$prefixTokenCSX ]
-                    Variable [ Name=$token ]
-                    Variable [ Name=$tokensUnrankedCSX ]
-                    Variable [ Name=$tokenGrouped ]
-                    Variable [ Name=$prefixTokenDBLP ]
-                    Variable [ Name=$lenCSX ]
-                    Variable [ Name=$paperDBLP ]
-                    Variable [ Name=$paperCSX ]
+                  FieldAccessor [
+                    Variable [ Name=#5 ]
+                    Field=id
                   ]
                   ]
                   FROM [                    Variable [ Name=#3 ]
-                    AS Variable [ Name=#4 ]
+                    AS Variable [ Name=#5 ]
                   ]
                 )
               ]
@@ -360,12 +311,24 @@
       Variable [ Name=$idCSX ]
       :=
       Variable [ Name=$idCSX ]
-      GROUP AS Variable [ Name=#5 ]
+      Variable [ Name=$sim ]
+      :=
+      Variable [ Name=$sim ]
+      GROUP AS Variable [ Name=#1 ]
       (
         paperDBLP:=Variable [ Name=$paperDBLP ]
         prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
         paperCSX:=Variable [ Name=$paperCSX ]
         prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+        idDBLP:=Variable [ Name=$idDBLP ]
+        tokensUnrankedDBLP:=Variable [ Name=$tokensUnrankedDBLP ]
+        lenDBLP:=Variable [ Name=$lenDBLP ]
+        tokensDBLP:=Variable [ Name=$tokensDBLP ]
+        idCSX:=Variable [ Name=$idCSX ]
+        tokensUnrankedCSX:=Variable [ Name=$tokensUnrankedCSX ]
+        lenCSX:=Variable [ Name=$lenCSX ]
+        tokensCSX:=Variable [ Name=$tokensCSX ]
+        sim:=Variable [ Name=$sim ]
       )
 
   )
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.3/dblp-csx-3_5.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.3/dblp-csx-3_5.3.ast
index 09b0092..04290ce 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.3/dblp-csx-3_5.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.3/dblp-csx-3_5.3.ast
@@ -52,16 +52,14 @@
       AS Variable [ Name=$paperDBLP ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
           FunctionCall fuzzyjoin.len@1[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensDBLP]
-              Variable [ Name=$paperDBLP ]
             ]
           ]
           LiteralExpr [FLOAT] [0.5]
@@ -75,20 +73,14 @@
       AS Variable [ Name=$paperCSX ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensCSX]
-          Variable [ Name=$prefixTokenDBLP ]
-          Variable [ Name=$paperDBLP ]
-          Variable [ Name=$paperCSX ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
           FunctionCall fuzzyjoin.len@1[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensCSX]
-              Variable [ Name=$prefixTokenDBLP ]
-              Variable [ Name=$paperDBLP ]
-              Variable [ Name=$paperCSX ]
             ]
           ]
           LiteralExpr [FLOAT] [0.5]
@@ -151,35 +143,24 @@
               Variable [ Name=$tokenGroupped ]
               :=
               Variable [ Name=$token ]
-              GROUP AS Variable [ Name=#1 ]
+              GROUP AS Variable [ Name=#2 ]
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
+                id:=Variable [ Name=$id ]
               )
 
             Orderby
               FunctionCall asterix.sql-count@1[
                 (
                   SELECT ELEMENT [
-                  FunctionCall asterix.resolve@-1[
-                    LiteralExpr [STRING] [id]
-                    Variable [ Name=$lenDBLP ]
-                    Variable [ Name=$tokensUnrankedDBLP ]
-                    Variable [ Name=$paper ]
-                    Variable [ Name=$tokenUnranked ]
-                    Variable [ Name=#1 ]
-                    Variable [ Name=#2 ]
-                    Variable [ Name=$idDBLP ]
-                    Variable [ Name=$prefixTokenCSX ]
-                    Variable [ Name=$token ]
-                    Variable [ Name=$tokenGroupped ]
-                    Variable [ Name=$prefixTokenDBLP ]
-                    Variable [ Name=$paperDBLP ]
-                    Variable [ Name=$paperCSX ]
+                  FieldAccessor [
+                    Variable [ Name=#4 ]
+                    Field=id
                   ]
                   ]
-                  FROM [                    Variable [ Name=#1 ]
-                    AS Variable [ Name=#2 ]
+                  FROM [                    Variable [ Name=#2 ]
+                    AS Variable [ Name=#4 ]
                   ]
                 )
               ]
@@ -262,35 +243,20 @@
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
+                id:=Variable [ Name=$id ]
               )
 
             Orderby
               FunctionCall asterix.sql-count@1[
                 (
                   SELECT ELEMENT [
-                  FunctionCall asterix.resolve@-1[
-                    LiteralExpr [STRING] [id]
-                    Variable [ Name=$lenDBLP ]
-                    Variable [ Name=$tokensUnrankedDBLP ]
-                    Variable [ Name=$paper ]
-                    Variable [ Name=$tokensDBLP ]
-                    Variable [ Name=$tokenUnranked ]
-                    Variable [ Name=$idCSX ]
-                    Variable [ Name=$idDBLP ]
-                    Variable [ Name=#3 ]
-                    Variable [ Name=#4 ]
-                    Variable [ Name=$prefixTokenCSX ]
-                    Variable [ Name=$token ]
-                    Variable [ Name=$tokensUnrankedCSX ]
-                    Variable [ Name=$tokenGroupped ]
-                    Variable [ Name=$prefixTokenDBLP ]
-                    Variable [ Name=$lenCSX ]
-                    Variable [ Name=$paperDBLP ]
-                    Variable [ Name=$paperCSX ]
+                  FieldAccessor [
+                    Variable [ Name=#5 ]
+                    Field=id
                   ]
                   ]
                   FROM [                    Variable [ Name=#3 ]
-                    AS Variable [ Name=#4 ]
+                    AS Variable [ Name=#5 ]
                   ]
                 )
               ]
@@ -348,12 +314,21 @@
       Variable [ Name=$sim ]
       :=
       Variable [ Name=$sim ]
-      GROUP AS Variable [ Name=#5 ]
+      GROUP AS Variable [ Name=#1 ]
       (
         paperDBLP:=Variable [ Name=$paperDBLP ]
         prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
         paperCSX:=Variable [ Name=$paperCSX ]
         prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+        idDBLP:=Variable [ Name=$idDBLP ]
+        tokensUnrankedDBLP:=Variable [ Name=$tokensUnrankedDBLP ]
+        lenDBLP:=Variable [ Name=$lenDBLP ]
+        tokensDBLP:=Variable [ Name=$tokensDBLP ]
+        idCSX:=Variable [ Name=$idCSX ]
+        tokensUnrankedCSX:=Variable [ Name=$tokensUnrankedCSX ]
+        lenCSX:=Variable [ Name=$lenCSX ]
+        tokensCSX:=Variable [ Name=$tokensCSX ]
+        sim:=Variable [ Name=$sim ]
       )
 
   )
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.4.1/dblp-csx-3_5.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.4.1/dblp-csx-3_5.3.ast
index 1a9973c..897fe6b 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.4.1/dblp-csx-3_5.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.4.1/dblp-csx-3_5.3.ast
@@ -87,22 +87,7 @@
             LiteralExpr [STRING] [sim]
             :
             IndexAccessor [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [sim]
-                Variable [ Name=$lenDBLP ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$tokensDBLP ]
-                Variable [ Name=$idCSX ]
-                Variable [ Name=$idDBLP ]
-                Variable [ Name=$prefixTokenCSX ]
-                Variable [ Name=#5 ]
-                Variable [ Name=$tokensUnrankedCSX ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$lenCSX ]
-                Variable [ Name=$tokensCSX ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$paperCSX ]
-              ]
+              Variable [ Name=$sim ]
               Index:               LiteralExpr [LONG] [0]
             ]
           )
@@ -114,18 +99,14 @@
           AS Variable [ Name=$paperDBLP ]
 ,
           FunctionCall fuzzyjoin.subset-collection@3[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensDBLP]
-              Variable [ Name=$paperDBLP ]
-              Variable [ Name=$paperCSX ]
             ]
             LiteralExpr [LONG] [0]
             FunctionCall fuzzyjoin.prefix-len-jaccard@2[
               FunctionCall fuzzyjoin.len@1[
-                FunctionCall asterix.resolve@-1[
+                FunctionCall asterix.dataset@1[
                   LiteralExpr [STRING] [tokensDBLP]
-                  Variable [ Name=$paperDBLP ]
-                  Variable [ Name=$paperCSX ]
                 ]
               ]
               LiteralExpr [FLOAT] [0.5]
@@ -139,20 +120,14 @@
           AS Variable [ Name=$paperCSX ]
 ,
           FunctionCall fuzzyjoin.subset-collection@3[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensCSX]
-              Variable [ Name=$prefixTokenDBLP ]
-              Variable [ Name=$paperDBLP ]
-              Variable [ Name=$paperCSX ]
             ]
             LiteralExpr [LONG] [0]
             FunctionCall fuzzyjoin.prefix-len-jaccard@2[
               FunctionCall fuzzyjoin.len@1[
-                FunctionCall asterix.resolve@-1[
+                FunctionCall asterix.dataset@1[
                   LiteralExpr [STRING] [tokensCSX]
-                  Variable [ Name=$prefixTokenDBLP ]
-                  Variable [ Name=$paperDBLP ]
-                  Variable [ Name=$paperCSX ]
                 ]
               ]
               LiteralExpr [FLOAT] [0.5]
@@ -215,35 +190,24 @@
                   Variable [ Name=$tokenGrouped ]
                   :=
                   Variable [ Name=$token ]
-                  GROUP AS Variable [ Name=#1 ]
+                  GROUP AS Variable [ Name=#2 ]
                   (
                     paper:=Variable [ Name=$paper ]
                     token:=Variable [ Name=$token ]
+                    id:=Variable [ Name=$id ]
                   )
 
                 Orderby
                   FunctionCall asterix.sql-count@1[
                     (
                       SELECT ELEMENT [
-                      FunctionCall asterix.resolve@-1[
-                        LiteralExpr [STRING] [id]
-                        Variable [ Name=$lenDBLP ]
-                        Variable [ Name=$tokensUnrankedDBLP ]
-                        Variable [ Name=$paper ]
-                        Variable [ Name=$tokenUnranked ]
-                        Variable [ Name=#1 ]
-                        Variable [ Name=#2 ]
-                        Variable [ Name=$idDBLP ]
-                        Variable [ Name=$prefixTokenCSX ]
-                        Variable [ Name=$token ]
-                        Variable [ Name=$tokenGrouped ]
-                        Variable [ Name=$prefixTokenDBLP ]
-                        Variable [ Name=$paperDBLP ]
-                        Variable [ Name=$paperCSX ]
+                      FieldAccessor [
+                        Variable [ Name=#4 ]
+                        Field=id
                       ]
                       ]
-                      FROM [                        Variable [ Name=#1 ]
-                        AS Variable [ Name=#2 ]
+                      FROM [                        Variable [ Name=#2 ]
+                        AS Variable [ Name=#4 ]
                       ]
                     )
                   ]
@@ -326,35 +290,20 @@
                   (
                     paper:=Variable [ Name=$paper ]
                     token:=Variable [ Name=$token ]
+                    id:=Variable [ Name=$id ]
                   )
 
                 Orderby
                   FunctionCall asterix.sql-count@1[
                     (
                       SELECT ELEMENT [
-                      FunctionCall asterix.resolve@-1[
-                        LiteralExpr [STRING] [id]
-                        Variable [ Name=$lenDBLP ]
-                        Variable [ Name=$tokensUnrankedDBLP ]
-                        Variable [ Name=$paper ]
-                        Variable [ Name=$tokensDBLP ]
-                        Variable [ Name=$tokenUnranked ]
-                        Variable [ Name=$idCSX ]
-                        Variable [ Name=$idDBLP ]
-                        Variable [ Name=#3 ]
-                        Variable [ Name=#4 ]
-                        Variable [ Name=$prefixTokenCSX ]
-                        Variable [ Name=$token ]
-                        Variable [ Name=$tokensUnrankedCSX ]
-                        Variable [ Name=$tokenGrouped ]
-                        Variable [ Name=$prefixTokenDBLP ]
-                        Variable [ Name=$lenCSX ]
-                        Variable [ Name=$paperDBLP ]
-                        Variable [ Name=$paperCSX ]
+                      FieldAccessor [
+                        Variable [ Name=#5 ]
+                        Field=id
                       ]
                       ]
                       FROM [                        Variable [ Name=#3 ]
-                        AS Variable [ Name=#4 ]
+                        AS Variable [ Name=#5 ]
                       ]
                     )
                   ]
@@ -409,12 +358,24 @@
           Variable [ Name=$idCSX ]
           :=
           Variable [ Name=$idCSX ]
-          GROUP AS Variable [ Name=#5 ]
+          Variable [ Name=$sim ]
+          :=
+          Variable [ Name=$sim ]
+          GROUP AS Variable [ Name=#1 ]
           (
             paperDBLP:=Variable [ Name=$paperDBLP ]
             prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
             paperCSX:=Variable [ Name=$paperCSX ]
             prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+            idDBLP:=Variable [ Name=$idDBLP ]
+            tokensUnrankedDBLP:=Variable [ Name=$tokensUnrankedDBLP ]
+            lenDBLP:=Variable [ Name=$lenDBLP ]
+            tokensDBLP:=Variable [ Name=$tokensDBLP ]
+            idCSX:=Variable [ Name=$idCSX ]
+            tokensUnrankedCSX:=Variable [ Name=$tokensUnrankedCSX ]
+            lenCSX:=Variable [ Name=$lenCSX ]
+            tokensCSX:=Variable [ Name=$tokensCSX ]
+            sim:=Variable [ Name=$sim ]
           )
 
       )
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.4/dblp-csx-3_5.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.4/dblp-csx-3_5.3.ast
index 58d5ac7..f404dac 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.4/dblp-csx-3_5.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5.4/dblp-csx-3_5.3.ast
@@ -87,22 +87,7 @@
             LiteralExpr [STRING] [sim]
             :
             IndexAccessor [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [sim]
-                Variable [ Name=$lenDBLP ]
-                Variable [ Name=$tokensUnrankedDBLP ]
-                Variable [ Name=$tokensDBLP ]
-                Variable [ Name=$idCSX ]
-                Variable [ Name=$idDBLP ]
-                Variable [ Name=$prefixTokenCSX ]
-                Variable [ Name=#5 ]
-                Variable [ Name=$tokensUnrankedCSX ]
-                Variable [ Name=$prefixTokenDBLP ]
-                Variable [ Name=$lenCSX ]
-                Variable [ Name=$tokensCSX ]
-                Variable [ Name=$paperDBLP ]
-                Variable [ Name=$paperCSX ]
-              ]
+              Variable [ Name=$sim ]
               Index:               LiteralExpr [LONG] [0]
             ]
           )
@@ -114,18 +99,14 @@
           AS Variable [ Name=$paperDBLP ]
 ,
           FunctionCall fuzzyjoin.subset-collection@3[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensDBLP]
-              Variable [ Name=$paperDBLP ]
-              Variable [ Name=$paperCSX ]
             ]
             LiteralExpr [LONG] [0]
             FunctionCall fuzzyjoin.prefix-len-jaccard@2[
               FunctionCall fuzzyjoin.len@1[
-                FunctionCall asterix.resolve@-1[
+                FunctionCall asterix.dataset@1[
                   LiteralExpr [STRING] [tokensDBLP]
-                  Variable [ Name=$paperDBLP ]
-                  Variable [ Name=$paperCSX ]
                 ]
               ]
               LiteralExpr [FLOAT] [0.5]
@@ -139,20 +120,14 @@
           AS Variable [ Name=$paperCSX ]
 ,
           FunctionCall fuzzyjoin.subset-collection@3[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensCSX]
-              Variable [ Name=$prefixTokenDBLP ]
-              Variable [ Name=$paperDBLP ]
-              Variable [ Name=$paperCSX ]
             ]
             LiteralExpr [LONG] [0]
             FunctionCall fuzzyjoin.prefix-len-jaccard@2[
               FunctionCall fuzzyjoin.len@1[
-                FunctionCall asterix.resolve@-1[
+                FunctionCall asterix.dataset@1[
                   LiteralExpr [STRING] [tokensCSX]
-                  Variable [ Name=$prefixTokenDBLP ]
-                  Variable [ Name=$paperDBLP ]
-                  Variable [ Name=$paperCSX ]
                 ]
               ]
               LiteralExpr [FLOAT] [0.5]
@@ -215,35 +190,24 @@
                   Variable [ Name=$tokenGrouped ]
                   :=
                   Variable [ Name=$token ]
-                  GROUP AS Variable [ Name=#1 ]
+                  GROUP AS Variable [ Name=#2 ]
                   (
                     paper:=Variable [ Name=$paper ]
                     token:=Variable [ Name=$token ]
+                    id:=Variable [ Name=$id ]
                   )
 
                 Orderby
                   FunctionCall asterix.sql-count@1[
                     (
                       SELECT ELEMENT [
-                      FunctionCall asterix.resolve@-1[
-                        LiteralExpr [STRING] [id]
-                        Variable [ Name=$lenDBLP ]
-                        Variable [ Name=$tokensUnrankedDBLP ]
-                        Variable [ Name=$paper ]
-                        Variable [ Name=$tokenUnranked ]
-                        Variable [ Name=#1 ]
-                        Variable [ Name=#2 ]
-                        Variable [ Name=$idDBLP ]
-                        Variable [ Name=$prefixTokenCSX ]
-                        Variable [ Name=$token ]
-                        Variable [ Name=$tokenGrouped ]
-                        Variable [ Name=$prefixTokenDBLP ]
-                        Variable [ Name=$paperDBLP ]
-                        Variable [ Name=$paperCSX ]
+                      FieldAccessor [
+                        Variable [ Name=#4 ]
+                        Field=id
                       ]
                       ]
-                      FROM [                        Variable [ Name=#1 ]
-                        AS Variable [ Name=#2 ]
+                      FROM [                        Variable [ Name=#2 ]
+                        AS Variable [ Name=#4 ]
                       ]
                     )
                   ]
@@ -326,35 +290,20 @@
                   (
                     paper:=Variable [ Name=$paper ]
                     token:=Variable [ Name=$token ]
+                    id:=Variable [ Name=$id ]
                   )
 
                 Orderby
                   FunctionCall asterix.sql-count@1[
                     (
                       SELECT ELEMENT [
-                      FunctionCall asterix.resolve@-1[
-                        LiteralExpr [STRING] [id]
-                        Variable [ Name=$lenDBLP ]
-                        Variable [ Name=$tokensUnrankedDBLP ]
-                        Variable [ Name=$paper ]
-                        Variable [ Name=$tokensDBLP ]
-                        Variable [ Name=$tokenUnranked ]
-                        Variable [ Name=$idCSX ]
-                        Variable [ Name=$idDBLP ]
-                        Variable [ Name=#3 ]
-                        Variable [ Name=#4 ]
-                        Variable [ Name=$prefixTokenCSX ]
-                        Variable [ Name=$token ]
-                        Variable [ Name=$tokensUnrankedCSX ]
-                        Variable [ Name=$tokenGrouped ]
-                        Variable [ Name=$prefixTokenDBLP ]
-                        Variable [ Name=$lenCSX ]
-                        Variable [ Name=$paperDBLP ]
-                        Variable [ Name=$paperCSX ]
+                      FieldAccessor [
+                        Variable [ Name=#5 ]
+                        Field=id
                       ]
                       ]
                       FROM [                        Variable [ Name=#3 ]
-                        AS Variable [ Name=#4 ]
+                        AS Variable [ Name=#5 ]
                       ]
                     )
                   ]
@@ -409,12 +358,24 @@
           Variable [ Name=$idCSX ]
           :=
           Variable [ Name=$idCSX ]
-          GROUP AS Variable [ Name=#5 ]
+          Variable [ Name=$sim ]
+          :=
+          Variable [ Name=$sim ]
+          GROUP AS Variable [ Name=#1 ]
           (
             paperDBLP:=Variable [ Name=$paperDBLP ]
             prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
             paperCSX:=Variable [ Name=$paperCSX ]
             prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+            idDBLP:=Variable [ Name=$idDBLP ]
+            tokensUnrankedDBLP:=Variable [ Name=$tokensUnrankedDBLP ]
+            lenDBLP:=Variable [ Name=$lenDBLP ]
+            tokensDBLP:=Variable [ Name=$tokensDBLP ]
+            idCSX:=Variable [ Name=$idCSX ]
+            tokensUnrankedCSX:=Variable [ Name=$tokensUnrankedCSX ]
+            lenCSX:=Variable [ Name=$lenCSX ]
+            tokensCSX:=Variable [ Name=$tokensCSX ]
+            sim:=Variable [ Name=$sim ]
           )
 
       )
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5/dblp-csx-3_5.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5/dblp-csx-3_5.3.ast
index 09b0092..04290ce 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5/dblp-csx-3_5.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/fuzzyjoin/dblp-csx-3_5/dblp-csx-3_5.3.ast
@@ -52,16 +52,14 @@
       AS Variable [ Name=$paperDBLP ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensDBLP]
-          Variable [ Name=$paperDBLP ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
           FunctionCall fuzzyjoin.len@1[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensDBLP]
-              Variable [ Name=$paperDBLP ]
             ]
           ]
           LiteralExpr [FLOAT] [0.5]
@@ -75,20 +73,14 @@
       AS Variable [ Name=$paperCSX ]
 ,
       FunctionCall fuzzyjoin.subset-collection@3[
-        FunctionCall asterix.resolve@-1[
+        FunctionCall asterix.dataset@1[
           LiteralExpr [STRING] [tokensCSX]
-          Variable [ Name=$prefixTokenDBLP ]
-          Variable [ Name=$paperDBLP ]
-          Variable [ Name=$paperCSX ]
         ]
         LiteralExpr [LONG] [0]
         FunctionCall fuzzyjoin.prefix-len-jaccard@2[
           FunctionCall fuzzyjoin.len@1[
-            FunctionCall asterix.resolve@-1[
+            FunctionCall asterix.dataset@1[
               LiteralExpr [STRING] [tokensCSX]
-              Variable [ Name=$prefixTokenDBLP ]
-              Variable [ Name=$paperDBLP ]
-              Variable [ Name=$paperCSX ]
             ]
           ]
           LiteralExpr [FLOAT] [0.5]
@@ -151,35 +143,24 @@
               Variable [ Name=$tokenGroupped ]
               :=
               Variable [ Name=$token ]
-              GROUP AS Variable [ Name=#1 ]
+              GROUP AS Variable [ Name=#2 ]
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
+                id:=Variable [ Name=$id ]
               )
 
             Orderby
               FunctionCall asterix.sql-count@1[
                 (
                   SELECT ELEMENT [
-                  FunctionCall asterix.resolve@-1[
-                    LiteralExpr [STRING] [id]
-                    Variable [ Name=$lenDBLP ]
-                    Variable [ Name=$tokensUnrankedDBLP ]
-                    Variable [ Name=$paper ]
-                    Variable [ Name=$tokenUnranked ]
-                    Variable [ Name=#1 ]
-                    Variable [ Name=#2 ]
-                    Variable [ Name=$idDBLP ]
-                    Variable [ Name=$prefixTokenCSX ]
-                    Variable [ Name=$token ]
-                    Variable [ Name=$tokenGroupped ]
-                    Variable [ Name=$prefixTokenDBLP ]
-                    Variable [ Name=$paperDBLP ]
-                    Variable [ Name=$paperCSX ]
+                  FieldAccessor [
+                    Variable [ Name=#4 ]
+                    Field=id
                   ]
                   ]
-                  FROM [                    Variable [ Name=#1 ]
-                    AS Variable [ Name=#2 ]
+                  FROM [                    Variable [ Name=#2 ]
+                    AS Variable [ Name=#4 ]
                   ]
                 )
               ]
@@ -262,35 +243,20 @@
               (
                 paper:=Variable [ Name=$paper ]
                 token:=Variable [ Name=$token ]
+                id:=Variable [ Name=$id ]
               )
 
             Orderby
               FunctionCall asterix.sql-count@1[
                 (
                   SELECT ELEMENT [
-                  FunctionCall asterix.resolve@-1[
-                    LiteralExpr [STRING] [id]
-                    Variable [ Name=$lenDBLP ]
-                    Variable [ Name=$tokensUnrankedDBLP ]
-                    Variable [ Name=$paper ]
-                    Variable [ Name=$tokensDBLP ]
-                    Variable [ Name=$tokenUnranked ]
-                    Variable [ Name=$idCSX ]
-                    Variable [ Name=$idDBLP ]
-                    Variable [ Name=#3 ]
-                    Variable [ Name=#4 ]
-                    Variable [ Name=$prefixTokenCSX ]
-                    Variable [ Name=$token ]
-                    Variable [ Name=$tokensUnrankedCSX ]
-                    Variable [ Name=$tokenGroupped ]
-                    Variable [ Name=$prefixTokenDBLP ]
-                    Variable [ Name=$lenCSX ]
-                    Variable [ Name=$paperDBLP ]
-                    Variable [ Name=$paperCSX ]
+                  FieldAccessor [
+                    Variable [ Name=#5 ]
+                    Field=id
                   ]
                   ]
                   FROM [                    Variable [ Name=#3 ]
-                    AS Variable [ Name=#4 ]
+                    AS Variable [ Name=#5 ]
                   ]
                 )
               ]
@@ -348,12 +314,21 @@
       Variable [ Name=$sim ]
       :=
       Variable [ Name=$sim ]
-      GROUP AS Variable [ Name=#5 ]
+      GROUP AS Variable [ Name=#1 ]
       (
         paperDBLP:=Variable [ Name=$paperDBLP ]
         prefixTokenDBLP:=Variable [ Name=$prefixTokenDBLP ]
         paperCSX:=Variable [ Name=$paperCSX ]
         prefixTokenCSX:=Variable [ Name=$prefixTokenCSX ]
+        idDBLP:=Variable [ Name=$idDBLP ]
+        tokensUnrankedDBLP:=Variable [ Name=$tokensUnrankedDBLP ]
+        lenDBLP:=Variable [ Name=$lenDBLP ]
+        tokensDBLP:=Variable [ Name=$tokensDBLP ]
+        idCSX:=Variable [ Name=$idCSX ]
+        tokensUnrankedCSX:=Variable [ Name=$tokensUnrankedCSX ]
+        lenCSX:=Variable [ Name=$lenCSX ]
+        tokensCSX:=Variable [ Name=$tokensCSX ]
+        sim:=Variable [ Name=$sim ]
       )
 
   )
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/hdfs/hdfs_02/hdfs_02.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/hdfs/hdfs_02/hdfs_02.3.ast
index b072ef5..f88caa5 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/hdfs/hdfs_02/hdfs_02.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/hdfs/hdfs_02/hdfs_02.3.ast
@@ -13,10 +13,9 @@
     FunctionCall asterix.count@1[
       (
         SELECT ELEMENT [
-        FunctionCall asterix.resolve@-1[
-          LiteralExpr [STRING] [token]
+        FunctionCall asterix.field-access-by-name@2[
           Variable [ Name=$g ]
-          Variable [ Name=$tok ]
+          LiteralExpr [STRING] [token]
         ]
         ]
         FROM [          Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/hdfs/hdfs_03/hdfs_03.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/hdfs/hdfs_03/hdfs_03.3.ast
index b072ef5..f88caa5 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/hdfs/hdfs_03/hdfs_03.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/hdfs/hdfs_03/hdfs_03.3.ast
@@ -13,10 +13,9 @@
     FunctionCall asterix.count@1[
       (
         SELECT ELEMENT [
-        FunctionCall asterix.resolve@-1[
-          LiteralExpr [STRING] [token]
+        FunctionCall asterix.field-access-by-name@2[
           Variable [ Name=$g ]
-          Variable [ Name=$tok ]
+          LiteralExpr [STRING] [token]
         ]
         ]
         FROM [          Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/hdfs/hdfs_shortcircuit/hdfs_shortcircuit.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/hdfs/hdfs_shortcircuit/hdfs_shortcircuit.3.ast
index b072ef5..f88caa5 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/hdfs/hdfs_shortcircuit/hdfs_shortcircuit.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/hdfs/hdfs_shortcircuit/hdfs_shortcircuit.3.ast
@@ -13,10 +13,9 @@
     FunctionCall asterix.count@1[
       (
         SELECT ELEMENT [
-        FunctionCall asterix.resolve@-1[
-          LiteralExpr [STRING] [token]
+        FunctionCall asterix.field-access-by-name@2[
           Variable [ Name=$g ]
-          Variable [ Name=$tok ]
+          LiteralExpr [STRING] [token]
         ]
         ]
         FROM [          Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/hints/issue_251_dataset_hint_6/issue_251_dataset_hint_6.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/hints/issue_251_dataset_hint_6/issue_251_dataset_hint_6.3.ast
index b072ef5..f88caa5 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/hints/issue_251_dataset_hint_6/issue_251_dataset_hint_6.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/hints/issue_251_dataset_hint_6/issue_251_dataset_hint_6.3.ast
@@ -13,10 +13,9 @@
     FunctionCall asterix.count@1[
       (
         SELECT ELEMENT [
-        FunctionCall asterix.resolve@-1[
-          LiteralExpr [STRING] [token]
+        FunctionCall asterix.field-access-by-name@2[
           Variable [ Name=$g ]
-          Variable [ Name=$tok ]
+          LiteralExpr [STRING] [token]
         ]
         ]
         FROM [          Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/misc/groupby-orderby-count/groupby-orderby-count.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/misc/groupby-orderby-count/groupby-orderby-count.3.ast
index 9c7ca3e..8784d48 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/misc/groupby-orderby-count/groupby-orderby-count.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/misc/groupby-orderby-count/groupby-orderby-count.3.ast
@@ -13,10 +13,9 @@
     FunctionCall asterix.count@1[
       (
         SELECT ELEMENT [
-        FunctionCall asterix.resolve@-1[
-          LiteralExpr [STRING] [token]
+        FunctionCall asterix.field-access-by-name@2[
           Variable [ Name=$g ]
-          Variable [ Name=$tok ]
+          LiteralExpr [STRING] [token]
         ]
         ]
         FROM [          Variable [ Name=$g ]
@@ -54,10 +53,9 @@
   FunctionCall asterix.count@1[
     (
       SELECT ELEMENT [
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [token]
+      FunctionCall asterix.field-access-by-name@2[
         Variable [ Name=$g ]
-        Variable [ Name=$tok ]
+        LiteralExpr [STRING] [token]
       ]
       ]
       FROM [        Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/open-closed/query-issue456/query-issue456.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/open-closed/query-issue456/query-issue456.3.ast
index 09d263d..b276b19 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/open-closed/query-issue456/query-issue456.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/open-closed/query-issue456/query-issue456.3.ast
@@ -2,14 +2,14 @@
 Query:
 SELECT ELEMENT [
 OrderedListConstructor [
-  FieldAccessor [
-    Variable [ Name=$x ]
-    Field=int_m
-  ]
+  Variable [ Name=$int_m ]
   FunctionCall asterix.count@1[
     (
       SELECT ELEMENT [
-      Variable [ Name=$x ]
+      FunctionCall asterix.field-access-by-name@2[
+        Variable [ Name=$g ]
+        LiteralExpr [STRING] [x]
+      ]
       ]
       FROM [        Variable [ Name=$g ]
         AS Variable [ Name=$g ]
@@ -39,12 +39,10 @@
   GROUP AS Variable [ Name=$g ]
   (
     x:=Variable [ Name=$x ]
+    id:=Variable [ Name=$id ]
   )
 
 Orderby
-  FieldAccessor [
-    Variable [ Name=$x ]
-    Field=int_m
-  ]
+  Variable [ Name=$int_m ]
   ASC
 
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/semistructured/count-nullable/count-nullable.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/semistructured/count-nullable/count-nullable.3.ast
index 0c83370..76e40c5 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/semistructured/count-nullable/count-nullable.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/semistructured/count-nullable/count-nullable.3.ast
@@ -13,10 +13,9 @@
     FunctionCall asterix.count@1[
       (
         SELECT ELEMENT [
-        FunctionCall asterix.resolve@-1[
-          LiteralExpr [STRING] [c]
+        FunctionCall asterix.field-access-by-name@2[
           Variable [ Name=$g ]
-          Variable [ Name=$age ]
+          LiteralExpr [STRING] [c]
         ]
         ]
         FROM [          Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/spatial/cell-aggregation-with-filtering/cell-aggregation-with-filtering.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/spatial/cell-aggregation-with-filtering/cell-aggregation-with-filtering.3.ast
index 8346dad..b37afaf 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/spatial/cell-aggregation-with-filtering/cell-aggregation-with-filtering.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/spatial/cell-aggregation-with-filtering/cell-aggregation-with-filtering.3.ast
@@ -89,6 +89,8 @@
   GROUP AS Variable [ Name=$g ]
   (
     t:=Variable [ Name=$t ]
+    keywords:=Variable [ Name=$keywords ]
+    region:=Variable [ Name=$region ]
   )
 
 Let Variable [ Name=$num ]
@@ -96,7 +98,10 @@
   FunctionCall asterix.count@1[
     (
       SELECT ELEMENT [
-      Variable [ Name=$t ]
+      FunctionCall asterix.field-access-by-name@2[
+        Variable [ Name=$g ]
+        LiteralExpr [STRING] [t]
+      ]
       ]
       FROM [        Variable [ Name=$g ]
         AS Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/spatial/cell-aggregation/cell-aggregation.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/spatial/cell-aggregation/cell-aggregation.3.ast
index 2b26217..342584e 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/spatial/cell-aggregation/cell-aggregation.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/spatial/cell-aggregation/cell-aggregation.3.ast
@@ -47,10 +47,9 @@
       FunctionCall asterix.count@1[
         (
           SELECT ELEMENT [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [o]
+          FunctionCall asterix.field-access-by-name@2[
             Variable [ Name=$g ]
-            Variable [ Name=$c ]
+            LiteralExpr [STRING] [o]
           ]
           ]
           FROM [            Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/temporal/overlap_bins_gby_0/overlap_bins_gby_0.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/temporal/overlap_bins_gby_0/overlap_bins_gby_0.3.ast
index 44c2b3b..d237bd8 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/temporal/overlap_bins_gby_0/overlap_bins_gby_0.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/temporal/overlap_bins_gby_0/overlap_bins_gby_0.3.ast
@@ -41,10 +41,9 @@
         :
         (
           SELECT ELEMENT [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [i]
+          FunctionCall asterix.field-access-by-name@2[
             Variable [ Name=$g ]
-            Variable [ Name=$bin ]
+            LiteralExpr [STRING] [i]
           ]
           ]
           FROM [            Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/temporal/overlap_bins_gby_1/overlap_bins_gby_1.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/temporal/overlap_bins_gby_1/overlap_bins_gby_1.3.ast
index 6edcb68..998fc6c 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/temporal/overlap_bins_gby_1/overlap_bins_gby_1.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/temporal/overlap_bins_gby_1/overlap_bins_gby_1.3.ast
@@ -10,20 +10,13 @@
   (
     LiteralExpr [STRING] [count]
     :
-    FunctionCall asterix.sql-count@1[
+    FunctionCall asterix.count@1[
       (
         SELECT ELEMENT [
-        (
-          SELECT ELEMENT [
-          LiteralExpr [LONG] [1]
-          ]
-          FROM [            Variable [ Name=$g ]
-            AS Variable [ Name=$g ]
-          ]
-        )
+        LiteralExpr [LONG] [1]
         ]
         FROM [          Variable [ Name=$g ]
-          AS Variable [ Name=#1 ]
+          AS Variable [ Name=$g ]
         ]
       )
     ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tinysocial/tinysocial-suite-open/tinysocial-suite.26.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tinysocial/tinysocial-suite-open/tinysocial-suite.26.ast
index 2228a45..9805e0a 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tinysocial/tinysocial-suite-open/tinysocial-suite.26.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tinysocial/tinysocial-suite-open/tinysocial-suite.26.ast
@@ -1,14 +1,7 @@
 DataverseUse TinySocial
 Query:
 SELECT [
-FieldAccessor [
-  FunctionCall asterix.resolve@-1[
-    LiteralExpr [STRING] [employment]
-    Variable [ Name=#1 ]
-    Variable [ Name=$organization-name ]
-  ]
-  Field=organization-name
-]
+Variable [ Name=$organization-name ]
 organization
 FunctionCall asterix.sql-avg@1[
   (
@@ -125,13 +118,6 @@
   )
 
 Orderby
-  FieldAccessor [
-    FunctionCall asterix.resolve@-1[
-      LiteralExpr [STRING] [employment]
-      Variable [ Name=#1 ]
-      Variable [ Name=$organization-name ]
-    ]
-    Field=organization-name
-  ]
+  Variable [ Name=$organization-name ]
   ASC
 
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tinysocial/tinysocial-suite-open/tinysocial-suite.27.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tinysocial/tinysocial-suite-open/tinysocial-suite.27.ast
index c982ef7..0cbc410 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tinysocial/tinysocial-suite-open/tinysocial-suite.27.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tinysocial/tinysocial-suite-open/tinysocial-suite.27.ast
@@ -103,3 +103,9 @@
   AS Variable [ Name=$employment ]
 ]
 Group All
+  GROUP AS Variable [ Name=#1 ]
+  (
+    fbu:=Variable [ Name=$fbu ]
+    employment:=Variable [ Name=$employment ]
+  )
+
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q01_pricing_summary_report_nt/q01_pricing_summary_report_nt.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q01_pricing_summary_report_nt/q01_pricing_summary_report_nt.3.ast
index 531a2ef..753f130 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q01_pricing_summary_report_nt/q01_pricing_summary_report_nt.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q01_pricing_summary_report_nt/q01_pricing_summary_report_nt.3.ast
@@ -199,11 +199,9 @@
     FunctionCall asterix.count@1[
       (
         SELECT ELEMENT [
-        FunctionCall asterix.resolve@-1[
-          LiteralExpr [STRING] [l]
+        FunctionCall asterix.field-access-by-name@2[
           Variable [ Name=$g ]
-          Variable [ Name=$l_linestatus ]
-          Variable [ Name=$l_returnflag ]
+          LiteralExpr [STRING] [l]
         ]
         ]
         FROM [          Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q03_shipping_priority_nt/q03_shipping_priority_nt.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q03_shipping_priority_nt/q03_shipping_priority_nt.3.ast
index 7b69432..f0ad1f5 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q03_shipping_priority_nt/q03_shipping_priority_nt.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q03_shipping_priority_nt/q03_shipping_priority_nt.3.ast
@@ -145,12 +145,9 @@
       ]
       FROM [        (
           SELECT ELEMENT [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [l]
-            Variable [ Name=$o_shippriority ]
+          FunctionCall asterix.field-access-by-name@2[
             Variable [ Name=$g ]
-            Variable [ Name=$o_orderdate ]
-            Variable [ Name=$l_orderkey ]
+            LiteralExpr [STRING] [l]
           ]
           ]
           FROM [            Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q05_local_supplier_volume/q05_local_supplier_volume.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q05_local_supplier_volume/q05_local_supplier_volume.3.ast
index 8a2f536..e65436e 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q05_local_supplier_volume/q05_local_supplier_volume.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q05_local_supplier_volume/q05_local_supplier_volume.3.ast
@@ -326,10 +326,9 @@
       ]
       FROM [        (
           SELECT ELEMENT [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [o1]
+          FunctionCall asterix.field-access-by-name@2[
             Variable [ Name=$g ]
-            Variable [ Name=$n_name ]
+            LiteralExpr [STRING] [o1]
           ]
           ]
           FROM [            Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q06_forecast_revenue_change/q06_forecast_revenue_change.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q06_forecast_revenue_change/q06_forecast_revenue_change.3.ast
index 60ca4f3..5d306b5 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q06_forecast_revenue_change/q06_forecast_revenue_change.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q06_forecast_revenue_change/q06_forecast_revenue_change.3.ast
@@ -82,3 +82,8 @@
     ]
   ]
 Group All
+  GROUP AS Variable [ Name=#1 ]
+  (
+    l:=Variable [ Name=$l ]
+  )
+
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q07_volume_shipping/q07_volume_shipping.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q07_volume_shipping/q07_volume_shipping.3.ast
index b5729fd..4a93077 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q07_volume_shipping/q07_volume_shipping.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q07_volume_shipping/q07_volume_shipping.3.ast
@@ -369,6 +369,7 @@
   (
     locs:=Variable [ Name=$locs ]
     t:=Variable [ Name=$t ]
+    l_year0:=Variable [ Name=$l_year0 ]
   )
 
 Let Variable [ Name=$revenue ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q10_returned_item/q10_returned_item.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q10_returned_item/q10_returned_item.3.ast
index 81ed2d2..1bb8627 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q10_returned_item/q10_returned_item.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q10_returned_item/q10_returned_item.3.ast
@@ -356,16 +356,9 @@
       ]
       FROM [        (
           SELECT ELEMENT [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [locn]
-            Variable [ Name=$c_address ]
+          FunctionCall asterix.field-access-by-name@2[
             Variable [ Name=$g ]
-            Variable [ Name=$c_name ]
-            Variable [ Name=$c_phone ]
-            Variable [ Name=$c_acctbal ]
-            Variable [ Name=$n_name ]
-            Variable [ Name=$c_custkey ]
-            Variable [ Name=$c_comment ]
+            LiteralExpr [STRING] [locn]
           ]
           ]
           FROM [            Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q10_returned_item_int64/q10_returned_item_int64.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q10_returned_item_int64/q10_returned_item_int64.3.ast
index 81ed2d2..1bb8627 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q10_returned_item_int64/q10_returned_item_int64.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q10_returned_item_int64/q10_returned_item_int64.3.ast
@@ -356,16 +356,9 @@
       ]
       FROM [        (
           SELECT ELEMENT [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [locn]
-            Variable [ Name=$c_address ]
+          FunctionCall asterix.field-access-by-name@2[
             Variable [ Name=$g ]
-            Variable [ Name=$c_name ]
-            Variable [ Name=$c_phone ]
-            Variable [ Name=$c_acctbal ]
-            Variable [ Name=$n_name ]
-            Variable [ Name=$c_custkey ]
-            Variable [ Name=$c_comment ]
+            LiteralExpr [STRING] [locn]
           ]
           ]
           FROM [            Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q13_customer_distribution/q13_customer_distribution.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q13_customer_distribution/q13_customer_distribution.3.ast
index 7f06804..0c026d7 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q13_customer_distribution/q13_customer_distribution.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q13_customer_distribution/q13_customer_distribution.3.ast
@@ -36,10 +36,9 @@
             ]
             FROM [              (
                 SELECT ELEMENT [
-                FunctionCall asterix.resolve@-1[
-                  LiteralExpr [STRING] [co]
+                FunctionCall asterix.field-access-by-name@2[
                   Variable [ Name=$g2 ]
-                  Variable [ Name=$c_custkey ]
+                  LiteralExpr [STRING] [co]
                 ]
                 ]
                 FROM [                  Variable [ Name=$g2 ]
@@ -145,23 +144,16 @@
 
 Let Variable [ Name=$custdist ]
   :=
-  FunctionCall asterix.sql-count@1[
+  FunctionCall asterix.count@1[
     (
       SELECT ELEMENT [
-      (
-        SELECT ELEMENT [
-        FieldAccessor [
-          Variable [ Name=#1 ]
-          Field=gco
-        ]
-        ]
-        FROM [          Variable [ Name=$g ]
-          AS Variable [ Name=$g ]
-        ]
-      )
+      FunctionCall asterix.field-access-by-name@2[
+        Variable [ Name=$g ]
+        LiteralExpr [STRING] [gco]
+      ]
       ]
       FROM [        Variable [ Name=$g ]
-        AS Variable [ Name=#1 ]
+        AS Variable [ Name=$g ]
       ]
     )
   ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q14_promotion_effect/q14_promotion_effect.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q14_promotion_effect/q14_promotion_effect.3.ast
index 05e22d1..9ac71e1 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q14_promotion_effect/q14_promotion_effect.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q14_promotion_effect/q14_promotion_effect.3.ast
@@ -24,7 +24,7 @@
             ]
             *
             OperatorExpr [
-              LiteralExpr [LONG] [1]
+              Variable [ Name=$t ]
               -
               FieldAccessor [
                 Variable [ Name=$i ]
@@ -39,12 +39,9 @@
       ]
       FROM [        (
           SELECT ELEMENT [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [lp]
+          FunctionCall asterix.field-access-by-name@2[
             Variable [ Name=$g ]
-            Variable [ Name=$l ]
-            Variable [ Name=$p ]
-            Variable [ Name=$t ]
+            LiteralExpr [STRING] [lp]
           ]
           ]
           FROM [            Variable [ Name=$g ]
@@ -66,7 +63,7 @@
         ]
         *
         OperatorExpr [
-          LiteralExpr [LONG] [1]
+          Variable [ Name=$t ]
           -
           FieldAccessor [
             Variable [ Name=$i ]
@@ -77,12 +74,9 @@
       ]
       FROM [        (
           SELECT ELEMENT [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [lp]
+          FunctionCall asterix.field-access-by-name@2[
             Variable [ Name=$g ]
-            Variable [ Name=$l ]
-            Variable [ Name=$p ]
-            Variable [ Name=$t ]
+            LiteralExpr [STRING] [lp]
           ]
           ]
           FROM [            Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q16_parts_supplier_relationship/q16_parts_supplier_relationship.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q16_parts_supplier_relationship/q16_parts_supplier_relationship.3.ast
index a6d19ba..94cd5e4 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q16_parts_supplier_relationship/q16_parts_supplier_relationship.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q16_parts_supplier_relationship/q16_parts_supplier_relationship.3.ast
@@ -341,12 +341,9 @@
       ]
       FROM [        (
           SELECT ELEMENT [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [t2]
+          FunctionCall asterix.field-access-by-name@2[
             Variable [ Name=$g ]
-            Variable [ Name=$p_brand ]
-            Variable [ Name=$p_size ]
-            Variable [ Name=$p_type ]
+            LiteralExpr [STRING] [t2]
           ]
           ]
           FROM [            Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q17_large_gby_variant/q17_large_gby_variant.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q17_large_gby_variant/q17_large_gby_variant.3.ast
index 25bc7f7..63834e1 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q17_large_gby_variant/q17_large_gby_variant.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q17_large_gby_variant/q17_large_gby_variant.3.ast
@@ -13,10 +13,9 @@
     FunctionCall asterix.count@1[
       (
         SELECT ELEMENT [
-        FunctionCall asterix.resolve@-1[
-          LiteralExpr [STRING] [l]
+        FunctionCall asterix.field-access-by-name@2[
           Variable [ Name=$g ]
-          Variable [ Name=$l_partkey ]
+          LiteralExpr [STRING] [l]
         ]
         ]
         FROM [          Variable [ Name=$g ]
@@ -41,10 +40,9 @@
           ]
           FROM [            (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [l]
+              FunctionCall asterix.field-access-by-name@2[
                 Variable [ Name=$g ]
-                Variable [ Name=$l_partkey ]
+                LiteralExpr [STRING] [l]
               ]
               ]
               FROM [                Variable [ Name=$g ]
@@ -70,10 +68,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_partkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -98,10 +95,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_partkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -126,10 +122,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_partkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -154,10 +149,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_partkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -182,10 +176,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_partkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -210,10 +203,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_partkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -238,10 +230,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_partkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -266,10 +257,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_partkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -294,10 +284,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_partkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q18_large_volume_customer/q18_large_volume_customer.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q18_large_volume_customer/q18_large_volume_customer.3.ast
index 4446895..0ab8030 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q18_large_volume_customer/q18_large_volume_customer.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q18_large_volume_customer/q18_large_volume_customer.3.ast
@@ -40,14 +40,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$o_orderdate ]
-              Variable [ Name=$c_name ]
-              Variable [ Name=$o_orderkey ]
-              Variable [ Name=$o_totalprice ]
-              Variable [ Name=$c_custkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -92,12 +87,9 @@
             ]
             FROM [              (
                 SELECT ELEMENT [
-                FunctionCall asterix.resolve@-1[
-                  LiteralExpr [STRING] [l]
-                  Variable [ Name=$o ]
-                  Variable [ Name=$l_orderkey ]
+                FunctionCall asterix.field-access-by-name@2[
                   Variable [ Name=$g2 ]
-                  Variable [ Name=$c ]
+                  LiteralExpr [STRING] [l]
                 ]
                 ]
                 FROM [                  Variable [ Name=$g2 ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q20_potential_part_promotion/q20_potential_part_promotion.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q20_potential_part_promotion/q20_potential_part_promotion.3.ast
index 9ef07b1..41802c2 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q20_potential_part_promotion/q20_potential_part_promotion.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q20_potential_part_promotion/q20_potential_part_promotion.3.ast
@@ -62,11 +62,9 @@
                   ]
                   FROM [                    (
                       SELECT ELEMENT [
-                      FunctionCall asterix.resolve@-1[
-                        LiteralExpr [STRING] [l]
-                        Variable [ Name=$l_suppkey ]
+                      FunctionCall asterix.field-access-by-name@2[
                         Variable [ Name=$g ]
-                        Variable [ Name=$l_partkey ]
+                        LiteralExpr [STRING] [l]
                       ]
                       ]
                       FROM [                        Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.ast
index 62cbc19..b91a2a9 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.ast
@@ -481,23 +481,16 @@
 
 Let Variable [ Name=$numwait ]
   :=
-  FunctionCall asterix.sql-count@1[
+  FunctionCall asterix.count@1[
     (
       SELECT ELEMENT [
-      (
-        SELECT ELEMENT [
-        FieldAccessor [
-          Variable [ Name=#1 ]
-          Field=t4
-        ]
-        ]
-        FROM [          Variable [ Name=$g ]
-          AS Variable [ Name=$g ]
-        ]
-      )
+      FunctionCall asterix.field-access-by-name@2[
+        Variable [ Name=$g ]
+        LiteralExpr [STRING] [t4]
+      ]
       ]
       FROM [        Variable [ Name=$g ]
-        AS Variable [ Name=#1 ]
+        AS Variable [ Name=$g ]
       ]
     )
   ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q22_global_sales_opportunity/q22_global_sales_opportunity.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q22_global_sales_opportunity/q22_global_sales_opportunity.3.ast
index ffd3d1c..adeab44 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q22_global_sales_opportunity/q22_global_sales_opportunity.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/q22_global_sales_opportunity/q22_global_sales_opportunity.3.ast
@@ -79,10 +79,9 @@
     FunctionCall asterix.count@1[
       (
         SELECT ELEMENT [
-        FunctionCall asterix.resolve@-1[
-          LiteralExpr [STRING] [ct]
+        FunctionCall asterix.field-access-by-name@2[
           Variable [ Name=$g ]
-          Variable [ Name=$cntrycode ]
+          LiteralExpr [STRING] [ct]
         ]
         ]
         FROM [          Variable [ Name=$g ]
@@ -104,10 +103,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [ct]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$cntrycode ]
+              LiteralExpr [STRING] [ct]
             ]
             ]
             FROM [              Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/query-issue601/query-issue601.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/query-issue601/query-issue601.3.ast
index f1705b8..2c32932 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/query-issue601/query-issue601.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch-sql-like/query-issue601/query-issue601.3.ast
@@ -5,32 +5,18 @@
   (
     LiteralExpr [STRING] [l_linenumber]
     :
-    FieldAccessor [
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [l]
-        Variable [ Name=$g ]
-        Variable [ Name=$l_linenumber ]
-      ]
-      Field=l_linenumber
-    ]
+    Variable [ Name=$l_linenumber ]
   )
   (
     LiteralExpr [STRING] [count_order]
     :
-    FunctionCall asterix.sql-count@1[
+    FunctionCall asterix.count@1[
       (
         SELECT ELEMENT [
-        (
-          SELECT ELEMENT [
-          Variable [ Name=$g ]
-          ]
-          FROM [            Variable [ Name=$g ]
-            AS Variable [ Name=$g ]
-          ]
-        )
+        Variable [ Name=$g ]
         ]
         FROM [          Variable [ Name=$g ]
-          AS Variable [ Name=#1 ]
+          AS Variable [ Name=$g ]
         ]
       )
     ]
@@ -55,13 +41,6 @@
   )
 
 Orderby
-  FieldAccessor [
-    FunctionCall asterix.resolve@-1[
-      LiteralExpr [STRING] [l]
-      Variable [ Name=$g ]
-      Variable [ Name=$l_linenumber ]
-    ]
-    Field=l_linenumber
-  ]
+  Variable [ Name=$l_linenumber ]
   ASC
 
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q01_pricing_summary_report_nt/q01_pricing_summary_report_nt.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q01_pricing_summary_report_nt/q01_pricing_summary_report_nt.3.ast
index 531a2ef..753f130 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q01_pricing_summary_report_nt/q01_pricing_summary_report_nt.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q01_pricing_summary_report_nt/q01_pricing_summary_report_nt.3.ast
@@ -199,11 +199,9 @@
     FunctionCall asterix.count@1[
       (
         SELECT ELEMENT [
-        FunctionCall asterix.resolve@-1[
-          LiteralExpr [STRING] [l]
+        FunctionCall asterix.field-access-by-name@2[
           Variable [ Name=$g ]
-          Variable [ Name=$l_linestatus ]
-          Variable [ Name=$l_returnflag ]
+          LiteralExpr [STRING] [l]
         ]
         ]
         FROM [          Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q03_shipping_priority_nt/q03_shipping_priority_nt.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q03_shipping_priority_nt/q03_shipping_priority_nt.3.ast
index 7b69432..f0ad1f5 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q03_shipping_priority_nt/q03_shipping_priority_nt.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q03_shipping_priority_nt/q03_shipping_priority_nt.3.ast
@@ -145,12 +145,9 @@
       ]
       FROM [        (
           SELECT ELEMENT [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [l]
-            Variable [ Name=$o_shippriority ]
+          FunctionCall asterix.field-access-by-name@2[
             Variable [ Name=$g ]
-            Variable [ Name=$o_orderdate ]
-            Variable [ Name=$l_orderkey ]
+            LiteralExpr [STRING] [l]
           ]
           ]
           FROM [            Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q05_local_supplier_volume/q05_local_supplier_volume.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q05_local_supplier_volume/q05_local_supplier_volume.3.ast
index 8a2f536..e65436e 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q05_local_supplier_volume/q05_local_supplier_volume.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q05_local_supplier_volume/q05_local_supplier_volume.3.ast
@@ -326,10 +326,9 @@
       ]
       FROM [        (
           SELECT ELEMENT [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [o1]
+          FunctionCall asterix.field-access-by-name@2[
             Variable [ Name=$g ]
-            Variable [ Name=$n_name ]
+            LiteralExpr [STRING] [o1]
           ]
           ]
           FROM [            Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q06_forecast_revenue_change/q06_forecast_revenue_change.4.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q06_forecast_revenue_change/q06_forecast_revenue_change.4.ast
index 3791a43..17b2c43 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q06_forecast_revenue_change/q06_forecast_revenue_change.4.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q06_forecast_revenue_change/q06_forecast_revenue_change.4.ast
@@ -69,3 +69,8 @@
     ]
   ]
 Group All
+  GROUP AS Variable [ Name=#1 ]
+  (
+    l:=Variable [ Name=$l ]
+  )
+
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q07_volume_shipping/q07_volume_shipping.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q07_volume_shipping/q07_volume_shipping.3.ast
index b5729fd..4a93077 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q07_volume_shipping/q07_volume_shipping.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q07_volume_shipping/q07_volume_shipping.3.ast
@@ -369,6 +369,7 @@
   (
     locs:=Variable [ Name=$locs ]
     t:=Variable [ Name=$t ]
+    l_year0:=Variable [ Name=$l_year0 ]
   )
 
 Let Variable [ Name=$revenue ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q08_national_market_share/q08_national_market_share.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q08_national_market_share/q08_national_market_share.3.ast
index f53ad0e..5c64434 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q08_national_market_share/q08_national_market_share.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q08_national_market_share/q08_national_market_share.3.ast
@@ -38,10 +38,9 @@
           ]
           FROM [            (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [t]
+              FunctionCall asterix.field-access-by-name@2[
                 Variable [ Name=$g ]
-                Variable [ Name=$year ]
+                LiteralExpr [STRING] [t]
               ]
               ]
               FROM [                Variable [ Name=$g ]
@@ -63,10 +62,9 @@
           ]
           FROM [            (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [t]
+              FunctionCall asterix.field-access-by-name@2[
                 Variable [ Name=$g ]
-                Variable [ Name=$year ]
+                LiteralExpr [STRING] [t]
               ]
               ]
               FROM [                Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q09_product_type_profit_nt/q09_product_type_profit_nt.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q09_product_type_profit_nt/q09_product_type_profit_nt.3.ast
index 74227e8..4810d686 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q09_product_type_profit_nt/q09_product_type_profit_nt.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q09_product_type_profit_nt/q09_product_type_profit_nt.3.ast
@@ -25,11 +25,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [profit]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$nation ]
-              Variable [ Name=$o_year ]
+              LiteralExpr [STRING] [profit]
             ]
             ]
             FROM [              Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q12_shipping/q12_shipping.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q12_shipping/q12_shipping.3.ast
index be59cf6..ad76f90 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q12_shipping/q12_shipping.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q12_shipping/q12_shipping.3.ast
@@ -45,10 +45,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [o]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_shipmode ]
+              LiteralExpr [STRING] [o]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -95,10 +94,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [o]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_shipmode ]
+              LiteralExpr [STRING] [o]
             ]
             ]
             FROM [              Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q13_customer_distribution/q13_customer_distribution.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q13_customer_distribution/q13_customer_distribution.3.ast
index 7f06804..2bf34bb 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q13_customer_distribution/q13_customer_distribution.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q13_customer_distribution/q13_customer_distribution.3.ast
@@ -36,10 +36,9 @@
             ]
             FROM [              (
                 SELECT ELEMENT [
-                FunctionCall asterix.resolve@-1[
-                  LiteralExpr [STRING] [co]
+                FunctionCall asterix.field-access-by-name@2[
                   Variable [ Name=$g2 ]
-                  Variable [ Name=$c_custkey ]
+                  LiteralExpr [STRING] [co]
                 ]
                 ]
                 FROM [                  Variable [ Name=$g2 ]
@@ -148,17 +147,10 @@
   FunctionCall asterix.sql-count@1[
     (
       SELECT ELEMENT [
-      (
-        SELECT ELEMENT [
-        FieldAccessor [
-          Variable [ Name=#1 ]
-          Field=gco
-        ]
-        ]
-        FROM [          Variable [ Name=$g ]
-          AS Variable [ Name=$g ]
-        ]
-      )
+      FieldAccessor [
+        Variable [ Name=#1 ]
+        Field=gco
+      ]
       ]
       FROM [        Variable [ Name=$g ]
         AS Variable [ Name=#1 ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q14_promotion_effect/q14_promotion_effect.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q14_promotion_effect/q14_promotion_effect.3.ast
index 05e22d1..9ac71e1 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q14_promotion_effect/q14_promotion_effect.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q14_promotion_effect/q14_promotion_effect.3.ast
@@ -24,7 +24,7 @@
             ]
             *
             OperatorExpr [
-              LiteralExpr [LONG] [1]
+              Variable [ Name=$t ]
               -
               FieldAccessor [
                 Variable [ Name=$i ]
@@ -39,12 +39,9 @@
       ]
       FROM [        (
           SELECT ELEMENT [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [lp]
+          FunctionCall asterix.field-access-by-name@2[
             Variable [ Name=$g ]
-            Variable [ Name=$l ]
-            Variable [ Name=$p ]
-            Variable [ Name=$t ]
+            LiteralExpr [STRING] [lp]
           ]
           ]
           FROM [            Variable [ Name=$g ]
@@ -66,7 +63,7 @@
         ]
         *
         OperatorExpr [
-          LiteralExpr [LONG] [1]
+          Variable [ Name=$t ]
           -
           FieldAccessor [
             Variable [ Name=$i ]
@@ -77,12 +74,9 @@
       ]
       FROM [        (
           SELECT ELEMENT [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [lp]
+          FunctionCall asterix.field-access-by-name@2[
             Variable [ Name=$g ]
-            Variable [ Name=$l ]
-            Variable [ Name=$p ]
-            Variable [ Name=$t ]
+            LiteralExpr [STRING] [lp]
           ]
           ]
           FROM [            Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q16_parts_supplier_relationship/q16_parts_supplier_relationship.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q16_parts_supplier_relationship/q16_parts_supplier_relationship.3.ast
index a6d19ba..94cd5e4 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q16_parts_supplier_relationship/q16_parts_supplier_relationship.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q16_parts_supplier_relationship/q16_parts_supplier_relationship.3.ast
@@ -341,12 +341,9 @@
       ]
       FROM [        (
           SELECT ELEMENT [
-          FunctionCall asterix.resolve@-1[
-            LiteralExpr [STRING] [t2]
+          FunctionCall asterix.field-access-by-name@2[
             Variable [ Name=$g ]
-            Variable [ Name=$p_brand ]
-            Variable [ Name=$p_size ]
-            Variable [ Name=$p_type ]
+            LiteralExpr [STRING] [t2]
           ]
           ]
           FROM [            Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q17_large_gby_variant/q17_large_gby_variant.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q17_large_gby_variant/q17_large_gby_variant.3.ast
index 25bc7f7..63834e1 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q17_large_gby_variant/q17_large_gby_variant.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q17_large_gby_variant/q17_large_gby_variant.3.ast
@@ -13,10 +13,9 @@
     FunctionCall asterix.count@1[
       (
         SELECT ELEMENT [
-        FunctionCall asterix.resolve@-1[
-          LiteralExpr [STRING] [l]
+        FunctionCall asterix.field-access-by-name@2[
           Variable [ Name=$g ]
-          Variable [ Name=$l_partkey ]
+          LiteralExpr [STRING] [l]
         ]
         ]
         FROM [          Variable [ Name=$g ]
@@ -41,10 +40,9 @@
           ]
           FROM [            (
               SELECT ELEMENT [
-              FunctionCall asterix.resolve@-1[
-                LiteralExpr [STRING] [l]
+              FunctionCall asterix.field-access-by-name@2[
                 Variable [ Name=$g ]
-                Variable [ Name=$l_partkey ]
+                LiteralExpr [STRING] [l]
               ]
               ]
               FROM [                Variable [ Name=$g ]
@@ -70,10 +68,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_partkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -98,10 +95,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_partkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -126,10 +122,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_partkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -154,10 +149,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_partkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -182,10 +176,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_partkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -210,10 +203,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_partkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -238,10 +230,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_partkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -266,10 +257,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_partkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -294,10 +284,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$l_partkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q18_large_volume_customer/q18_large_volume_customer.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q18_large_volume_customer/q18_large_volume_customer.3.ast
index 4446895..0ab8030 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q18_large_volume_customer/q18_large_volume_customer.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q18_large_volume_customer/q18_large_volume_customer.3.ast
@@ -40,14 +40,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [l]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$o_orderdate ]
-              Variable [ Name=$c_name ]
-              Variable [ Name=$o_orderkey ]
-              Variable [ Name=$o_totalprice ]
-              Variable [ Name=$c_custkey ]
+              LiteralExpr [STRING] [l]
             ]
             ]
             FROM [              Variable [ Name=$g ]
@@ -92,12 +87,9 @@
             ]
             FROM [              (
                 SELECT ELEMENT [
-                FunctionCall asterix.resolve@-1[
-                  LiteralExpr [STRING] [l]
-                  Variable [ Name=$o ]
-                  Variable [ Name=$l_orderkey ]
+                FunctionCall asterix.field-access-by-name@2[
                   Variable [ Name=$g2 ]
-                  Variable [ Name=$c ]
+                  LiteralExpr [STRING] [l]
                 ]
                 ]
                 FROM [                  Variable [ Name=$g2 ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q20_potential_part_promotion/q20_potential_part_promotion.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q20_potential_part_promotion/q20_potential_part_promotion.3.ast
index 9ef07b1..41802c2 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q20_potential_part_promotion/q20_potential_part_promotion.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q20_potential_part_promotion/q20_potential_part_promotion.3.ast
@@ -62,11 +62,9 @@
                   ]
                   FROM [                    (
                       SELECT ELEMENT [
-                      FunctionCall asterix.resolve@-1[
-                        LiteralExpr [STRING] [l]
-                        Variable [ Name=$l_suppkey ]
+                      FunctionCall asterix.field-access-by-name@2[
                         Variable [ Name=$g ]
-                        Variable [ Name=$l_partkey ]
+                        LiteralExpr [STRING] [l]
                       ]
                       ]
                       FROM [                        Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.ast
index 62cbc19..b91a2a9 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q21_suppliers_who_kept_orders_waiting/q21_suppliers_who_kept_orders_waiting.3.ast
@@ -481,23 +481,16 @@
 
 Let Variable [ Name=$numwait ]
   :=
-  FunctionCall asterix.sql-count@1[
+  FunctionCall asterix.count@1[
     (
       SELECT ELEMENT [
-      (
-        SELECT ELEMENT [
-        FieldAccessor [
-          Variable [ Name=#1 ]
-          Field=t4
-        ]
-        ]
-        FROM [          Variable [ Name=$g ]
-          AS Variable [ Name=$g ]
-        ]
-      )
+      FunctionCall asterix.field-access-by-name@2[
+        Variable [ Name=$g ]
+        LiteralExpr [STRING] [t4]
+      ]
       ]
       FROM [        Variable [ Name=$g ]
-        AS Variable [ Name=#1 ]
+        AS Variable [ Name=$g ]
       ]
     )
   ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q22_global_sales_opportunity/q22_global_sales_opportunity.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q22_global_sales_opportunity/q22_global_sales_opportunity.3.ast
index ffd3d1c..adeab44 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q22_global_sales_opportunity/q22_global_sales_opportunity.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/q22_global_sales_opportunity/q22_global_sales_opportunity.3.ast
@@ -79,10 +79,9 @@
     FunctionCall asterix.count@1[
       (
         SELECT ELEMENT [
-        FunctionCall asterix.resolve@-1[
-          LiteralExpr [STRING] [ct]
+        FunctionCall asterix.field-access-by-name@2[
           Variable [ Name=$g ]
-          Variable [ Name=$cntrycode ]
+          LiteralExpr [STRING] [ct]
         ]
         ]
         FROM [          Variable [ Name=$g ]
@@ -104,10 +103,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [ct]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$cntrycode ]
+              LiteralExpr [STRING] [ct]
             ]
             ]
             FROM [              Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/query-issue562/query-issue562.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/query-issue562/query-issue562.3.ast
index bbca35e..80ab8ce 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/query-issue562/query-issue562.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/query-issue562/query-issue562.3.ast
@@ -206,10 +206,9 @@
         ]
         FROM [          (
             SELECT ELEMENT [
-            FunctionCall asterix.resolve@-1[
-              LiteralExpr [STRING] [ct]
+            FunctionCall asterix.field-access-by-name@2[
               Variable [ Name=$g ]
-              Variable [ Name=$cntrycode ]
+              LiteralExpr [STRING] [ct]
             ]
             ]
             FROM [              Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/query-issue601/query-issue601.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/query-issue601/query-issue601.3.ast
index f1705b8..2c32932 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/query-issue601/query-issue601.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/query-issue601/query-issue601.3.ast
@@ -5,32 +5,18 @@
   (
     LiteralExpr [STRING] [l_linenumber]
     :
-    FieldAccessor [
-      FunctionCall asterix.resolve@-1[
-        LiteralExpr [STRING] [l]
-        Variable [ Name=$g ]
-        Variable [ Name=$l_linenumber ]
-      ]
-      Field=l_linenumber
-    ]
+    Variable [ Name=$l_linenumber ]
   )
   (
     LiteralExpr [STRING] [count_order]
     :
-    FunctionCall asterix.sql-count@1[
+    FunctionCall asterix.count@1[
       (
         SELECT ELEMENT [
-        (
-          SELECT ELEMENT [
-          Variable [ Name=$g ]
-          ]
-          FROM [            Variable [ Name=$g ]
-            AS Variable [ Name=$g ]
-          ]
-        )
+        Variable [ Name=$g ]
         ]
         FROM [          Variable [ Name=$g ]
-          AS Variable [ Name=#1 ]
+          AS Variable [ Name=$g ]
         ]
       )
     ]
@@ -55,13 +41,6 @@
   )
 
 Orderby
-  FieldAccessor [
-    FunctionCall asterix.resolve@-1[
-      LiteralExpr [STRING] [l]
-      Variable [ Name=$g ]
-      Variable [ Name=$l_linenumber ]
-    ]
-    Field=l_linenumber
-  ]
+  Variable [ Name=$l_linenumber ]
   ASC
 
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/query-issue810-3/query-issue810-3.3.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/query-issue810-3/query-issue810-3.3.ast
index ffae08a..6e101a7 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/query-issue810-3/query-issue810-3.3.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/tpch/query-issue810-3/query-issue810-3.3.ast
@@ -85,11 +85,9 @@
     ]
     FROM [      (
         SELECT ELEMENT [
-        FunctionCall asterix.resolve@-1[
-          LiteralExpr [STRING] [l]
+        FunctionCall asterix.field-access-by-name@2[
           Variable [ Name=$g ]
-          Variable [ Name=$l_linestatus ]
-          Variable [ Name=$l_returnflag ]
+          LiteralExpr [STRING] [l]
         ]
         ]
         FROM [          Variable [ Name=$g ]
@@ -116,12 +114,9 @@
     ]
     FROM [      (
         SELECT ELEMENT [
-        FunctionCall asterix.resolve@-1[
-          LiteralExpr [STRING] [l]
-          Variable [ Name=$expensives ]
+        FunctionCall asterix.field-access-by-name@2[
           Variable [ Name=$g ]
-          Variable [ Name=$l_linestatus ]
-          Variable [ Name=$l_returnflag ]
+          LiteralExpr [STRING] [l]
         ]
         ]
         FROM [          Variable [ Name=$g ]
@@ -171,13 +166,9 @@
     ]
     FROM [      (
         SELECT ELEMENT [
-        FunctionCall asterix.resolve@-1[
-          LiteralExpr [STRING] [l]
-          Variable [ Name=$expensives ]
+        FunctionCall asterix.field-access-by-name@2[
           Variable [ Name=$g ]
-          Variable [ Name=$l_linestatus ]
-          Variable [ Name=$l_returnflag ]
-          Variable [ Name=$cheaps ]
+          LiteralExpr [STRING] [l]
         ]
         ]
         FROM [          Variable [ Name=$g ]
@@ -209,14 +200,9 @@
     ]
     FROM [      (
         SELECT ELEMENT [
-        FunctionCall asterix.resolve@-1[
-          LiteralExpr [STRING] [l]
-          Variable [ Name=$expensives ]
+        FunctionCall asterix.field-access-by-name@2[
           Variable [ Name=$g ]
-          Variable [ Name=$l_linestatus ]
-          Variable [ Name=$l_returnflag ]
-          Variable [ Name=$charges ]
-          Variable [ Name=$cheaps ]
+          LiteralExpr [STRING] [l]
         ]
         ]
         FROM [          Variable [ Name=$g ]
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/user-defined-functions/udf30/udf30.1.ast b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/user-defined-functions/udf30/udf30.1.ast
index 646fafc..b787d0d 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/user-defined-functions/udf30/udf30.1.ast
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results_parser_sqlpp/user-defined-functions/udf30/udf30.1.ast
@@ -5,7 +5,7 @@
 Query:
 Let Variable [ Name=$z ]
   :=
-  FunctionCall asterix.resolve@-1[
+  FunctionCall asterix.dataset@1[
     LiteralExpr [STRING] [y]
   ]
 SELECT ELEMENT [
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/testsuite_sqlpp.xml b/asterixdb/asterix-app/src/test/resources/runtimets/testsuite_sqlpp.xml
index bc919db..0c6493d 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/testsuite_sqlpp.xml
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/testsuite_sqlpp.xml
@@ -2787,7 +2787,7 @@
     <test-case FilePath="global-aggregate">
       <compilation-unit name="q05_error">
         <output-dir compare="Text">q01</output-dir>
-        <expected-error>Cannot find dataset u in dataverse TinySocial nor an alias with name u</expected-error>
+        <expected-error>Type mismatch: function field-access-by-name expects its 1st input parameter to be type object, but the actual input type is array</expected-error>
       </compilation-unit>
     </test-case>
     <test-case FilePath="global-aggregate">
@@ -3579,7 +3579,6 @@
     <test-case FilePath="misc">
       <compilation-unit name="query-ASTERIXDB-1577">
         <output-dir compare="Text">query-ASTERIXDB-1577</output-dir>
-        <expected-error>Type mismatch: function field-access-by-name expects its 1st input parameter to be type object, but the actual input type is array</expected-error>
       </compilation-unit>
     </test-case>
     <test-case FilePath="misc">
@@ -5403,6 +5402,16 @@
         <output-dir compare="Text">fullyqualified2</output-dir>
       </compilation-unit>
     </test-case>
+    <test-case FilePath="resolution">
+      <compilation-unit name="order_1">
+        <output-dir compare="Text">order_1</output-dir>
+      </compilation-unit>
+    </test-case>
+    <test-case FilePath="resolution">
+      <compilation-unit name="groupby_rename_with_sugar">
+        <output-dir compare="Text">groupby_rename_with_sugar</output-dir>
+      </compilation-unit>
+    </test-case>
   </test-group>
   <test-group name="scan">
     <test-case FilePath="scan">
@@ -6437,7 +6446,6 @@
     <test-case FilePath="subquery">
       <compilation-unit name="query-ASTERIXDB-1574-3">
         <output-dir compare="Text">query-ASTERIXDB-1574</output-dir>
-        <expected-error>Cannot resolve ambiguous alias reference for undefined identifier</expected-error>
       </compilation-unit>
     </test-case>
     <test-case FilePath="subquery">
@@ -9061,12 +9069,6 @@
       </compilation-unit>
     </test-case>
     <test-case FilePath="union">
-      <compilation-unit name="union_negative_2">
-        <output-dir compare="Text">union</output-dir>
-        <expected-error>Cannot find dataset t in dataverse TinySocial nor an alias with name t</expected-error>
-      </compilation-unit>
-    </test-case>
-    <test-case FilePath="union">
       <compilation-unit name="union_negative_3">
         <output-dir compare="Text">union</output-dir>
         <expected-error>Operation UNION with set semantics is not supported.</expected-error>
@@ -9093,6 +9095,11 @@
       </compilation-unit>
     </test-case>
     <test-case FilePath="union">
+      <compilation-unit name="union_orderby_5">
+        <output-dir compare="Text">union_orderby_5</output-dir>
+      </compilation-unit>
+    </test-case>
+    <test-case FilePath="union">
       <compilation-unit name="query-ASTERIXDB-1354-2">
         <output-dir compare="Text">query-ASTERIXDB-1354-2</output-dir>
       </compilation-unit>
diff --git a/asterixdb/asterix-lang-common/pom.xml b/asterixdb/asterix-lang-common/pom.xml
index 0ee5030..a163e54 100644
--- a/asterixdb/asterix-lang-common/pom.xml
+++ b/asterixdb/asterix-lang-common/pom.xml
@@ -91,6 +91,10 @@
       <artifactId>commons-lang</artifactId>
     </dependency>
     <dependency>
+      <groupId>org.apache.commons</groupId>
+      <artifactId>commons-collections4</artifactId>
+    </dependency>
+    <dependency>
       <groupId>org.apache.hyracks</groupId>
       <artifactId>algebricks-core</artifactId>
     </dependency>
diff --git a/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/base/IReturningStatement.java b/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/base/IReturningStatement.java
index 02e5267..d31b765 100644
--- a/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/base/IReturningStatement.java
+++ b/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/base/IReturningStatement.java
@@ -19,6 +19,8 @@
 
 package org.apache.asterix.lang.common.base;
 
+import org.apache.asterix.lang.common.struct.VarIdentifier;
+
 import java.util.List;
 
 /**
@@ -64,4 +66,16 @@
      *            the main body expression.
      */
     void setBody(Expression expr);
+
+    /**
+     * @return external (pre-defined) variables for the statement
+     */
+    List<VarIdentifier> getExternalVars();
+
+    /**
+     * Sets external (pre-defined) variables for the statement
+     *
+     * @param externalVars external variables
+     */
+    void setExternalVars(List<VarIdentifier> externalVars);
 }
diff --git a/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/context/Scope.java b/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/context/Scope.java
index ad277d3..df6d3a5 100644
--- a/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/context/Scope.java
+++ b/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/context/Scope.java
@@ -18,40 +18,39 @@
  */
 package org.apache.asterix.lang.common.context;
 
-import java.util.HashMap;
-import java.util.HashSet;
+import java.util.ArrayList;
 import java.util.Iterator;
-import java.util.Map;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
 import java.util.Set;
 
 import org.apache.asterix.common.functions.FunctionSignature;
-import org.apache.asterix.lang.common.base.Expression;
 import org.apache.asterix.lang.common.expression.VariableExpr;
 import org.apache.asterix.lang.common.parser.ScopeChecker;
-import org.apache.asterix.lang.common.rewrites.VariableSubstitutionEnvironment;
 import org.apache.asterix.lang.common.struct.Identifier;
 import org.apache.asterix.lang.common.struct.VarIdentifier;
+import org.apache.commons.collections4.iterators.ReverseListIterator;
 
 public final class Scope {
-    private Scope parent;
-    private Map<String, Identifier> symbols = new HashMap<String, Identifier>();
-    private Map<String, Expression> varExprMap = new HashMap<String, Expression>();
-    private FunctionSignatures functionSignatures = null;
     private final ScopeChecker scopeChecker;
-    private boolean maskParentScope = false;
-
-    public Scope(ScopeChecker scopeChecker, Scope parent) {
-        this.scopeChecker = scopeChecker;
-        this.parent = parent;
-    }
+    private final Scope parent;
+    private final LinkedHashMap<String, Identifier> symbols;
+    private final boolean maskParentScope;
+    private FunctionSignatures functionSignatures;
 
     public Scope(ScopeChecker scopeChecker) {
         this(scopeChecker, null);
     }
 
+    public Scope(ScopeChecker scopeChecker, Scope parent) {
+        this(scopeChecker, parent, false);
+    }
+
     public Scope(ScopeChecker scopeChecker, Scope parent, boolean maskParentScope) {
-        this(scopeChecker, parent);
+        this.scopeChecker = scopeChecker;
+        this.parent = parent;
         this.maskParentScope = maskParentScope;
+        this.symbols = new LinkedHashMap<>();
     }
 
     /**
@@ -81,36 +80,6 @@
         symbols.put(ident.getValue(), ident);
     }
 
-    /**
-     * Add a symbol and its definition expression into the scope
-     *
-     * @param ident
-     */
-    public void addSymbolExpressionMappingToScope(VariableExpr ident, Expression expr) {
-        varExprMap.put(ident.getVar().getValue(), expr);
-    }
-
-    /**
-     * Remove a symbol and its definition expression into the scope
-     *
-     * @param ident
-     */
-    public Expression removeSymbolExpressionMapping(VariableExpr ident) {
-        if (ident == null) {
-            return null;
-        }
-        return varExprMap.remove(ident.getVar().getValue());
-    }
-
-    /**
-     * @return the variable substituion environment for inlining variable references by its original
-     */
-    public VariableSubstitutionEnvironment getVarSubstitutionEnvironment() {
-        VariableSubstitutionEnvironment env = new VariableSubstitutionEnvironment();
-        env.addMappings(varExprMap);
-        return env;
-    }
-
     public void addNewVarSymbolToScope(VarIdentifier ident) {
         scopeChecker.incVarCounter();
         ident.setId(scopeChecker.getVarCounter());
@@ -120,8 +89,8 @@
     /**
      * Add a FunctionDescriptor into functionSignatures
      *
-     * @param fd
-     *            FunctionDescriptor
+     * @param signature
+     *            FunctionSignature
      * @param varargs
      *            whether this function has varargs
      */
@@ -163,7 +132,6 @@
         if (functionSignatures != null && scope.functionSignatures != null) {
             functionSignatures.addAll(scope.functionSignatures);
         }
-        varExprMap.putAll(scope.varExprMap);
     }
 
     /**
@@ -171,16 +139,17 @@
      *
      * @return an iterator of visible symbols.
      */
-    public Iterator<Identifier> liveSymbols() {
-        final Iterator<Identifier> identifierIterator = symbols.values().iterator();
-        final Iterator<Identifier> parentIterator = parent == null ? null : parent.liveSymbols();
+    public Iterator<Identifier> liveSymbols(Scope stopAtExclusive) {
+        final Iterator<Identifier> identifierIterator = new ReverseListIterator<>(new ArrayList<>(symbols.values()));
+        final Iterator<Identifier> parentIterator =
+                parent == null || parent == stopAtExclusive ? null : parent.liveSymbols(stopAtExclusive);
         return new Iterator<Identifier>() {
             private Identifier currentSymbol = null;
 
             @Override
             public boolean hasNext() {
                 currentSymbol = null;
-                if (identifierIterator != null && identifierIterator.hasNext()) {
+                if (identifierIterator.hasNext()) {
                     currentSymbol = identifierIterator.next();
                 } else if (!maskParentScope && parentIterator != null && parentIterator.hasNext()) {
                     do {
@@ -214,8 +183,12 @@
     }
 
     public Set<VariableExpr> getLiveVariables() {
-        Set<VariableExpr> vars = new HashSet<VariableExpr>();
-        Iterator<Identifier> identifierIterator = liveSymbols();
+        return getLiveVariables(null);
+    }
+
+    public Set<VariableExpr> getLiveVariables(Scope stopAtExclusive) {
+        LinkedHashSet<VariableExpr> vars = new LinkedHashSet<>();
+        Iterator<Identifier> identifierIterator = liveSymbols(stopAtExclusive);
         while (identifierIterator.hasNext()) {
             Identifier identifier = identifierIterator.next();
             if (identifier instanceof VarIdentifier) {
diff --git a/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/expression/OperatorExpr.java b/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/expression/OperatorExpr.java
index 5cc759c..90b457e 100644
--- a/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/expression/OperatorExpr.java
+++ b/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/expression/OperatorExpr.java
@@ -98,7 +98,7 @@
         addOperator(op);
     }
 
-    public void addOperator(OperatorType op) throws CompilationException {
+    public void addOperator(OperatorType op) {
         if (op == null) {
             throw new NullPointerException();
         }
diff --git a/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/parser/ScopeChecker.java b/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/parser/ScopeChecker.java
index 771ae16..7dadd67 100644
--- a/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/parser/ScopeChecker.java
+++ b/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/parser/ScopeChecker.java
@@ -60,8 +60,7 @@
      * @return new scope
      */
     public final Scope createNewScope() {
-        Scope parent = scopeStack.peek();
-        Scope scope = new Scope(this, parent);// top one as parent
+        Scope scope = extendCurrentScopeNoPush(false);
         scopeStack.push(scope);
         return scope;
     }
@@ -72,20 +71,14 @@
      * @return
      */
     public final Scope extendCurrentScope() {
-        return extendCurrentScope(false);
-    }
-
-    public final Scope extendCurrentScope(boolean maskParentScope) {
-        Scope scope = extendCurrentScopeNoPush(maskParentScope);
-        scopeStack.pop();
-        scopeStack.push(scope);
+        Scope scope = extendCurrentScopeNoPush(false);
+        replaceCurrentScope(scope);
         return scope;
     }
 
-    public final Scope extendCurrentScopeNoPush(boolean maskParentScope) {
-        Scope scope = scopeStack.peek();
-        scope = new Scope(this, scope, maskParentScope);
-        return scope;
+    protected final Scope extendCurrentScopeNoPush(boolean maskParentScope) {
+        Scope parent = scopeStack.peek();
+        return new Scope(this, parent, maskParentScope);
     }
 
     public final void replaceCurrentScope(Scope scope) {
@@ -116,6 +109,15 @@
     }
 
     /**
+     * get scope preceding the current scope
+     * @return preceding scope or {@code null} if current scope is the top one
+     */
+    public final Scope getPrecedingScope() {
+        int n = scopeStack.size();
+        return n > 1 ? scopeStack.get(n - 2) : null;
+    }
+
+    /**
      * find symbol in the scope
      *
      * @return identifier
diff --git a/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/statement/InsertStatement.java b/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/statement/InsertStatement.java
index 4cc2001..797f48a 100644
--- a/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/statement/InsertStatement.java
+++ b/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/statement/InsertStatement.java
@@ -28,6 +28,7 @@
 import org.apache.asterix.lang.common.base.Statement;
 import org.apache.asterix.lang.common.expression.VariableExpr;
 import org.apache.asterix.lang.common.struct.Identifier;
+import org.apache.asterix.lang.common.struct.VarIdentifier;
 import org.apache.asterix.lang.common.visitor.base.ILangVisitor;
 
 public class InsertStatement implements IReturningStatement {
@@ -114,6 +115,16 @@
     }
 
     @Override
+    public List<VarIdentifier> getExternalVars() {
+        return null;
+    }
+
+    @Override
+    public void setExternalVars(List<VarIdentifier> externalVars) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
     public <R, T> R accept(ILangVisitor<R, T> visitor, T arg) throws CompilationException {
         return visitor.visit(this, arg);
     }
diff --git a/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/statement/Query.java b/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/statement/Query.java
index 66a55dc..8dc7b87 100644
--- a/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/statement/Query.java
+++ b/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/statement/Query.java
@@ -26,12 +26,14 @@
 import org.apache.asterix.lang.common.base.Expression;
 import org.apache.asterix.lang.common.base.IReturningStatement;
 import org.apache.asterix.lang.common.base.Statement;
+import org.apache.asterix.lang.common.struct.VarIdentifier;
 import org.apache.asterix.lang.common.visitor.base.ILangVisitor;
 
 public class Query implements IReturningStatement {
     private final boolean explain;
     private boolean topLevel = true;
     private Expression body;
+    private List<VarIdentifier> externalVars;
     private int varCounter;
 
     public Query(boolean explain) {
@@ -39,10 +41,16 @@
     }
 
     public Query(boolean explain, boolean topLevel, Expression body, int varCounter) {
+        this(explain, topLevel, body, varCounter, null);
+    }
+
+    public Query(boolean explain, boolean topLevel, Expression body, int varCounter,
+            List<VarIdentifier> externalVars) {
         this.explain = explain;
         this.topLevel = topLevel;
         this.body = body;
         this.varCounter = varCounter;
+        this.externalVars = externalVars;
     }
 
     @Override
@@ -79,6 +87,16 @@
         return topLevel;
     }
 
+    @Override
+    public List<VarIdentifier> getExternalVars() {
+        return externalVars;
+    }
+
+    @Override
+    public void setExternalVars(List<VarIdentifier> externalVars) {
+        this.externalVars = externalVars;
+    }
+
     public boolean isExplain() {
         return explain;
     }
diff --git a/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/struct/VarIdentifier.java b/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/struct/VarIdentifier.java
index 091c82d..587dd1c 100644
--- a/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/struct/VarIdentifier.java
+++ b/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/struct/VarIdentifier.java
@@ -22,14 +22,12 @@
 
 public final class VarIdentifier extends Identifier {
     private int id = 0;
-    private boolean namedValueAccess = false;
 
     public VarIdentifier() {
-        super();
     }
 
     public VarIdentifier(VarIdentifier v) {
-        this(v.getValue(), v.getId(), v.namedValueAccess());
+        this(v.getValue(), v.getId());
     }
 
     public VarIdentifier(String value) {
@@ -37,14 +35,8 @@
     }
 
     public VarIdentifier(String value, int id) {
-        this(value, id, false);
-    }
-
-    private VarIdentifier(String value, int id, boolean namedValueAccess) {
-        super();
         this.value = value;
         this.id = id;
-        this.namedValueAccess = namedValueAccess;
     }
 
     public void setId(int id) {
@@ -57,17 +49,7 @@
 
     @Override
     public VarIdentifier clone() {
-        VarIdentifier vi = new VarIdentifier(this.value);
-        vi.setId(this.id);
-        return vi;
-    }
-
-    public void setNamedValueAccess(boolean namedValueAccess) {
-        this.namedValueAccess = namedValueAccess;
-    }
-
-    public boolean namedValueAccess() {
-        return namedValueAccess;
+        return new VarIdentifier(value, id);
     }
 
     @Override
diff --git a/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/visitor/AbstractInlineUdfsVisitor.java b/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/visitor/AbstractInlineUdfsVisitor.java
index 858a8c2..61617ec 100644
--- a/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/visitor/AbstractInlineUdfsVisitor.java
+++ b/asterixdb/asterix-lang-common/src/main/java/org/apache/asterix/lang/common/visitor/AbstractInlineUdfsVisitor.java
@@ -274,7 +274,7 @@
         } else {
             // Rewrite the function body itself (without setting unbounded variables to dataset access).
             // TODO(buyingyi): throw an exception for recursive function definition or limit the stack depth.
-            implem.setFuncBody(rewriteFunctionBody(implem.getFuncBody()));
+            implem.setFuncBody(rewriteFunctionBody(implem.getFuncBody(), implem.getParamList()));
             // it's one of the functions we want to inline
             List<LetClause> clauses = new ArrayList<>();
             Iterator<VarIdentifier> paramIter = implem.getParamList().iterator();
@@ -321,10 +321,13 @@
         return new Pair<>(changed, newList);
     }
 
-    protected Expression rewriteFunctionBody(Expression expr) throws CompilationException {
+    protected Expression rewriteFunctionBody(Expression expr, List<VarIdentifier> paramList)
+            throws CompilationException {
         Query wrappedQuery = new Query(false);
         wrappedQuery.setBody(expr);
         wrappedQuery.setTopLevel(false);
+        wrappedQuery.setExternalVars(paramList);
+
         IQueryRewriter queryRewriter = rewriterFactory.createQueryRewriter();
         queryRewriter.rewrite(declaredFunctions, wrappedQuery, metadataProvider, context);
         return wrappedQuery.getBody();
diff --git a/asterixdb/asterix-lang-sqlpp/pom.xml b/asterixdb/asterix-lang-sqlpp/pom.xml
index 6b19fc7..46c0c4a 100644
--- a/asterixdb/asterix-lang-sqlpp/pom.xml
+++ b/asterixdb/asterix-lang-sqlpp/pom.xml
@@ -162,6 +162,10 @@
       <artifactId>algebricks-core</artifactId>
     </dependency>
     <dependency>
+      <groupId>org.apache.commons</groupId>
+      <artifactId>commons-lang3</artifactId>
+    </dependency>
+    <dependency>
       <groupId>junit</groupId>
       <artifactId>junit</artifactId>
       <scope>test</scope>
diff --git a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/SqlppFunctionBodyRewriter.java b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/SqlppFunctionBodyRewriter.java
index fbf64f7..a8b3dc6 100644
--- a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/SqlppFunctionBodyRewriter.java
+++ b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/SqlppFunctionBodyRewriter.java
@@ -44,25 +44,24 @@
         // Substitutes group-by key expressions.
         substituteGroupbyKeyExpression();
 
-        // Rewrites SQL-92 global aggregations.
-        rewriteGlobalAggregations();
-
-        // Group-by core/sugar rewrites.
+        // Group-by core rewrites
         rewriteGroupBys();
 
         // Rewrites set operations.
         rewriteSetOperations();
 
+        // Generate ids for variables (considering scopes) and replace global variable access with the dataset function.
+        variableCheckAndRewrite();
+
+        // Rewrites SQL-92 global aggregations.
+        rewriteGroupByAggregationSugar();
+
         // Rewrites like/not-like expressions.
         rewriteOperatorExpression();
 
         // Rewrites several variable-arg functions into their corresponding internal list-input functions.
         rewriteListInputFunctions();
 
-        // Generates ids for variables (considering scopes) but DOES NOT replace unbounded variable access with the dataset function.
-        // An unbounded variable within a function could be a bounded variable in the top-level query.
-        variableCheckAndRewrite(false);
-
         // Inlines functions recursively.
         inlineDeclaredUdfs();
     }
diff --git a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/SqlppQueryRewriter.java b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/SqlppQueryRewriter.java
index a2de694..3e9a873 100644
--- a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/SqlppQueryRewriter.java
+++ b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/SqlppQueryRewriter.java
@@ -56,7 +56,7 @@
 import org.apache.asterix.lang.sqlpp.rewrites.visitor.SetOperationVisitor;
 import org.apache.asterix.lang.sqlpp.rewrites.visitor.SqlppBuiltinFunctionRewriteVisitor;
 import org.apache.asterix.lang.sqlpp.rewrites.visitor.SqlppDistinctAggregationSugarVisitor;
-import org.apache.asterix.lang.sqlpp.rewrites.visitor.SqlppGlobalAggregationSugarVisitor;
+import org.apache.asterix.lang.sqlpp.rewrites.visitor.SqlppGroupByAggregationSugarVisitor;
 import org.apache.asterix.lang.sqlpp.rewrites.visitor.SqlppGroupByVisitor;
 import org.apache.asterix.lang.sqlpp.rewrites.visitor.SqlppInlineUdfsVisitor;
 import org.apache.asterix.lang.sqlpp.rewrites.visitor.SqlppListInputFunctionRewriteVisitor;
@@ -90,8 +90,6 @@
         if (topStatement == null) {
             return;
         }
-        // Marks the current variable counter.
-        context.markCounter();
 
         // Sets up parameters.
         setup(declaredFunctions, topStatement, metadataProvider, context);
@@ -105,21 +103,21 @@
         // Substitutes group-by key expressions.
         substituteGroupbyKeyExpression();
 
-        // Rewrites SQL-92 global aggregations.
-        rewriteGlobalAggregations();
-
-        // Group-by core/sugar rewrites.
+        // Group-by core rewrites
         rewriteGroupBys();
 
         // Rewrites set operations.
         rewriteSetOperations();
 
+        // Generate ids for variables (considering scopes) and replace global variable access with the dataset function.
+        variableCheckAndRewrite();
+
+        // Rewrites SQL-92 aggregate functions
+        rewriteGroupByAggregationSugar();
+
         // Rewrites like/not-like expressions.
         rewriteOperatorExpression();
 
-        // Generate ids for variables (considering scopes) and replace global variable access with the dataset function.
-        variableCheckAndRewrite(true);
-
         // Inlines WITH expressions after variableCheckAndRewrite(...) so that the variable scoping for WITH
         // expression is correct.
         inlineWithExpressions();
@@ -138,21 +136,13 @@
         // Rewrites distinct aggregates into regular aggregates
         rewriteDistinctAggregations();
 
-        // Resets the variable counter to the previous marked value.
-        // Therefore, the variable ids in the final query plans will not be perturbed
-        // by the additon or removal of intermediate AST rewrites.
-        context.resetCounter();
-
-        // Replace global variable access with the dataset function for inlined expressions.
-        variableCheckAndRewrite(true);
-
         // Sets the var counter of the query.
         topStatement.setVarCounter(context.getVarCounter());
     }
 
-    protected void rewriteGlobalAggregations() throws CompilationException {
-        SqlppGlobalAggregationSugarVisitor globalAggregationVisitor = new SqlppGlobalAggregationSugarVisitor();
-        topExpr.accept(globalAggregationVisitor, null);
+    protected void rewriteGroupByAggregationSugar() throws CompilationException {
+        SqlppGroupByAggregationSugarVisitor visitor = new SqlppGroupByAggregationSugarVisitor(context);
+        topExpr.accept(visitor, null);
     }
 
     protected void rewriteDistinctAggregations() throws CompilationException {
@@ -212,9 +202,9 @@
         topExpr.accept(inlineColumnAliasVisitor, null);
     }
 
-    protected void variableCheckAndRewrite(boolean overwrite) throws CompilationException {
+    protected void variableCheckAndRewrite() throws CompilationException {
         VariableCheckAndRewriteVisitor variableCheckAndRewriteVisitor =
-                new VariableCheckAndRewriteVisitor(context, overwrite, metadataProvider);
+                new VariableCheckAndRewriteVisitor(context, metadataProvider, topExpr.getExternalVars());
         topExpr.accept(variableCheckAndRewriteVisitor, null);
     }
 
diff --git a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/visitor/SqlppGlobalAggregationSugarVisitor.java b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/visitor/SqlppGlobalAggregationSugarVisitor.java
deleted file mode 100644
index 16ae05c..0000000
--- a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/visitor/SqlppGlobalAggregationSugarVisitor.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.asterix.lang.sqlpp.rewrites.visitor;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import org.apache.asterix.common.exceptions.CompilationException;
-import org.apache.asterix.lang.common.base.Expression;
-import org.apache.asterix.lang.common.base.ILangExpression;
-import org.apache.asterix.lang.common.clause.GroupbyClause;
-import org.apache.asterix.lang.common.expression.GbyVariableExpressionPair;
-import org.apache.asterix.lang.sqlpp.clause.SelectBlock;
-import org.apache.asterix.lang.sqlpp.clause.SelectClause;
-import org.apache.asterix.lang.sqlpp.visitor.CheckSql92AggregateVisitor;
-import org.apache.asterix.lang.sqlpp.visitor.base.AbstractSqlppSimpleExpressionVisitor;
-
-public class SqlppGlobalAggregationSugarVisitor extends AbstractSqlppSimpleExpressionVisitor {
-
-    @Override
-    public Expression visit(SelectBlock selectBlock, ILangExpression arg) throws CompilationException {
-        SelectClause selectClause = selectBlock.getSelectClause();
-        if (!selectBlock.hasGroupbyClause() && selectBlock.hasFromClause()) {
-            boolean addImplicitGby;
-            if (selectClause.selectRegular()) {
-                addImplicitGby = isSql92Aggregate(selectClause.getSelectRegular(), selectBlock);
-            } else {
-                addImplicitGby = isSql92Aggregate(selectClause.getSelectElement(), selectBlock);
-            }
-            if (addImplicitGby) {
-                // Adds an implicit group-by clause for SQL-92 global aggregate.
-                List<GbyVariableExpressionPair> gbyPairList = new ArrayList<>();
-                List<GbyVariableExpressionPair> decorPairList = new ArrayList<>();
-                GroupbyClause gbyClause = new GroupbyClause(gbyPairList, decorPairList, new HashMap<>(), null, null,
-                        false, true);
-                selectBlock.setGroupbyClause(gbyClause);
-            }
-        }
-        return super.visit(selectBlock, arg);
-    }
-
-    private boolean isSql92Aggregate(ILangExpression expr, SelectBlock selectBlock) throws CompilationException {
-        CheckSql92AggregateVisitor visitor = new CheckSql92AggregateVisitor();
-        return expr.accept(visitor, selectBlock);
-    }
-}
diff --git a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/visitor/SqlppGroupByAggregationSugarVisitor.java b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/visitor/SqlppGroupByAggregationSugarVisitor.java
new file mode 100644
index 0000000..6f420b4
--- /dev/null
+++ b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/visitor/SqlppGroupByAggregationSugarVisitor.java
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.asterix.lang.sqlpp.rewrites.visitor;
+
+import org.apache.asterix.common.exceptions.CompilationException;
+import org.apache.asterix.common.functions.FunctionSignature;
+import org.apache.asterix.lang.common.base.Expression;
+import org.apache.asterix.lang.common.base.ILangExpression;
+import org.apache.asterix.lang.common.clause.GroupbyClause;
+import org.apache.asterix.lang.common.clause.LetClause;
+import org.apache.asterix.lang.common.clause.LimitClause;
+import org.apache.asterix.lang.common.clause.OrderbyClause;
+import org.apache.asterix.lang.common.expression.CallExpr;
+import org.apache.asterix.lang.common.expression.FieldAccessor;
+import org.apache.asterix.lang.common.expression.GbyVariableExpressionPair;
+import org.apache.asterix.lang.common.expression.VariableExpr;
+import org.apache.asterix.lang.common.rewrites.LangRewritingContext;
+import org.apache.asterix.lang.common.struct.Identifier;
+import org.apache.asterix.lang.common.struct.VarIdentifier;
+import org.apache.asterix.lang.sqlpp.clause.FromClause;
+import org.apache.asterix.lang.sqlpp.clause.FromTerm;
+import org.apache.asterix.lang.sqlpp.clause.HavingClause;
+import org.apache.asterix.lang.sqlpp.clause.SelectBlock;
+import org.apache.asterix.lang.sqlpp.clause.SelectClause;
+import org.apache.asterix.lang.sqlpp.clause.SelectElement;
+import org.apache.asterix.lang.sqlpp.clause.SelectSetOperation;
+import org.apache.asterix.lang.sqlpp.expression.SelectExpression;
+import org.apache.asterix.lang.sqlpp.struct.SetOperationInput;
+import org.apache.asterix.lang.sqlpp.util.FunctionMapUtil;
+import org.apache.asterix.lang.sqlpp.util.SqlppRewriteUtil;
+import org.apache.asterix.lang.sqlpp.util.SqlppVariableUtil;
+import org.apache.asterix.lang.sqlpp.visitor.base.AbstractSqlppExpressionScopingVisitor;
+import org.apache.asterix.lang.sqlpp.visitor.base.AbstractSqlppSimpleExpressionVisitor;
+import org.apache.hyracks.algebricks.common.utils.Pair;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * An AST pre-processor to rewrite group-by sugar queries, which does the following transformations:
+ * 1. Rewrite the argument expression of an aggregation function into a subquery
+ * 2. Turn a SQL-92 aggregate function into a SQL++ core aggregate function when performing 1.
+ * <p>
+ * <p>
+ * For example, this visitor turns the following query:
+ * <pre>
+ * FROM Employee e
+ * JOIN Incentive i ON e.job_category = i.job_category
+ * JOIN SuperStars s ON e.id = s.id
+ * GROUP BY e.department_id AS deptId
+ * GROUP AS eis(e AS e, i AS i, s AS s)
+ * SELECT deptId as deptId, SUM(e.salary + i.bonus) AS star_cost;
+ * </pre>
+ * into the following core-version query:
+ * <pre>
+ * FROM Employee e
+ * JOIN Incentive i ON e.job_category = i.job_category
+ * JOIN SuperStars s ON e.id = s.id
+ * GROUP BY e.department_id AS deptId
+ * GROUP AS eis(e AS e, i AS i, s AS s)
+ * SELECT ELEMENT {
+ *          'deptId': deptId,
+ *          'star_cost': array_sum( (FROM eis AS p SELECT ELEMENT p.e.salary + p.i.bonus) )
+ * };
+ * </pre>
+ * where <code>SUM(e.salary + i.bonus)</code>
+ * is turned into <code>array_sum( (FROM eis AS p SELECT ELEMENT p.e.salary + p.i.bonus) )</code>
+ */
+public class SqlppGroupByAggregationSugarVisitor extends AbstractSqlppExpressionScopingVisitor {
+
+    public SqlppGroupByAggregationSugarVisitor(LangRewritingContext context) {
+        super(context);
+    }
+
+    @Override
+    public Expression visit(SelectBlock selectBlock, ILangExpression arg) throws CompilationException {
+        // Traverses the select block in the order of "from", "let"s, "where",
+        // "group by", "let"s, "having" and "select".
+        FromClause fromClause = selectBlock.getFromClause();
+        if (selectBlock.hasFromClause()) {
+            fromClause.accept(this, arg);
+        }
+        if (selectBlock.hasLetClauses()) {
+            List<LetClause> letList = selectBlock.getLetList();
+            for (LetClause letClause : letList) {
+                letClause.accept(this, arg);
+            }
+        }
+        if (selectBlock.hasWhereClause()) {
+            selectBlock.getWhereClause().accept(this, arg);
+        }
+        if (selectBlock.hasGroupbyClause()) {
+            Set<VariableExpr> visibleVarsPreGroupByScope = scopeChecker.getCurrentScope().getLiveVariables();
+
+            GroupbyClause groupbyClause = selectBlock.getGroupbyClause();
+            groupbyClause.accept(this, arg);
+            Collection<VariableExpr> visibleVarsInCurrentScope = SqlppVariableUtil.getBindingVariables(groupbyClause);
+
+            VariableExpr groupVar = groupbyClause.getGroupVar();
+            Map<Expression, Identifier> groupFieldVars = getGroupFieldVariables(groupbyClause);
+
+            Collection<VariableExpr> freeVariablesInGbyLets = new HashSet<>();
+            if (selectBlock.hasLetClausesAfterGroupby()) {
+                List<LetClause> letListAfterGby = selectBlock.getLetListAfterGroupby();
+                for (LetClause letClauseAfterGby : letListAfterGby) {
+                    letClauseAfterGby.accept(this, arg);
+                    // Rewrites each let clause after the group-by.
+                    rewriteExpressionUsingGroupVariable(groupVar, groupFieldVars, letClauseAfterGby,
+                            visibleVarsPreGroupByScope);
+                    Collection<VariableExpr> freeVariablesInLet =
+                            SqlppVariableUtil.getFreeVariables(letClauseAfterGby.getBindingExpr());
+                    freeVariablesInLet.removeAll(visibleVarsInCurrentScope);
+                    freeVariablesInGbyLets.addAll(freeVariablesInLet);
+                    visibleVarsInCurrentScope.add(letClauseAfterGby.getVarExpr());
+                }
+            }
+
+            Collection<VariableExpr> freeVariables = new HashSet<>();
+            if (selectBlock.hasHavingClause()) {
+                // Rewrites the having clause.
+                HavingClause havingClause = selectBlock.getHavingClause();
+                havingClause.accept(this, arg);
+                rewriteExpressionUsingGroupVariable(groupVar, groupFieldVars, havingClause, visibleVarsPreGroupByScope);
+                freeVariables.addAll(SqlppVariableUtil.getFreeVariables(havingClause));
+            }
+
+            SelectExpression parentSelectExpression = (SelectExpression) arg;
+            // We cannot rewrite ORDER BY and LIMIT if it's a SET operation query.
+            if (!parentSelectExpression.getSelectSetOperation().hasRightInputs()) {
+                if (parentSelectExpression.hasOrderby()) {
+                    // Rewrites the ORDER BY clause.
+                    OrderbyClause orderbyClause = parentSelectExpression.getOrderbyClause();
+                    orderbyClause.accept(this, arg);
+                    rewriteExpressionUsingGroupVariable(groupVar, groupFieldVars, orderbyClause,
+                            visibleVarsPreGroupByScope);
+                    freeVariables.addAll(SqlppVariableUtil.getFreeVariables(orderbyClause));
+                }
+                if (parentSelectExpression.hasLimit()) {
+                    // Rewrites the LIMIT clause.
+                    LimitClause limitClause = parentSelectExpression.getLimitClause();
+                    limitClause.accept(this, arg);
+                    rewriteExpressionUsingGroupVariable(groupVar, groupFieldVars, limitClause,
+                            visibleVarsPreGroupByScope);
+                    freeVariables.addAll(SqlppVariableUtil.getFreeVariables(limitClause));
+                }
+            }
+
+            // Visits the select clause.
+            SelectClause selectClause = selectBlock.getSelectClause();
+            selectClause.accept(this, arg);
+            // Rewrites the select clause.
+            rewriteExpressionUsingGroupVariable(groupVar, groupFieldVars, selectClause, visibleVarsPreGroupByScope);
+            freeVariables.addAll(SqlppVariableUtil.getFreeVariables(selectClause));
+            freeVariables.removeAll(visibleVarsInCurrentScope);
+
+            // Gets the final free variables.
+            freeVariables.addAll(freeVariablesInGbyLets);
+
+            // Gets outer scope variables.
+            Collection<VariableExpr> decorVars = scopeChecker.getCurrentScope().getLiveVariables();
+            decorVars.removeAll(visibleVarsInCurrentScope);
+
+            // Only retains used free variables.
+            if (!decorVars.containsAll(freeVariables)) {
+                throw new IllegalStateException(decorVars + ":" + freeVariables);
+            }
+            decorVars.retainAll(freeVariables);
+
+            if (!decorVars.isEmpty()) {
+                // Adds necessary decoration variables for the GROUP BY.
+                // NOTE: we need to include outer binding variables so as they can be evaluated before
+                // the GROUP BY instead of being inlined as part of nested pipepline. The current optimzier
+                // is not able to optimize the latter case. The following query is such an example:
+                // asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/dapd/q2-11
+                List<GbyVariableExpressionPair> decorList = new ArrayList<>();
+                for (VariableExpr var : decorVars) {
+                    decorList.add(new GbyVariableExpressionPair((VariableExpr) SqlppRewriteUtil.deepCopy(var),
+                            (Expression) SqlppRewriteUtil.deepCopy(var)));
+                }
+                groupbyClause.getDecorPairList().addAll(decorList);
+            }
+        } else {
+            selectBlock.getSelectClause().accept(this, arg);
+        }
+        return null;
+    }
+
+    private Map<Expression, Identifier> getGroupFieldVariables(GroupbyClause groupbyClause) {
+        Map<Expression, Identifier> fieldVars = new HashMap<>();
+        for (Pair<Expression, Identifier> groupField : groupbyClause.getGroupFieldList()) {
+            fieldVars.put(groupField.first, groupField.second);
+        }
+        return fieldVars;
+    }
+
+    // Applying sugar rewriting for group-by.
+    private void rewriteExpressionUsingGroupVariable(VariableExpr groupVar, Map<Expression, Identifier> fieldVars,
+            ILangExpression expr, Set<VariableExpr> outerScopeVariables) throws CompilationException {
+        Sql92AggregateFunctionVisitor visitor =
+                new Sql92AggregateFunctionVisitor(groupVar, fieldVars, outerScopeVariables);
+        expr.accept(visitor, null);
+    }
+
+    private final class Sql92AggregateFunctionVisitor extends AbstractSqlppSimpleExpressionVisitor {
+
+        private final Expression groupVar;
+
+        private final Map<Expression, Identifier> fieldVars;
+
+        private final Collection<VariableExpr> outerVars;
+
+        private Sql92AggregateFunctionVisitor(Expression groupVar, Map<Expression, Identifier> fieldVars,
+                Collection<VariableExpr> outerVars) {
+            this.groupVar = groupVar;
+            this.fieldVars = fieldVars;
+            this.outerVars = outerVars;
+        }
+
+        @Override
+        public Expression visit(CallExpr callExpr, ILangExpression arg) throws CompilationException {
+            List<Expression> newExprList = new ArrayList<>();
+            FunctionSignature signature = callExpr.getFunctionSignature();
+            boolean aggregate = FunctionMapUtil.isSql92AggregateFunction(signature);
+            boolean rewritten = false;
+            for (Expression expr : callExpr.getExprList()) {
+                Expression newExpr = aggregate ? wrapAggregationArgument(expr) : expr;
+                rewritten |= newExpr != expr;
+                newExprList.add(newExpr.accept(this, arg));
+            }
+            if (rewritten) {
+                // Rewrites the SQL-92 function name to core functions,
+                // e.g., SUM --> array_sum
+                callExpr.setFunctionSignature(FunctionMapUtil.sql92ToCoreAggregateFunction(signature));
+            }
+            callExpr.setExprList(newExprList);
+            return callExpr;
+        }
+
+        private Expression wrapAggregationArgument(Expression argExpr) throws CompilationException {
+            Expression expr = argExpr;
+            Set<VariableExpr> freeVars = SqlppRewriteUtil.getFreeVariable(expr);
+
+            VariableExpr fromBindingVar = new VariableExpr(context.newVariable());
+            FromTerm fromTerm = new FromTerm(groupVar, fromBindingVar, null, null);
+            FromClause fromClause = new FromClause(Collections.singletonList(fromTerm));
+
+            // Maps field variable expressions to field accesses.
+            Map<Expression, Expression> varExprMap = new HashMap<>();
+            for (VariableExpr usedVar : freeVars) {
+                // Reference to a field in the group variable.
+                if (fieldVars.containsKey(usedVar)) {
+                    // Rewrites to a reference to a field in the group variable.
+                    varExprMap.put(usedVar,
+                            new FieldAccessor(fromBindingVar, new VarIdentifier(fieldVars.get(usedVar).getValue())));
+                } else if (outerVars.contains(usedVar)) {
+                    // Do nothing
+                } else if (fieldVars.size() == 1) {
+                    // Rewrites to a reference to a single field in the group variable.
+                    varExprMap.put(usedVar,
+                            new FieldAccessor(new FieldAccessor(fromBindingVar, fieldVars.values().iterator().next()),
+                                    SqlppVariableUtil.toUserDefinedVariableName(usedVar.getVar())));
+                } else {
+                    throw new CompilationException(
+                            "Cannot resolve alias reference for undefined identifier " + usedVar.getVar().getValue()
+                                    + " in " + fieldVars);
+                }
+            }
+
+            // Select clause.
+            SelectElement selectElement =
+                    new SelectElement(SqlppRewriteUtil.substituteExpression(expr, varExprMap, context));
+            SelectClause selectClause = new SelectClause(selectElement, null, false);
+
+            // Construct the select expression.
+            SelectBlock selectBlock = new SelectBlock(selectClause, fromClause, null, null, null, null, null);
+            SelectSetOperation selectSetOperation =
+                    new SelectSetOperation(new SetOperationInput(selectBlock, null), null);
+            return new SelectExpression(null, selectSetOperation, null, null, true);
+        }
+    }
+}
diff --git a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/visitor/SqlppGroupBySugarVisitor.java b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/visitor/SqlppGroupBySugarVisitor.java
deleted file mode 100644
index b7604ab..0000000
--- a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/visitor/SqlppGroupBySugarVisitor.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.asterix.lang.sqlpp.rewrites.visitor;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.asterix.common.exceptions.CompilationException;
-import org.apache.asterix.common.functions.FunctionSignature;
-import org.apache.asterix.lang.common.base.Expression;
-import org.apache.asterix.lang.common.base.ILangExpression;
-import org.apache.asterix.lang.common.expression.CallExpr;
-import org.apache.asterix.lang.common.expression.FieldAccessor;
-import org.apache.asterix.lang.common.expression.VariableExpr;
-import org.apache.asterix.lang.common.rewrites.LangRewritingContext;
-import org.apache.asterix.lang.sqlpp.clause.FromClause;
-import org.apache.asterix.lang.sqlpp.clause.FromTerm;
-import org.apache.asterix.lang.sqlpp.clause.SelectBlock;
-import org.apache.asterix.lang.sqlpp.clause.SelectClause;
-import org.apache.asterix.lang.sqlpp.clause.SelectElement;
-import org.apache.asterix.lang.sqlpp.clause.SelectSetOperation;
-import org.apache.asterix.lang.sqlpp.expression.SelectExpression;
-import org.apache.asterix.lang.sqlpp.struct.SetOperationInput;
-import org.apache.asterix.lang.sqlpp.util.FunctionMapUtil;
-import org.apache.asterix.lang.sqlpp.util.SqlppRewriteUtil;
-import org.apache.asterix.lang.sqlpp.util.SqlppVariableUtil;
-import org.apache.asterix.lang.sqlpp.visitor.base.AbstractSqlppExpressionScopingVisitor;
-
-/**
- * An AST pre-processor to rewrite group-by sugar queries, which does the following transformations:
- * 1. Rewrite the argument expression of an aggregation function into a subquery if the argument
- * expression is not a subquery;
- * 2. Turn a SQL-92 aggregate function into a SQL++ core aggregate function when performing 1.
- */
-
-// For example, this visitor turns the following query
-//
-// FROM Employee e
-// JOIN Incentive i ON e.job_category = i.job_category
-// JOIN SuperStars s ON e.id = s.id
-// GROUP BY e.department_id AS deptId
-// GROUP AS eis(e AS e, i AS i, s AS s)
-// SELECT deptId as deptId, SUM(e.salary + i.bonus) AS star_cost;
-//
-// into the following core-version query:
-//
-// FROM Employee e
-// JOIN Incentive i ON e.job_category = i.job_category
-// JOIN SuperStars s ON e.id = s.id
-// GROUP BY e.department_id AS deptId
-// GROUP AS eis(e AS e, i AS i, s AS s)
-// SELECT ELEMENT {
-//          'deptId': deptId,
-//          'star_cost': array_sum( (FROM eis AS p SELECT ELEMENT p.e.salary + p.i.bonus) )
-// };
-//
-// where SUM(e.salary + i.bonus) is turned into array_sum( (FROM eis AS p SELECT ELEMENT p.e.salary + p.i.bonus) ).
-
-public class SqlppGroupBySugarVisitor extends AbstractSqlppExpressionScopingVisitor {
-
-    private final Expression groupVar;
-    private final Collection<VariableExpr> fieldVars;
-
-    public SqlppGroupBySugarVisitor(LangRewritingContext context, Expression groupVar,
-            Collection<VariableExpr> fieldVars) {
-        super(context);
-        this.groupVar = groupVar;
-        this.fieldVars = fieldVars;
-    }
-
-    @Override
-    public Expression visit(CallExpr callExpr, ILangExpression arg) throws CompilationException {
-        List<Expression> newExprList = new ArrayList<>();
-        FunctionSignature signature = callExpr.getFunctionSignature();
-        boolean aggregate = FunctionMapUtil.isSql92AggregateFunction(signature);
-        boolean rewritten = false;
-        for (Expression expr : callExpr.getExprList()) {
-            Expression newExpr = aggregate ? wrapAggregationArgument(expr) : expr;
-            rewritten |= newExpr != expr;
-            newExprList.add(newExpr.accept(this, arg));
-        }
-        if (rewritten) {
-            // Rewrites the SQL-92 function name to core functions,
-            // e.g., SUM --> array_sum
-            callExpr.setFunctionSignature(FunctionMapUtil.sql92ToCoreAggregateFunction(signature));
-        }
-        callExpr.setExprList(newExprList);
-        return callExpr;
-    }
-
-    private Expression wrapAggregationArgument(Expression argExpr) throws CompilationException {
-        Expression expr = argExpr;
-        Set<VariableExpr> freeVars = SqlppRewriteUtil.getFreeVariable(expr);
-
-        VariableExpr fromBindingVar = new VariableExpr(context.newVariable());
-        FromTerm fromTerm = new FromTerm(groupVar, fromBindingVar, null, null);
-        FromClause fromClause = new FromClause(Collections.singletonList(fromTerm));
-
-        // Maps field variable expressions to field accesses.
-        Map<Expression, Expression> varExprMap = new HashMap<>();
-        for (VariableExpr usedVar : freeVars) {
-            // Reference to a field in the group variable.
-            if (fieldVars.contains(usedVar)) {
-                // Rewrites to a reference to a field in the group variable.
-                varExprMap.put(usedVar, new FieldAccessor(fromBindingVar,
-                        SqlppVariableUtil.toUserDefinedVariableName(usedVar.getVar())));
-            }
-        }
-
-        // Select clause.
-        SelectElement selectElement =
-                new SelectElement(SqlppRewriteUtil.substituteExpression(expr, varExprMap, context));
-        SelectClause selectClause = new SelectClause(selectElement, null, false);
-
-        // Construct the select expression.
-        SelectBlock selectBlock = new SelectBlock(selectClause, fromClause, null, null, null, null, null);
-        SelectSetOperation selectSetOperation = new SelectSetOperation(new SetOperationInput(selectBlock, null), null);
-        return new SelectExpression(null, selectSetOperation, null, null, true);
-    }
-}
diff --git a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/visitor/SqlppGroupByVisitor.java b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/visitor/SqlppGroupByVisitor.java
index dfe371e..bee5830 100644
--- a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/visitor/SqlppGroupByVisitor.java
+++ b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/visitor/SqlppGroupByVisitor.java
@@ -18,254 +18,119 @@
  */
 package org.apache.asterix.lang.sqlpp.rewrites.visitor;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
 import org.apache.asterix.common.exceptions.CompilationException;
 import org.apache.asterix.lang.common.base.Expression;
 import org.apache.asterix.lang.common.base.ILangExpression;
 import org.apache.asterix.lang.common.clause.GroupbyClause;
-import org.apache.asterix.lang.common.clause.LetClause;
-import org.apache.asterix.lang.common.clause.LimitClause;
-import org.apache.asterix.lang.common.clause.OrderbyClause;
 import org.apache.asterix.lang.common.expression.GbyVariableExpressionPair;
 import org.apache.asterix.lang.common.expression.VariableExpr;
 import org.apache.asterix.lang.common.rewrites.LangRewritingContext;
 import org.apache.asterix.lang.common.struct.Identifier;
-import org.apache.asterix.lang.common.struct.VarIdentifier;
-import org.apache.asterix.lang.sqlpp.clause.FromClause;
-import org.apache.asterix.lang.sqlpp.clause.HavingClause;
 import org.apache.asterix.lang.sqlpp.clause.SelectBlock;
 import org.apache.asterix.lang.sqlpp.clause.SelectClause;
-import org.apache.asterix.lang.sqlpp.expression.SelectExpression;
-import org.apache.asterix.lang.sqlpp.util.SqlppRewriteUtil;
 import org.apache.asterix.lang.sqlpp.util.SqlppVariableUtil;
-import org.apache.asterix.lang.sqlpp.visitor.base.AbstractSqlppExpressionScopingVisitor;
+import org.apache.asterix.lang.sqlpp.visitor.CheckSql92AggregateVisitor;
+import org.apache.asterix.lang.sqlpp.visitor.base.AbstractSqlppSimpleExpressionVisitor;
 import org.apache.hyracks.algebricks.common.utils.Pair;
 
-/**
- * A pre-processor that adds the group variable as well as its group field
- * list into the AST. It will also invoke SQL group-by aggregation sugar rewritings.
- */
-// This visitor rewrites non-core SQL++ group-by queries into their SQL++ core version
-// queries. For example, for the non-core query in
-// asterix-app/src/test/resources/runtimets/queries_sqlpp/group-by/sugar-01/sugar-01.3.query.sqlpp,
-//
-// FROM Employee e
-// JOIN Incentive i ON e.job_category = i.job_category
-// JOIN SuperStars s ON e.id = s.id
-// GROUP BY e.department_id AS deptId
-// SELECT deptId as deptId, SUM(e.salary + i.bonus) AS star_cost;
-//
-// this visitor transforms it into the core version in
-// asterix-app/src/test/resources/runtimets/queries_sqlpp/group-by/sugar-01/sugar-01.3.query.sqlpp,
-//
-// FROM Employee e
-// JOIN Incentive i ON e.job_category = i.job_category
-// JOIN SuperStars s ON e.id = s.id
-// GROUP BY e.department_id AS deptId
-// GROUP AS eis(e AS e, i AS i, s AS s)
-// SELECT ELEMENT {
-//  'deptId': deptId,
-//  'star_cost': array_sum( (FROM eis AS p SELECT ELEMENT p.e.salary + p.i.bonus) )
-// };
-/**
- * The transformation include three things:
- * 1. Add a group variable as well as its definition, e.g., GROUP AS eis(e AS e, i AS i, s AS s);
- * 2. Rewrite the argument expression of an aggregation function into a subquery if the argument
- * expression is not a subquery;
- * 3. Turn a SQL-92 aggregate function into a SQL++ core aggregate function when performing 2, e.g.,
- * SUM(e.salary + i.bonus) becomes
- * array_sum( (FROM eis AS p SELECT ELEMENT p.e.salary + p.i.bonus) ).
- */
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
 
-public class SqlppGroupByVisitor extends AbstractSqlppExpressionScopingVisitor {
+/**
+ * A pre-processor that
+ * <ul>
+ *     <li>adds the group variable as well as its group field
+ *         list into the AST. e.g., GROUP AS eis(e AS e, i AS i, s AS s)</li>
+ *     <li>adds group by clause if select block contains SQL-92 agregate function but there's no group by clause</li>
+ * </ul>
+ */
+public class SqlppGroupByVisitor extends AbstractSqlppSimpleExpressionVisitor {
+
+    private final LangRewritingContext context;
 
     public SqlppGroupByVisitor(LangRewritingContext context) {
-        super(context);
+        this.context = context;
     }
 
     @Override
     public Expression visit(SelectBlock selectBlock, ILangExpression arg) throws CompilationException {
-        // Traverses the select block in the order of "from", "let"s, "where",
-        // "group by", "let"s, "having" and "select".
-        FromClause fromClause = selectBlock.getFromClause();
         if (selectBlock.hasFromClause()) {
-            fromClause.accept(this, arg);
-        }
-        if (selectBlock.hasLetClauses()) {
-            List<LetClause> letList = selectBlock.getLetList();
-            for (LetClause letClause : letList) {
-                letClause.accept(this, arg);
-            }
-        }
-        if (selectBlock.hasWhereClause()) {
-            selectBlock.getWhereClause().accept(this, arg);
-        }
-        if (selectBlock.hasGroupbyClause()) {
-            GroupbyClause groupbyClause = selectBlock.getGroupbyClause();
-            groupbyClause.accept(this, fromClause);
-            Collection<VariableExpr> visibleVarsInCurrentScope = SqlppVariableUtil.getBindingVariables(groupbyClause);
-
-            VariableExpr groupVar = groupbyClause.getGroupVar();
-            Set<VariableExpr> groupFieldVars = getGroupFieldVariables(groupbyClause);
-
-            Collection<VariableExpr> freeVariablesInGbyLets = new HashSet<>();
-            if (selectBlock.hasLetClausesAfterGroupby()) {
-                List<LetClause> letListAfterGby = selectBlock.getLetListAfterGroupby();
-                for (LetClause letClauseAfterGby : letListAfterGby) {
-                    letClauseAfterGby.accept(this, arg);
-                    // Rewrites each let clause after the group-by.
-                    SqlppRewriteUtil.rewriteExpressionUsingGroupVariable(groupVar, groupFieldVars, letClauseAfterGby,
-                            context);
-                    Collection<VariableExpr> freeVariablesInLet = SqlppVariableUtil.getFreeVariables(letClauseAfterGby
-                            .getBindingExpr());
-                    freeVariablesInLet.removeAll(visibleVarsInCurrentScope);
-                    freeVariablesInGbyLets.addAll(freeVariablesInLet);
-                    visibleVarsInCurrentScope.add(letClauseAfterGby.getVarExpr());
-                }
-            }
-
-            Collection<VariableExpr> freeVariables = new HashSet<>();
-            if (selectBlock.hasHavingClause()) {
-                // Rewrites the having clause.
-                HavingClause havingClause = selectBlock.getHavingClause();
-                havingClause.accept(this, arg);
-                SqlppRewriteUtil.rewriteExpressionUsingGroupVariable(groupVar, groupFieldVars, havingClause, context);
-                freeVariables.addAll(SqlppVariableUtil.getFreeVariables(havingClause));
-            }
-
-            SelectExpression parentSelectExpression = (SelectExpression) arg;
-            // We cannot rewrite ORDER BY and LIMIT if it's a SET operation query.
-            if (!parentSelectExpression.getSelectSetOperation().hasRightInputs()) {
-                if (parentSelectExpression.hasOrderby()) {
-                    // Rewrites the ORDER BY clause.
-                    OrderbyClause orderbyClause = parentSelectExpression.getOrderbyClause();
-                    orderbyClause.accept(this, arg);
-                    SqlppRewriteUtil.rewriteExpressionUsingGroupVariable(groupVar, groupFieldVars, orderbyClause,
-                            context);
-                    freeVariables.addAll(SqlppVariableUtil.getFreeVariables(orderbyClause));
-                }
-                if (parentSelectExpression.hasLimit()) {
-                    // Rewrites the LIMIT clause.
-                    LimitClause limitClause = parentSelectExpression.getLimitClause();
-                    limitClause.accept(this, arg);
-                    SqlppRewriteUtil
-                            .rewriteExpressionUsingGroupVariable(groupVar, groupFieldVars, limitClause, context);
-                    freeVariables.addAll(SqlppVariableUtil.getFreeVariables(limitClause));
-                }
-            }
-
-            // Visits the select clause.
-            SelectClause selectClause = selectBlock.getSelectClause();
-            selectClause.accept(this, arg);
-            // Rewrites the select clause.
-            SqlppRewriteUtil.rewriteExpressionUsingGroupVariable(groupVar, groupFieldVars, selectClause, context);
-            freeVariables.addAll(SqlppVariableUtil.getFreeVariables(selectClause));
-            freeVariables.removeAll(visibleVarsInCurrentScope);
-
-            // Gets the final free variables.
-            freeVariables.addAll(freeVariablesInGbyLets);
-
-            // Gets outer scope variables.
-            Collection<VariableExpr> decorVars = SqlppVariableUtil.getLiveVariables(
-                    scopeChecker.getCurrentScope(), true);
-            decorVars.removeAll(visibleVarsInCurrentScope);
-
-            // Need path resolution or not?
-            boolean needResolution = !decorVars.containsAll(freeVariables);
-            // If path resolution is needed, we need to include all outer scope variables in the decoration list.
-            // Otherwise, we only need to retain used free variables.
-            if (needResolution) {
-                // Tracks used variables, including WITH variables.
-                decorVars.retainAll(freeVariables);
-                // Adds all outer scope variables, for path resolution.
-                Collection<VariableExpr> visibleOuterScopeNonWithVars = SqlppVariableUtil.getLiveVariables(
-                        scopeChecker.getCurrentScope(), false);
-                visibleOuterScopeNonWithVars.removeAll(visibleVarsInCurrentScope);
-                decorVars.addAll(visibleOuterScopeNonWithVars);
+            if (selectBlock.hasGroupbyClause()) {
+                rewriteSelectWithGroupBy(selectBlock, arg);
             } else {
-                // Only retains used free variables.
-                decorVars.retainAll(freeVariables);
+                rewriteSelectWithoutGroupBy(selectBlock);
             }
-            if (!decorVars.isEmpty()) {
-                // Adds used WITH variables.
-                Collection<VariableExpr> visibleOuterScopeNonWithVars = SqlppVariableUtil.getLiveVariables(
-                        scopeChecker.getCurrentScope(), false);
-                visibleOuterScopeNonWithVars.retainAll(freeVariables);
-                decorVars.addAll(visibleOuterScopeNonWithVars);
-
-                // Adds necessary decoration variables for the GROUP BY.
-                // NOTE: we need to include WITH binding variables so as they can be evaluated before
-                // the GROUP BY instead of being inlined as part of nested pipepline. The current optimzier
-                // is not able to optimize the latter case. The following query is such an example:
-                // asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/dapd/q2-11
-                List<GbyVariableExpressionPair> decorList = new ArrayList<>();
-                for (VariableExpr var : decorVars) {
-                    decorList.add(new GbyVariableExpressionPair((VariableExpr) SqlppRewriteUtil.deepCopy(var),
-                            (Expression) SqlppRewriteUtil.deepCopy(var)));
-                }
-                groupbyClause.getDecorPairList().addAll(decorList);
-            }
-        } else {
-            selectBlock.getSelectClause().accept(this, arg);
         }
-        return null;
+        return super.visit(selectBlock, arg);
     }
 
-    @Override
-    public Expression visit(GroupbyClause gc, ILangExpression arg) throws CompilationException {
-        FromClause fromClause = (FromClause) arg;
-        Collection<VariableExpr> fromBindingVars =
-                fromClause == null ? new ArrayList<>() : SqlppVariableUtil.getBindingVariables(fromClause);
+    private void rewriteSelectWithGroupBy(SelectBlock selectBlock, ILangExpression arg) throws CompilationException {
+        GroupbyClause gbyClause = selectBlock.getGroupbyClause();
+
+        // Sets the group variable.
+        if (!gbyClause.hasGroupVar()) {
+            VariableExpr groupVar = new VariableExpr(context.newVariable());
+            gbyClause.setGroupVar(groupVar);
+        }
+
         // Sets the field list for the group variable.
-        List<Pair<Expression, Identifier>> groupFieldList = new ArrayList<>();
-        if (!gc.hasGroupFieldList()) {
-            for (VariableExpr varExpr : fromBindingVars) {
-                Pair<Expression, Identifier> varIdPair = new Pair<>(new VariableExpr(varExpr.getVar()),
-                        SqlppVariableUtil.toUserDefinedVariableName(varExpr.getVar()));
-                groupFieldList.add(varIdPair);
-            }
-            gc.setGroupFieldList(groupFieldList);
-        } else {
-            for (Pair<Expression, Identifier> groupField : gc.getGroupFieldList()) {
+        List<Pair<Expression, Identifier>> groupFieldList;
+        if (gbyClause.hasGroupFieldList()) {
+            groupFieldList = new ArrayList<>();
+            for (Pair<Expression, Identifier> groupField : gbyClause.getGroupFieldList()) {
                 Expression newFieldExpr = groupField.first.accept(this, arg);
                 groupFieldList.add(new Pair<>(newFieldExpr, groupField.second));
             }
+        } else {
+            groupFieldList = createGroupFieldList(selectBlock);
         }
-
-        gc.setGroupFieldList(groupFieldList);
-
-        // Sets the group variable.
-        if (!gc.hasGroupVar()) {
-            VariableExpr groupVar = new VariableExpr(context.newVariable());
-            gc.setGroupVar(groupVar);
-        }
-
-        // Adds the group variable into the "with" (i.e., re-binding) variable list.
-        VariableExpr gbyVarRef = new VariableExpr(gc.getGroupVar().getVar());
-        gbyVarRef.setIsNewVar(false);
-        Map<Expression, VariableExpr> withVarMap = new HashMap<>();
-        withVarMap.put(gbyVarRef, (VariableExpr) SqlppRewriteUtil.deepCopy(gbyVarRef));
-        gc.setWithVarMap(withVarMap);
-
-        // Call super.visit(...) to scope variables.
-        return super.visit(gc, arg);
+        gbyClause.setGroupFieldList(groupFieldList);
     }
 
-    private Set<VariableExpr> getGroupFieldVariables(GroupbyClause groupbyClause) {
-        Set<VariableExpr> fieldVars = new HashSet<>();
-        if (groupbyClause.hasGroupFieldList()) {
-            for (Pair<Expression, Identifier> groupField : groupbyClause.getGroupFieldList()) {
-                fieldVars.add(new VariableExpr(new VarIdentifier(SqlppVariableUtil
-                        .toInternalVariableName(groupField.second.getValue()))));
-            }
+    private void rewriteSelectWithoutGroupBy(SelectBlock selectBlock) throws CompilationException {
+        if (hasSql92Aggregate(selectBlock)) {
+            // Adds an implicit group-by clause for SQL-92 global aggregate.
+            List<GbyVariableExpressionPair> gbyPairList = new ArrayList<>();
+            List<GbyVariableExpressionPair> decorPairList = new ArrayList<>();
+            VariableExpr groupVar = new VariableExpr(context.newVariable());
+            List<Pair<Expression, Identifier>> groupFieldList = createGroupFieldList(selectBlock);
+            GroupbyClause gbyClause = new GroupbyClause(gbyPairList, decorPairList, new HashMap<>(), groupVar,
+                    groupFieldList, false, true);
+            selectBlock.setGroupbyClause(gbyClause);
         }
-        return fieldVars;
+    }
+
+    private boolean hasSql92Aggregate(SelectBlock selectBlock) throws CompilationException {
+        SelectClause selectClause = selectBlock.getSelectClause();
+        if (selectClause.selectRegular()) {
+            return isSql92Aggregate(selectClause.getSelectRegular(), selectBlock);
+        } else if (selectClause.selectElement()) {
+            return isSql92Aggregate(selectClause.getSelectElement(), selectBlock);
+        } else {
+            throw new IllegalStateException();
+        }
+    }
+
+    private boolean isSql92Aggregate(ILangExpression expr, SelectBlock selectBlock) throws CompilationException {
+        CheckSql92AggregateVisitor visitor = new CheckSql92AggregateVisitor();
+        return expr.accept(visitor, selectBlock);
+    }
+
+    private List<Pair<Expression, Identifier>> createGroupFieldList(SelectBlock selectBlock) {
+        List<Pair<Expression, Identifier>> groupFieldList = new ArrayList<>();
+        addToGroupFieldList(groupFieldList, SqlppVariableUtil.getBindingVariables(selectBlock.getFromClause()));
+        addToGroupFieldList(groupFieldList, SqlppVariableUtil.getBindingVariables(selectBlock.getLetList()));
+        return groupFieldList;
+    }
+
+    private void addToGroupFieldList(List<Pair<Expression, Identifier>> groupFieldList,
+            Collection<VariableExpr> fromBindingVars) {
+        for (VariableExpr varExpr : fromBindingVars) {
+            Pair<Expression, Identifier> varIdPair = new Pair<>(new VariableExpr(varExpr.getVar()),
+                    SqlppVariableUtil.toUserDefinedVariableName(varExpr.getVar()));
+            groupFieldList.add(varIdPair);
+        }
     }
 }
diff --git a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/visitor/VariableCheckAndRewriteVisitor.java b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/visitor/VariableCheckAndRewriteVisitor.java
index 6e6ffeb..7a37f94 100644
--- a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/visitor/VariableCheckAndRewriteVisitor.java
+++ b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/rewrites/visitor/VariableCheckAndRewriteVisitor.java
@@ -35,32 +35,27 @@
 import org.apache.asterix.lang.common.rewrites.LangRewritingContext;
 import org.apache.asterix.lang.common.struct.Identifier;
 import org.apache.asterix.lang.common.struct.VarIdentifier;
+import org.apache.asterix.lang.sqlpp.util.FunctionMapUtil;
 import org.apache.asterix.lang.sqlpp.util.SqlppVariableUtil;
 import org.apache.asterix.lang.sqlpp.visitor.CheckDatasetOnlyResolutionVisitor;
 import org.apache.asterix.lang.sqlpp.visitor.base.AbstractSqlppExpressionScopingVisitor;
 import org.apache.asterix.metadata.declared.MetadataProvider;
 import org.apache.asterix.om.functions.BuiltinFunctions;
+import org.apache.commons.lang3.StringUtils;
 import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
 
 public class VariableCheckAndRewriteVisitor extends AbstractSqlppExpressionScopingVisitor {
 
     private static final FunctionSignature FN_DATASET = new FunctionSignature(BuiltinFunctions.DATASET);
 
-    protected final boolean overwrite;
     protected final MetadataProvider metadataProvider;
 
     /**
-     * @param context,
-     *            manages ids of variables and guarantees uniqueness of variables.
-     * @param overwrite,
-     *            whether rewrite unbounded variables to dataset function calls.
-     *            This flag can only be true for rewriting a top-level query.
-     *            It should be false for rewriting the body expression of a user-defined function.
+     * @param context, manages ids of variables and guarantees uniqueness of variables.
      */
-    public VariableCheckAndRewriteVisitor(LangRewritingContext context, boolean overwrite,
-            MetadataProvider metadataProvider) {
-        super(context);
-        this.overwrite = overwrite;
+    public VariableCheckAndRewriteVisitor(LangRewritingContext context, MetadataProvider metadataProvider,
+            List<VarIdentifier> externalVars) {
+        super(context, externalVars);
         this.metadataProvider = metadataProvider;
     }
 
@@ -74,7 +69,7 @@
             VariableExpr varExpr = (VariableExpr) leadingExpr;
             String lastIdentifier = fa.getIdent().getValue();
             Expression resolvedExpr = resolve(varExpr,
-                    /** Resolves within the dataverse that has the same name as the variable name. */
+                    /* Resolves within the dataverse that has the same name as the variable name. */
                     SqlppVariableUtil.toUserDefinedVariableName(varExpr.getVar().getValue()).getValue(), lastIdentifier,
                     fa, parent);
             if (resolvedExpr.getKind() == Kind.CALL_EXPRESSION) {
@@ -91,36 +86,70 @@
 
     @Override
     public Expression visit(VariableExpr varExpr, ILangExpression parent) throws CompilationException {
-        return resolve(varExpr, null /** Resolves within the default dataverse. */
-                , SqlppVariableUtil.toUserDefinedVariableName(varExpr.getVar().getValue()).getValue(), varExpr, parent);
+        return resolve(varExpr, null /* Resolves within the default dataverse. */,
+                SqlppVariableUtil.toUserDefinedVariableName(varExpr.getVar().getValue()).getValue(), varExpr, parent);
     }
 
     // Resolve a variable expression with dataverse name and dataset name.
     private Expression resolve(VariableExpr varExpr, String dataverseName, String datasetName,
-            Expression originalExprWithUndefinedIdentifier, ILangExpression parent)
-            throws CompilationException {
+            Expression originalExprWithUndefinedIdentifier, ILangExpression parent) throws CompilationException {
+
         String varName = varExpr.getVar().getValue();
-        checkError(varName);
-        if (!rewriteNeeded(varExpr)) {
+
+        VarIdentifier var = lookupVariable(varName);
+        if (var != null) {
+            // Exists such an identifier
+            varExpr.setIsNewVar(false);
+            varExpr.setVar(var);
             return varExpr;
         }
-        // Note: WITH variables are not used for path resolution. The reason is that
-        // the accurate typing for ordered list with an UNION item type is not implemented.
-        // We currently type it as [ANY]. If we include WITH variables for path resolution,
-        // it will lead to ambiguities and the plan is going to be very complex.  An example query is:
-        // asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/subquery/exists
-        Set<VariableExpr> liveVars = SqlppVariableUtil.getLiveVariables(scopeChecker.getCurrentScope(), false);
-        boolean resolveToDatasetOnly = resolveToDatasetOnly(originalExprWithUndefinedIdentifier, parent);
-        boolean resolveAsDataset = datasetExists(dataverseName, datasetName);
 
+        boolean resolveToDatasetOnly = resolveToDatasetOnly(originalExprWithUndefinedIdentifier, parent);
         if (resolveToDatasetOnly) {
-            if (resolveAsDataset) {
-                return wrapWithDatasetFunction(dataverseName, datasetName);
-            } else {
-                throwUnresolvableError(dataverseName, datasetName);
-            }
+            return resolveAsDataset(dataverseName, datasetName);
         }
-        return wrapWithResolveFunction(varExpr, liveVars);
+
+        Set<VariableExpr> localVars = scopeChecker.getCurrentScope().getLiveVariables(scopeChecker.getPrecedingScope());
+        switch (localVars.size()) {
+            case 0:
+                return resolveAsDataset(dataverseName, datasetName);
+            case 1:
+                return resolveAsFieldAccess(localVars.iterator().next(),
+                        SqlppVariableUtil.toUserDefinedVariableName(varName).getValue());
+            default:
+                // More than one possibilities.
+                throw new CompilationException(
+                        "Cannot resolve ambiguous alias reference for undefined identifier " + SqlppVariableUtil
+                                .toUserDefinedVariableName(varName).getValue() + " in " + localVars);
+        }
+    }
+
+    private VarIdentifier lookupVariable(String varName) throws CompilationException {
+        if (scopeChecker.isInForbiddenScopes(varName)) {
+            throw new CompilationException(
+                    "Inside limit clauses, it is disallowed to reference a variable having the same name"
+                            + " as any variable bound in the same scope as the limit clause.");
+        }
+        Identifier ident = scopeChecker.lookupSymbol(varName);
+        return ident != null ? (VarIdentifier) ident : null;
+    }
+
+    private Expression resolveAsDataset(String dataverseName, String datasetName) throws CompilationException {
+        if (!datasetExists(dataverseName, datasetName)) {
+            throwUnresolvableError(dataverseName, datasetName);
+        }
+        String fullyQualifiedName = dataverseName == null ? datasetName : dataverseName + "." + datasetName;
+        List<Expression> argList = new ArrayList<>(1);
+        argList.add(new LiteralExpr(new StringLiteral(fullyQualifiedName)));
+        return new CallExpr(new FunctionSignature(BuiltinFunctions.DATASET), argList);
+    }
+
+    // Rewrites for an field access by name
+    private Expression resolveAsFieldAccess(VariableExpr var, String fieldName) throws CompilationException {
+        List<Expression> argList = new ArrayList<>(2);
+        argList.add(var);
+        argList.add(new LiteralExpr(new StringLiteral(fieldName)));
+        return new CallExpr(new FunctionSignature(BuiltinFunctions.FIELD_ACCESS_BY_NAME), argList);
     }
 
     private void throwUnresolvableError(String dataverseName, String datasetName) throws CompilationException {
@@ -130,19 +159,10 @@
                     + " because there is no dataverse declared, nor an alias with name " + datasetName + "!");
         }
         //If no available dataset nor in-scope variable to resolve to, we throw an error.
-        throw new CompilationException("Cannot find dataset " + datasetName + " in dataverse "
-                + (dataverseName == null ? defaultDataverseName : dataverseName) + " nor an alias with name "
-                + datasetName + "!");
-    }
-
-    // Checks whether we need to error the variable reference, e.g., the variable is referred
-    // in a LIMIT clause.
-    private void checkError(String varName) throws CompilationException {
-        if (scopeChecker.isInForbiddenScopes(varName)) {
-            throw new CompilationException(
-                    "Inside limit clauses, it is disallowed to reference a variable having the same name"
-                            + " as any variable bound in the same scope as the limit clause.");
-        }
+        throw new CompilationException(
+                "Cannot find dataset " + datasetName + " in dataverse " + (dataverseName == null ?
+                        defaultDataverseName :
+                        dataverseName) + " nor an alias with name " + datasetName + "!");
     }
 
     // For a From/Join/UNNEST/Quantifiers binding expression, we resolve the undefined identifier reference as
@@ -153,51 +173,29 @@
         return parent.accept(visitor, originalExpressionWithUndefinedIdentifier);
     }
 
-    // Whether a rewrite is needed for a variable reference expression.
-    private boolean rewriteNeeded(VariableExpr varExpr) throws CompilationException {
-        String varName = varExpr.getVar().getValue();
-        Identifier ident = scopeChecker.lookupSymbol(varName);
-        if (ident != null) {
-            // Exists such an identifier
-            varExpr.setIsNewVar(false);
-            varExpr.setVar((VarIdentifier) ident);
-            return false;
-        } else {
-            // Meets a undefined variable
-            return overwrite;
-        }
-    }
-
-    private Expression wrapWithDatasetFunction(String dataverseName, String datasetName) throws CompilationException {
-        String fullyQualifiedName = dataverseName == null ? datasetName : dataverseName + "." + datasetName;
-        List<Expression> argList = new ArrayList<>();
-        argList.add(new LiteralExpr(new StringLiteral(fullyQualifiedName)));
-        return new CallExpr(new FunctionSignature(BuiltinFunctions.DATASET), argList);
-    }
-
     private boolean datasetExists(String dataverseName, String datasetName) throws CompilationException {
         try {
-            if (metadataProvider.findDataset(dataverseName, datasetName) != null) {
-                return true;
-            }
-            return fullyQualifiedDatasetNameExists(datasetName);
+            return metadataProvider.findDataset(dataverseName, datasetName) != null || fullyQualifiedDatasetNameExists(
+                    datasetName);
         } catch (AlgebricksException e) {
             throw new CompilationException(e);
         }
     }
 
     private boolean fullyQualifiedDatasetNameExists(String name) throws AlgebricksException {
-        if (!name.contains(".")) {
+        if (name.indexOf('.') < 0) {
             return false;
         }
-        String[] path = name.split("\\.");
-        if (path.length != 2) {
-            return false;
-        }
-        if (metadataProvider.findDataset(path[0], path[1]) != null) {
-            return true;
-        }
-        return false;
+        String[] path = StringUtils.split(name, '.');
+        return path.length == 2 && metadataProvider.findDataset(path[0], path[1]) != null;
     }
 
+    @Override
+    public Expression visit(CallExpr callExpr, ILangExpression arg) throws CompilationException {
+        // skip variables inside SQL-92 aggregates (they will be resolved by SqlppGroupByAggregationSugarVisitor)
+        if (FunctionMapUtil.isSql92AggregateFunction(callExpr.getFunctionSignature())) {
+            return callExpr;
+        }
+        return super.visit(callExpr, arg);
+    }
 }
diff --git a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/util/SqlppRewriteUtil.java b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/util/SqlppRewriteUtil.java
index a8c5ddc..228ea23 100644
--- a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/util/SqlppRewriteUtil.java
+++ b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/util/SqlppRewriteUtil.java
@@ -18,7 +18,6 @@
  */
 package org.apache.asterix.lang.sqlpp.util;
 
-import java.util.Collection;
 import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
@@ -29,7 +28,6 @@
 import org.apache.asterix.lang.common.expression.VariableExpr;
 import org.apache.asterix.lang.common.rewrites.LangRewritingContext;
 import org.apache.asterix.lang.common.statement.Query;
-import org.apache.asterix.lang.sqlpp.rewrites.visitor.SqlppGroupBySugarVisitor;
 import org.apache.asterix.lang.sqlpp.visitor.CheckSubqueryVisitor;
 import org.apache.asterix.lang.sqlpp.visitor.DeepCopyVisitor;
 import org.apache.asterix.lang.sqlpp.visitor.FreeVariableVisitor;
@@ -40,14 +38,6 @@
     private SqlppRewriteUtil() {
     }
 
-    // Applying sugar rewriting for group-by.
-    public static Expression rewriteExpressionUsingGroupVariable(VariableExpr groupVar,
-            Collection<VariableExpr> fieldVars, ILangExpression expr, LangRewritingContext context)
-            throws CompilationException {
-        SqlppGroupBySugarVisitor visitor = new SqlppGroupBySugarVisitor(context, groupVar, fieldVars);
-        return expr.accept(visitor, null);
-    }
-
     public static Set<VariableExpr> getFreeVariable(Expression expr) throws CompilationException {
         Set<VariableExpr> vars = new HashSet<>();
         FreeVariableVisitor visitor = new FreeVariableVisitor();
diff --git a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/util/SqlppVariableUtil.java b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/util/SqlppVariableUtil.java
index 2d6ac53..519627c 100644
--- a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/util/SqlppVariableUtil.java
+++ b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/util/SqlppVariableUtil.java
@@ -22,15 +22,12 @@
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashSet;
-import java.util.Iterator;
 import java.util.List;
-import java.util.Set;
 
 import org.apache.asterix.common.exceptions.CompilationException;
 import org.apache.asterix.lang.common.base.ILangExpression;
 import org.apache.asterix.lang.common.clause.GroupbyClause;
 import org.apache.asterix.lang.common.clause.LetClause;
-import org.apache.asterix.lang.common.context.Scope;
 import org.apache.asterix.lang.common.expression.GbyVariableExpressionPair;
 import org.apache.asterix.lang.common.expression.VariableExpr;
 import org.apache.asterix.lang.common.struct.VarIdentifier;
@@ -77,22 +74,6 @@
         return varName;
     }
 
-    public static Set<VariableExpr> getLiveVariables(Scope scope, boolean includeWithVariables) {
-        Set<VariableExpr> results = new HashSet<>();
-        Set<VariableExpr> liveVars = scope.getLiveVariables();
-        Iterator<VariableExpr> liveVarIter = liveVars.iterator();
-        while (liveVarIter.hasNext()) {
-            VariableExpr liveVar = liveVarIter.next();
-            // Variables defined in WITH clauses are named value access.
-            // TODO(buyingi): remove this if block once we can accurately type
-            // ordered lists with UNION item type. Currently it is typed as [ANY].
-            if (includeWithVariables || !liveVar.getVar().namedValueAccess()) {
-                results.add(liveVar);
-            }
-        }
-        return results;
-    }
-
     public static String toInternalVariableName(String varName) {
         return USER_VAR_PREFIX + varName;
     }
diff --git a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/DeepCopyVisitor.java b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/DeepCopyVisitor.java
index 0d3f320..ffd63d4 100644
--- a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/DeepCopyVisitor.java
+++ b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/DeepCopyVisitor.java
@@ -231,7 +231,8 @@
 
     @Override
     public Query visit(Query q, Void arg) throws CompilationException {
-        return new Query(q.isExplain(), q.isTopLevel(), (Expression) q.getBody().accept(this, arg), q.getVarCounter());
+        return new Query(q.isExplain(), q.isTopLevel(), (Expression) q.getBody().accept(this, arg), q.getVarCounter(),
+                q.getExternalVars());
     }
 
     @Override
diff --git a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/FreeVariableVisitor.java b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/FreeVariableVisitor.java
index 6c38334..1a54b92 100644
--- a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/FreeVariableVisitor.java
+++ b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/FreeVariableVisitor.java
@@ -166,7 +166,8 @@
 
         selectBlock.getSelectClause().accept(this, selectFreeVars);
         // Removes group-by, from, let, and gby-let binding vars.
-        removeAllBindingVarsInSelectBlock(selectFreeVars, fromBindingVars, letsBindingVars, gbyLetsBindingVars);
+        removeAllBindingVarsInSelectBlock(selectFreeVars, fromBindingVars, letsBindingVars, gbyBindingVars,
+                gbyLetsBindingVars);
 
         if (selectBlock.hasFromClause()) {
             selectBlock.getFromClause().accept(this, fromFreeVars);
@@ -193,13 +194,15 @@
             }
             if (selectBlock.hasHavingClause()) {
                 selectBlock.getHavingClause().accept(this, selectFreeVars);
-                removeAllBindingVarsInSelectBlock(selectFreeVars, fromBindingVars, letsBindingVars, gbyLetsBindingVars);
+                removeAllBindingVarsInSelectBlock(selectFreeVars, fromBindingVars, letsBindingVars, gbyBindingVars,
+                        gbyLetsBindingVars);
             }
         }
 
         // Removes all binding vars from <code>freeVars</code>, which contains the free
         // vars in the order-by and limit.
-        removeAllBindingVarsInSelectBlock(freeVars, fromBindingVars, letsBindingVars, gbyLetsBindingVars);
+        removeAllBindingVarsInSelectBlock(freeVars, fromBindingVars, letsBindingVars, gbyBindingVars,
+                gbyLetsBindingVars);
 
         // Adds all free vars.
         freeVars.addAll(selectFreeVars);
@@ -462,23 +465,23 @@
 
     /**
      * Removes all binding variables defined in the select block for a free variable collection.
-     *
-     * @param freeVars,
+     *  @param selectFreeVars,
      *            free variables.
      * @param fromBindingVars,
      *            binding variables defined in the from clause of a select block.
      * @param letsBindingVars,
      *            binding variables defined in the let clauses of the select block.
-     * @param gbyLetsBindingVars,
-     *            binding variables defined in the let clauses after a group-by in the select block.
+     * @param gbyBindingVars
+     *            binding variables defined in the groupby clauses of the select block
+     * @param gbyLetsBindingVars
+     *            binding variables defined in the let clauses after groupby of the select block.
      */
     private void removeAllBindingVarsInSelectBlock(Collection<VariableExpr> selectFreeVars,
             Collection<VariableExpr> fromBindingVars, Collection<VariableExpr> letsBindingVars,
-            Collection<VariableExpr> gbyLetsBindingVars) {
+            Collection<VariableExpr> gbyBindingVars, Collection<VariableExpr> gbyLetsBindingVars) {
         selectFreeVars.removeAll(fromBindingVars);
         selectFreeVars.removeAll(letsBindingVars);
-        selectFreeVars.removeAll(gbyLetsBindingVars);
+        selectFreeVars.removeAll(gbyBindingVars);
         selectFreeVars.removeAll(gbyLetsBindingVars);
     }
-
 }
diff --git a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/SqlppAstPrintVisitor.java b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/SqlppAstPrintVisitor.java
index 38d09f9..09eaa59 100644
--- a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/SqlppAstPrintVisitor.java
+++ b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/SqlppAstPrintVisitor.java
@@ -20,6 +20,7 @@
 
 import java.io.PrintWriter;
 import java.util.List;
+import java.util.Map;
 
 import org.apache.asterix.common.exceptions.CompilationException;
 import org.apache.asterix.common.functions.FunctionSignature;
@@ -28,6 +29,7 @@
 import org.apache.asterix.lang.common.clause.LetClause;
 import org.apache.asterix.lang.common.expression.CallExpr;
 import org.apache.asterix.lang.common.expression.GbyVariableExpressionPair;
+import org.apache.asterix.lang.common.expression.VariableExpr;
 import org.apache.asterix.lang.common.struct.Identifier;
 import org.apache.asterix.lang.common.visitor.QueryPrintVisitor;
 import org.apache.asterix.lang.sqlpp.clause.AbstractBinaryCorrelateClause;
@@ -264,15 +266,25 @@
     public Void visit(GroupbyClause gc, Integer step) throws CompilationException {
         if (gc.isGroupAll()) {
             out.println(skip(step) + "Group All");
-            return null;
-        }
-        out.println(skip(step) + "Groupby");
-        for (GbyVariableExpressionPair pair : gc.getGbyPairList()) {
-            if (pair.getVar() != null) {
-                pair.getVar().accept(this, step + 1);
-                out.println(skip(step + 1) + ":=");
+        } else {
+            out.println(skip(step) + "Groupby");
+            for (GbyVariableExpressionPair pair : gc.getGbyPairList()) {
+                if (pair.getVar() != null) {
+                    pair.getVar().accept(this, step + 1);
+                    out.println(skip(step + 1) + ":=");
+                }
+                pair.getExpr().accept(this, step + 1);
             }
-            pair.getExpr().accept(this, step + 1);
+        }
+        if (gc.hasDecorList()) {
+            out.println(skip(step + 1) + "DECOR");
+            for (GbyVariableExpressionPair pair : gc.getDecorPairList()) {
+                if (pair.getVar() != null) {
+                    pair.getVar().accept(this, step + 1);
+                    out.println(skip(step + 1) + ":=");
+                }
+                pair.getExpr().accept(this, step + 1);
+            }
         }
         if (gc.hasGroupVar()) {
             out.print(skip(step + 1) + "GROUP AS ");
@@ -286,6 +298,14 @@
                 out.println(skip(step + 1) + ")");
             }
         }
+        if (gc.hasWithMap()) {
+            out.println(skip(step + 1) + "WITH");
+            for (Map.Entry<Expression, VariableExpr> pair : gc.getWithVarMap().entrySet()) {
+                pair.getValue().accept(this, step + 1);
+                out.println(skip(step + 1) + ":=");
+                pair.getKey().accept(this, step + 1);
+            }
+        }
         out.println();
         return null;
     }
diff --git a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/SqlppCloneAndSubstituteVariablesVisitor.java b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/SqlppCloneAndSubstituteVariablesVisitor.java
index 844856d..65e9255 100644
--- a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/SqlppCloneAndSubstituteVariablesVisitor.java
+++ b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/SqlppCloneAndSubstituteVariablesVisitor.java
@@ -223,7 +223,7 @@
             for (LetClause letClause : selectBlock.getLetList()) {
                 newLet = letClause.accept(this, currentEnv);
                 currentEnv = newLet.second;
-                newLetClauses.add(letClause);
+                newLetClauses.add((LetClause) newLet.first);
             }
         }
 
@@ -346,7 +346,7 @@
         if (selectExpression.hasLetClauses()) {
             for (LetClause letClause : selectExpression.getLetList()) {
                 p = letClause.accept(this, currentEnv);
-                newLetList.add(letClause);
+                newLetList.add((LetClause) p.first);
                 currentEnv = p.second;
             }
         }
diff --git a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/SqlppDeleteRewriteVisitor.java b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/SqlppDeleteRewriteVisitor.java
index 4cda253..4542bab 100644
--- a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/SqlppDeleteRewriteVisitor.java
+++ b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/SqlppDeleteRewriteVisitor.java
@@ -22,7 +22,6 @@
 import java.util.Collections;
 import java.util.List;
 
-import org.apache.asterix.common.functions.FunctionConstants;
 import org.apache.asterix.common.functions.FunctionSignature;
 import org.apache.asterix.lang.common.base.Expression;
 import org.apache.asterix.lang.common.clause.WhereClause;
diff --git a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/base/AbstractSqlppExpressionScopingVisitor.java b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/base/AbstractSqlppExpressionScopingVisitor.java
index 2f9cb32..737cc53 100644
--- a/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/base/AbstractSqlppExpressionScopingVisitor.java
+++ b/asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/visitor/base/AbstractSqlppExpressionScopingVisitor.java
@@ -18,7 +18,6 @@
  */
 package org.apache.asterix.lang.sqlpp.visitor.base;
 
-import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -26,19 +25,15 @@
 import java.util.Set;
 
 import org.apache.asterix.common.exceptions.CompilationException;
-import org.apache.asterix.common.functions.FunctionSignature;
 import org.apache.asterix.lang.common.base.Expression;
 import org.apache.asterix.lang.common.base.ILangExpression;
 import org.apache.asterix.lang.common.clause.GroupbyClause;
 import org.apache.asterix.lang.common.clause.LetClause;
 import org.apache.asterix.lang.common.clause.LimitClause;
 import org.apache.asterix.lang.common.context.Scope;
-import org.apache.asterix.lang.common.expression.CallExpr;
 import org.apache.asterix.lang.common.expression.GbyVariableExpressionPair;
-import org.apache.asterix.lang.common.expression.LiteralExpr;
 import org.apache.asterix.lang.common.expression.QuantifiedExpression;
 import org.apache.asterix.lang.common.expression.VariableExpr;
-import org.apache.asterix.lang.common.literal.StringLiteral;
 import org.apache.asterix.lang.common.parser.ScopeChecker;
 import org.apache.asterix.lang.common.rewrites.LangRewritingContext;
 import org.apache.asterix.lang.common.statement.FunctionDecl;
@@ -57,7 +52,6 @@
 import org.apache.asterix.lang.sqlpp.expression.SelectExpression;
 import org.apache.asterix.lang.sqlpp.struct.SetOperationRight;
 import org.apache.asterix.lang.sqlpp.util.SqlppVariableUtil;
-import org.apache.asterix.om.functions.BuiltinFunctions;
 import org.apache.hyracks.algebricks.common.utils.Pair;
 import org.apache.hyracks.algebricks.core.algebra.base.Counter;
 
@@ -71,8 +65,23 @@
      *            manages ids of variables and guarantees uniqueness of variables.
      */
     public AbstractSqlppExpressionScopingVisitor(LangRewritingContext context) {
+        this(context, null);
+    }
+
+    /**
+     * @param context,
+     *            manages ids of variables and guarantees uniqueness of variables.
+     * @param externalVars
+     *            pre-defined (external) variables that must be added to the initial scope
+     */
+    public AbstractSqlppExpressionScopingVisitor(LangRewritingContext context, List<VarIdentifier> externalVars) {
         this.context = context;
         this.scopeChecker.setVarCounter(new Counter(context.getVarCounter()));
+        if (externalVars != null) {
+            for (VarIdentifier paramVar : externalVars) {
+                scopeChecker.getCurrentScope().addSymbolToScope(paramVar);
+            }
+        }
     }
 
     @Override
@@ -219,7 +228,7 @@
     public Expression visit(GroupbyClause gc, ILangExpression arg) throws CompilationException {
         // After a GROUP BY, variables defined before the current SELECT BLOCK (e.g., in a WITH clause
         // or an outer scope query) should still be visible.
-        Scope newScope = new Scope(scopeChecker, scopeChecker.getCurrentScope().getParentScope());
+        Scope newScope = new Scope(scopeChecker, scopeChecker.getPrecedingScope());
         // Puts all group-by variables into the symbol set of the new scope.
         for (GbyVariableExpressionPair gbyKeyVarExpr : gc.getGbyPairList()) {
             gbyKeyVarExpr.setExpr(visit(gbyKeyVarExpr.getExpr(), gc));
@@ -243,7 +252,7 @@
             }
         }
         if (gc.hasGroupVar()) {
-            addNewVarSymbolToScope(scopeChecker.getCurrentScope(), gc.getGroupVar().getVar());
+            addNewVarSymbolToScope(newScope, gc.getGroupVar().getVar());
         }
         if (gc.hasWithMap()) {
             Map<Expression, VariableExpr> newWithMap = new HashMap<>();
@@ -288,8 +297,6 @@
         // visit let list
         if (selectExpression.hasLetClauses()) {
             for (LetClause letClause : selectExpression.getLetList()) {
-                // Variables defined in WITH clauses are considered as named access instead of real variables.
-                letClause.getVarExpr().getVar().setNamedValueAccess(true);
                 letClause.accept(this, selectExpression);
             }
             scopeChecker.createNewScope();
@@ -365,17 +372,6 @@
         return null;
     }
 
-    // Rewrites for an undefined variable reference, which potentially could be a syntatic sugar.
-    protected Expression wrapWithResolveFunction(VariableExpr expr, Set<VariableExpr> liveVars)
-            throws CompilationException {
-        List<Expression> argList = new ArrayList<>();
-        //Ignore the parser-generated prefix "$" for a dataset.
-        String varName = SqlppVariableUtil.toUserDefinedVariableName(expr.getVar().getValue()).getValue();
-        argList.add(new LiteralExpr(new StringLiteral(varName)));
-        argList.addAll(liveVars);
-        return new CallExpr(new FunctionSignature(BuiltinFunctions.RESOLVE), argList);
-    }
-
     // Adds a new encountered alias identifier into a scope
     private void addNewVarSymbolToScope(Scope scope, VarIdentifier var) throws CompilationException {
         if (scope.findLocalSymbol(var.getValue()) != null) {
diff --git a/asterixdb/asterix-lang-sqlpp/src/main/javacc/SQLPP.jj b/asterixdb/asterix-lang-sqlpp/src/main/javacc/SQLPP.jj
index c5d6d26..2bf84e0 100644
--- a/asterixdb/asterix-lang-sqlpp/src/main/javacc/SQLPP.jj
+++ b/asterixdb/asterix-lang-sqlpp/src/main/javacc/SQLPP.jj
@@ -143,6 +143,7 @@
 import org.apache.asterix.lang.common.statement.UpsertStatement;
 import org.apache.asterix.lang.common.statement.WriteStatement;
 import org.apache.asterix.lang.common.struct.Identifier;
+import org.apache.asterix.lang.common.struct.OperatorType;
 import org.apache.asterix.lang.common.struct.QuantifiedPair;
 import org.apache.asterix.lang.common.struct.VarIdentifier;
 import org.apache.asterix.lang.sqlpp.clause.AbstractBinaryCorrelateClause;
@@ -1973,6 +1974,7 @@
        <AND>
        operand = IsExpr()
        {
+         op.addOperator(OperatorType.AND);
          op.addOperand(operand);
        }
     )?
diff --git a/asterixdb/asterix-om/src/main/java/org/apache/asterix/om/functions/BuiltinFunctions.java b/asterixdb/asterix-om/src/main/java/org/apache/asterix/om/functions/BuiltinFunctions.java
index e59c600..e1f5bb0 100644
--- a/asterixdb/asterix-om/src/main/java/org/apache/asterix/om/functions/BuiltinFunctions.java
+++ b/asterixdb/asterix-om/src/main/java/org/apache/asterix/om/functions/BuiltinFunctions.java
@@ -871,8 +871,6 @@
             FunctionIdentifier.VARARGS);
     public static final FunctionIdentifier META_KEY = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "meta-key",
             FunctionIdentifier.VARARGS);
-    public static final FunctionIdentifier RESOLVE = new FunctionIdentifier(FunctionConstants.ASTERIX_NS, "resolve",
-            FunctionIdentifier.VARARGS);
 
     public static IFunctionInfo getAsterixFunctionInfo(FunctionIdentifier fid) {
         return registeredFunctions.get(fid);
@@ -1184,7 +1182,7 @@
         addPrivateFunction(OPEN_RECORD_CONSTRUCTOR, OpenRecordConstructorResultType.INSTANCE, true);
         addPrivateFunction(FIELD_ACCESS_BY_INDEX, FieldAccessByIndexResultType.INSTANCE, true);
         addPrivateFunction(FIELD_ACCESS_NESTED, FieldAccessNestedResultType.INSTANCE, true);
-        addPrivateFunction(FIELD_ACCESS_BY_NAME, FieldAccessByNameResultType.INSTANCE, true);
+        addFunction(FIELD_ACCESS_BY_NAME, FieldAccessByNameResultType.INSTANCE, true);
         addFunction(GET_RECORD_FIELDS, OrderedListOfAnyTypeComputer.INSTANCE, true);
         addFunction(GET_RECORD_FIELD_VALUE, FieldAccessNestedResultType.INSTANCE, true);
         addFunction(RECORD_PAIRS, RecordPairsTypeComputer.INSTANCE, true);
@@ -1270,7 +1268,6 @@
         // meta() function
         addFunction(META, OpenARecordTypeComputer.INSTANCE, true);
         addPrivateFunction(META_KEY, AnyTypeComputer.INSTANCE, false);
-        addFunction(RESOLVE, AnyTypeComputer.INSTANCE, false);
 
         addPrivateFunction(COLLECTION_TO_SEQUENCE, CollectionToSequenceTypeComputer.INSTANCE, true);
 
diff --git a/hyracks-fullstack/algebricks/algebricks-core/src/main/java/org/apache/hyracks/algebricks/core/algebra/operators/physical/ExternalGroupByPOperator.java b/hyracks-fullstack/algebricks/algebricks-core/src/main/java/org/apache/hyracks/algebricks/core/algebra/operators/physical/ExternalGroupByPOperator.java
index 9e7daf0..eecd066 100644
--- a/hyracks-fullstack/algebricks/algebricks-core/src/main/java/org/apache/hyracks/algebricks/core/algebra/operators/physical/ExternalGroupByPOperator.java
+++ b/hyracks-fullstack/algebricks/algebricks-core/src/main/java/org/apache/hyracks/algebricks/core/algebra/operators/physical/ExternalGroupByPOperator.java
@@ -179,18 +179,23 @@
         Mutable<ILogicalOperator> r0 = p0.getRoots().get(0);
         AggregateOperator aggOp = (AggregateOperator) r0.getValue();
 
+        compileSubplans(inputSchemas[0], gby, opSchema, context);
+
         IPartialAggregationTypeComputer partialAggregationTypeComputer = context.getPartialAggregationTypeComputer();
         List<Object> intermediateTypes = new ArrayList<Object>();
         int n = aggOp.getExpressions().size();
         ISerializedAggregateEvaluatorFactory[] aff = new ISerializedAggregateEvaluatorFactory[n];
         int i = 0;
         IExpressionRuntimeProvider expressionRuntimeProvider = context.getExpressionRuntimeProvider();
-        IVariableTypeEnvironment aggOpInputEnv = context.getTypeEnvironment(aggOp.getInputs().get(0).getValue());
+        ILogicalOperator aggOpInput = aggOp.getInputs().get(0).getValue();
+        IOperatorSchema aggOpInputSchema = context.getSchema(aggOpInput);
+        IOperatorSchema[] aggOpInputSchemas = new IOperatorSchema[] { aggOpInputSchema };
+        IVariableTypeEnvironment aggOpInputEnv = context.getTypeEnvironment(aggOpInput);
         IVariableTypeEnvironment outputEnv = context.getTypeEnvironment(op);
         for (Mutable<ILogicalExpression> exprRef : aggOp.getExpressions()) {
             AggregateFunctionCallExpression aggFun = (AggregateFunctionCallExpression) exprRef.getValue();
             aff[i++] = expressionRuntimeProvider.createSerializableAggregateFunctionFactory(aggFun, aggOpInputEnv,
-                    inputSchemas, context);
+                    aggOpInputSchemas, context);
             intermediateTypes
                     .add(partialAggregationTypeComputer.getType(aggFun, aggOpInputEnv, context.getMetadataProvider()));
         }
@@ -215,7 +220,6 @@
             aggOpInputEnv.setVarType(var, outputEnv.getVarType(var));
         }
 
-        compileSubplans(inputSchemas[0], gby, opSchema, context);
         IOperatorDescriptorRegistry spec = builder.getJobSpec();
         IBinaryComparatorFactory[] comparatorFactories = JobGenHelper.variablesToAscBinaryComparatorFactories(gbyCols,
                 aggOpInputEnv, context);