You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tajo.apache.org by ji...@apache.org on 2015/07/22 11:05:42 UTC

[1/3] tajo git commit: TAJO-1343: Improve the memory usage of physical executors. (jihoon)

Repository: tajo
Updated Branches:
  refs/heads/master e5b30e542 -> 4820610f4


http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/WindowAggExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/WindowAggExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/WindowAggExec.java
index d177c48..c09e85e 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/WindowAggExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/WindowAggExec.java
@@ -35,7 +35,6 @@ import org.apache.tajo.storage.VTuple;
 import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
-import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
@@ -67,6 +66,8 @@ public class WindowAggExec extends UnaryPhysicalExec {
   private boolean [] windowFuncFlags;
   private boolean [] endUnboundedFollowingFlags;
   private boolean [] endCurrentRowFlags;
+  private Tuple currentKey;
+  private Tuple evaluatedTuple;
 
   // operator state
   enum WindowState {
@@ -79,10 +80,9 @@ public class WindowAggExec extends UnaryPhysicalExec {
 
   // Transient state
   boolean firstTime = true;
-  List<Tuple> evaluatedTuples = null;
-  List<Tuple> accumulatedInTuples = null;
-  List<Tuple> nextAccumulatedProjected = null;
-  List<Tuple> nextAccumulatedInTuples = null;
+  TupleList evaluatedTuples = null;
+  TupleList accumulatedInTuples = null;
+  TupleList nextAccumulatedInTuples = null;
   WindowState state = WindowState.NEW_WINDOW;
   Iterator<Tuple> tupleInFrameIterator = null;
 
@@ -105,6 +105,8 @@ public class WindowAggExec extends UnaryPhysicalExec {
       hasPartitionKeys = false;
     }
 
+    currentKey = new VTuple(partitionKeyNum);
+
     if (plan.hasAggFunctions()) {
       functions = plan.getWindowFunctions();
       functionNum = functions.length;
@@ -169,7 +171,7 @@ public class WindowAggExec extends UnaryPhysicalExec {
       schemaForOrderBy = outSchema;
     }
 
-
+    evaluatedTuple = new VTuple(schemaForOrderBy.size());
     nonFunctionColumnNum = plan.getTargets().length - functionNum;
     nonFunctionColumns = new int[nonFunctionColumnNum];
     for (int idx = 0; idx < plan.getTargets().length - functionNum; idx++) {
@@ -193,7 +195,6 @@ public class WindowAggExec extends UnaryPhysicalExec {
 
   @Override
   public Tuple next() throws IOException {
-    Tuple currentKey = null;
     Tuple readTuple = null;
 
     while(!context.isStopped() && state != WindowState.END_OF_TUPLE) {
@@ -212,7 +213,6 @@ public class WindowAggExec extends UnaryPhysicalExec {
         }
 
         if (readTuple != null && hasPartitionKeys) { // get a key tuple
-          currentKey = new VTuple(partitionKeyIds.length);
           for (int i = 0; i < partitionKeyIds.length; i++) {
             currentKey.put(i, readTuple.asDatum(partitionKeyIds[i]));
           }
@@ -244,7 +244,7 @@ public class WindowAggExec extends UnaryPhysicalExec {
 
   private void initWindow() {
     if (firstTime) {
-      accumulatedInTuples = Lists.newArrayList();
+      accumulatedInTuples = new TupleList();
 
       contexts = new FunctionContext[functionNum];
       for(int evalIdx = 0; evalIdx < functionNum; evalIdx++) {
@@ -257,8 +257,10 @@ public class WindowAggExec extends UnaryPhysicalExec {
   private void accumulatingWindow(Tuple currentKey, Tuple inTuple) {
 
     if (lastKey == null || lastKey.equals(currentKey)) { // if the current key is same to the previous key
-      accumulatedInTuples.add(new VTuple(inTuple));
-
+      accumulatedInTuples.add(inTuple);
+      if (lastKey == null) {
+        lastKey = new VTuple(currentKey.size());
+      }
     } else {
       // if the current key is different from the previous key,
       // the current key belongs to the next window frame. preaccumulatingNextWindow() will
@@ -267,37 +269,30 @@ public class WindowAggExec extends UnaryPhysicalExec {
       transition(WindowState.EVALUATION);
     }
 
-    lastKey = currentKey;
+    lastKey.put(currentKey.getValues());
   }
 
   private void preAccumulatingNextWindow(Tuple inTuple) {
-    Tuple projectedTuple = new VTuple(outSchema.size());
-    for(int idx = 0; idx < nonFunctionColumnNum; idx++) {
-      projectedTuple.put(idx, inTuple.asDatum(nonFunctionColumns[idx]));
-    }
-    nextAccumulatedProjected = Lists.newArrayList();
-    nextAccumulatedProjected.add(projectedTuple);
-    nextAccumulatedInTuples = Lists.newArrayList();
-    nextAccumulatedInTuples.add(new VTuple(inTuple));
+    nextAccumulatedInTuples = new TupleList();
+    nextAccumulatedInTuples.add(inTuple);
   }
 
   private void evaluationWindowFrame() {
     TupleComparator comp;
 
-    evaluatedTuples = new ArrayList<Tuple>();
+    evaluatedTuples = new TupleList();
 
     for (int i = 0; i <accumulatedInTuples.size(); i++) {
       Tuple inTuple = accumulatedInTuples.get(i);
 
-      Tuple projectedTuple = new VTuple(schemaForOrderBy.size());
       for (int c = 0; c < nonFunctionColumnNum; c++) {
-        projectedTuple.put(c, inTuple.asDatum(nonFunctionColumns[c]));
+        evaluatedTuple.put(c, inTuple.asDatum(nonFunctionColumns[c]));
       }
       for (int c = 0; c < sortKeyColumns.length; c++) {
-        projectedTuple.put(outputColumnNum + c, inTuple.asDatum(sortKeyColumns[c]));
+        evaluatedTuple.put(outputColumnNum + c, inTuple.asDatum(sortKeyColumns[c]));
       }
 
-      evaluatedTuples.add(projectedTuple);
+      evaluatedTuples.add(evaluatedTuple);
     }
 
     for (int idx = 0; idx < functions.length; idx++) {
@@ -354,4 +349,22 @@ public class WindowAggExec extends UnaryPhysicalExec {
     lastKey = null;
     noMoreTuples = false;
   }
+
+  @Override
+  public void close() throws IOException {
+    if (evaluatedTuples != null) {
+      evaluatedTuples.clear();
+      evaluatedTuples = null;
+    }
+    if (accumulatedInTuples != null) {
+      accumulatedInTuples.clear();
+      accumulatedInTuples = null;
+    }
+    if (nextAccumulatedInTuples != null) {
+      nextAccumulatedInTuples.clear();
+      nextAccumulatedInTuples = null;
+    }
+
+    super.close();
+  }
 }

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/query/QueryContext.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/query/QueryContext.java b/tajo-core/src/main/java/org/apache/tajo/engine/query/QueryContext.java
index da2f2ad..7279e8e 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/query/QueryContext.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/query/QueryContext.java
@@ -29,6 +29,8 @@ import org.apache.tajo.plan.logical.NodeType;
 import org.apache.tajo.session.Session;
 
 import java.net.URI;
+import java.util.HashMap;
+import java.util.Map;
 
 import static org.apache.tajo.rpc.protocolrecords.PrimitiveProtos.KeyValueSetProto;
 
@@ -42,7 +44,10 @@ public class QueryContext extends OverridableConf {
 
   public QueryContext(TajoConf conf, Session session) {
     super(conf, ConfigKey.ConfigType.QUERY, ConfigKey.ConfigType.SESSION);
-    putAll(session.getAllVariables());
+    Map<String, String> copy = new HashMap<String, String>(session.getAllVariables());
+    // Among session variables, timezone must not be
+    copy.remove("TIMEZONE");
+    putAll(copy);
   }
 
   public QueryContext(TajoConf conf, KeyValueSetProto proto) {

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/utils/CacheHolder.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/utils/CacheHolder.java b/tajo-core/src/main/java/org/apache/tajo/engine/utils/CacheHolder.java
index addca49..05936be 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/utils/CacheHolder.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/utils/CacheHolder.java
@@ -20,15 +20,14 @@ package org.apache.tajo.engine.utils;
 
 import org.apache.tajo.catalog.proto.CatalogProtos;
 import org.apache.tajo.catalog.statistics.TableStats;
-import org.apache.tajo.storage.Tuple;
+import org.apache.tajo.engine.planner.physical.TupleList;
+import org.apache.tajo.engine.planner.physical.TupleMap;
 import org.apache.tajo.storage.fragment.Fragment;
 import org.apache.tajo.storage.fragment.FragmentConvertor;
 import org.apache.tajo.util.Deallocatable;
 import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
-import java.util.List;
-import java.util.Map;
 
 public interface CacheHolder<T> {
 
@@ -52,19 +51,19 @@ public interface CacheHolder<T> {
    * This is a cache-holder for a join table
    * It will release when execution block is finished
    */
-  public static class BroadcastCacheHolder implements CacheHolder<Map<Tuple, List<Tuple>>> {
-    private Map<Tuple, List<Tuple>> data;
+  class BroadcastCacheHolder implements CacheHolder<TupleMap<TupleList>> {
+    private TupleMap<TupleList> data;
     private Deallocatable rowBlock;
     private TableStats tableStats;
 
-    public BroadcastCacheHolder(Map<Tuple, List<Tuple>> data, TableStats tableStats, Deallocatable rowBlock){
+    public BroadcastCacheHolder(TupleMap<TupleList> data, TableStats tableStats, Deallocatable rowBlock){
       this.data = data;
       this.tableStats = tableStats;
       this.rowBlock = rowBlock;
     }
 
     @Override
-    public Map<Tuple, List<Tuple>> getData() {
+    public TupleMap<TupleList> getData() {
       return data;
     }
 

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/utils/TupleUtil.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/utils/TupleUtil.java b/tajo-core/src/main/java/org/apache/tajo/engine/utils/TupleUtil.java
index 1dcbcab..0a04213 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/utils/TupleUtil.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/utils/TupleUtil.java
@@ -19,7 +19,6 @@
 package org.apache.tajo.engine.utils;
 
 import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import org.apache.commons.codec.binary.Base64;
 import org.apache.commons.logging.Log;
@@ -30,17 +29,13 @@ import org.apache.tajo.catalog.SortSpec;
 import org.apache.tajo.catalog.statistics.ColumnStats;
 import org.apache.tajo.datum.DatumFactory;
 import org.apache.tajo.datum.NullDatum;
-import org.apache.tajo.plan.expr.EvalNode;
 import org.apache.tajo.storage.RowStoreUtil;
 import org.apache.tajo.storage.RowStoreUtil.RowStoreEncoder;
-import org.apache.tajo.storage.Tuple;
 import org.apache.tajo.storage.TupleRange;
 import org.apache.tajo.storage.VTuple;
 
 import java.io.UnsupportedEncodingException;
 import java.net.URLEncoder;
-import java.util.Collection;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 
@@ -177,20 +172,4 @@ public class TupleUtil {
     }
     return new TupleRange(sortSpecs, startTuple, endTuple);
   }
-
-  /**
-   * It creates a tuple of a given size filled with NULL values in all fields
-   * It is usually used in outer join algorithms.
-   *
-   * @param size The number of columns of a creating tuple
-   * @return The created tuple filled with NULL values
-   */
-  public static Tuple createNullPaddedTuple(int size){
-    VTuple aTuple = new VTuple(size);
-    int i;
-    for(i = 0; i < size; i++){
-      aTuple.put(i, DatumFactory.createNullDatum());
-    }
-    return aTuple;
-  }
 }

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/master/exec/NonForwardQueryResultSystemScanner.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/master/exec/NonForwardQueryResultSystemScanner.java b/tajo-core/src/main/java/org/apache/tajo/master/exec/NonForwardQueryResultSystemScanner.java
index 52c8d79..228c0b8 100644
--- a/tajo-core/src/main/java/org/apache/tajo/master/exec/NonForwardQueryResultSystemScanner.java
+++ b/tajo-core/src/main/java/org/apache/tajo/master/exec/NonForwardQueryResultSystemScanner.java
@@ -694,8 +694,7 @@ public class NonForwardQueryResultSystemScanner implements NonForwardQueryResult
     @Override
     public Tuple next() throws IOException {
       Tuple aTuple;
-      Tuple outTuple = new VTuple(outColumnNum);
-      
+
       if (isClosed) {
         return null;
       }
@@ -707,7 +706,7 @@ public class NonForwardQueryResultSystemScanner implements NonForwardQueryResult
       if (!scanNode.hasQual()) {
         if (currentRow < cachedData.size()) {
           aTuple = cachedData.get(currentRow++);
-          projector.eval(aTuple, outTuple);
+          Tuple outTuple = projector.eval(aTuple);
           outTuple.setOffset(aTuple.getOffset());
           return outTuple;
         }
@@ -716,7 +715,8 @@ public class NonForwardQueryResultSystemScanner implements NonForwardQueryResult
         while (currentRow < cachedData.size()) {
           aTuple = cachedData.get(currentRow++);
           if (qual.eval(aTuple).isTrue()) {
-            projector.eval(aTuple, outTuple);
+            Tuple outTuple = projector.eval(aTuple);
+            outTuple.setOffset(aTuple.getOffset());
             return outTuple;
           }
         }

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/test/java/org/apache/tajo/TajoTestingCluster.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/test/java/org/apache/tajo/TajoTestingCluster.java b/tajo-core/src/test/java/org/apache/tajo/TajoTestingCluster.java
index 60349dd..25b306f 100644
--- a/tajo-core/src/test/java/org/apache/tajo/TajoTestingCluster.java
+++ b/tajo-core/src/test/java/org/apache/tajo/TajoTestingCluster.java
@@ -154,6 +154,7 @@ public class TajoTestingCluster {
     // Memory cache termination
     conf.setIntVar(ConfVars.WORKER_HISTORY_EXPIRE_PERIOD, 1);
 
+    // Python function path
     conf.setStrings(ConfVars.PYTHON_CODE_DIR.varname, getClass().getResource("/python").toString());
 
     /* Since Travis CI limits the size of standard output log up to 4MB */

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/test/java/org/apache/tajo/engine/planner/TestLogicalPlanner.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/test/java/org/apache/tajo/engine/planner/TestLogicalPlanner.java b/tajo-core/src/test/java/org/apache/tajo/engine/planner/TestLogicalPlanner.java
index c01adb5..d383662 100644
--- a/tajo-core/src/test/java/org/apache/tajo/engine/planner/TestLogicalPlanner.java
+++ b/tajo-core/src/test/java/org/apache/tajo/engine/planner/TestLogicalPlanner.java
@@ -40,6 +40,7 @@ import org.apache.tajo.engine.function.builtin.SumInt;
 import org.apache.tajo.engine.json.CoreGsonHelper;
 import org.apache.tajo.engine.parser.SQLAnalyzer;
 import org.apache.tajo.engine.query.QueryContext;
+import org.apache.tajo.plan.*;
 import org.apache.tajo.exception.TajoException;
 import org.apache.tajo.plan.LogicalOptimizer;
 import org.apache.tajo.plan.LogicalPlan;
@@ -1334,5 +1335,4 @@ public class TestLogicalPlanner {
     assertEquals(alterTableNode.getPartitionValues()[1], "01");
     assertEquals(alterTableNode.getPartitionValues()[2], "11");
   }
-
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/test/java/org/apache/tajo/engine/planner/physical/TestTupleSorter.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/test/java/org/apache/tajo/engine/planner/physical/TestTupleSorter.java b/tajo-core/src/test/java/org/apache/tajo/engine/planner/physical/TestTupleSorter.java
index ea1214e..4061b25 100644
--- a/tajo-core/src/test/java/org/apache/tajo/engine/planner/physical/TestTupleSorter.java
+++ b/tajo-core/src/test/java/org/apache/tajo/engine/planner/physical/TestTupleSorter.java
@@ -33,13 +33,7 @@ import org.apache.tajo.storage.Tuple;
 import org.apache.tajo.storage.VTuple;
 import org.junit.Test;
 
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Random;
-import java.util.Set;
-import java.util.TreeSet;
+import java.util.*;
 
 import static org.junit.Assert.assertArrayEquals;
 
@@ -80,7 +74,8 @@ public class TestTupleSorter {
     long[] time1 = new long[ITERATION];
     long[] time2 = new long[ITERATION];
     for(int iteration = 0; iteration < ITERATION; iteration++) {
-      List<Tuple> target = Arrays.asList(Arrays.copyOf(tuples, tuples.length));
+      TupleList target = new TupleList(tuples.length);
+      target.addAll(Arrays.asList(Arrays.copyOf(tuples, tuples.length)));
       Set<Integer> keys = new TreeSet<Integer>();
       for (int i = 0; i < MAX_SORT_KEY; i++) {
         keys.add(rnd.nextInt(schema.size()));

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/test/java/org/apache/tajo/engine/query/TestGroupByQuery.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/test/java/org/apache/tajo/engine/query/TestGroupByQuery.java b/tajo-core/src/test/java/org/apache/tajo/engine/query/TestGroupByQuery.java
index 3055362..a5caf38 100644
--- a/tajo-core/src/test/java/org/apache/tajo/engine/query/TestGroupByQuery.java
+++ b/tajo-core/src/test/java/org/apache/tajo/engine/query/TestGroupByQuery.java
@@ -26,8 +26,8 @@ import org.apache.tajo.common.TajoDataTypes.Type;
 import org.apache.tajo.conf.TajoConf.ConfVars;
 import org.apache.tajo.querymaster.Query;
 import org.apache.tajo.querymaster.QueryMasterTask;
-import org.apache.tajo.querymaster.Task;
 import org.apache.tajo.querymaster.Stage;
+import org.apache.tajo.querymaster.Task;
 import org.apache.tajo.storage.StorageConstants;
 import org.apache.tajo.util.KeyValueSet;
 import org.apache.tajo.util.TUtil;
@@ -565,12 +565,12 @@ public class TestGroupByQuery extends QueryTestCaseBase {
   }
 
   @Test
+  @Option(sort = true)
+  @SimpleTest
   public final void testHavingWithAggFunction() throws Exception {
     // select l_orderkey, avg(l_partkey) total, sum(l_linenumber) as num from lineitem group by l_orderkey
     // having avg(l_partkey) = 2.5 or num = 1;
-    ResultSet res = executeQuery();
-    assertResultSet(res);
-    cleanupQuery(res);
+    runSimpleTests();
   }
 
   @Test
@@ -693,6 +693,8 @@ public class TestGroupByQuery extends QueryTestCaseBase {
 
   @Test
   public final void testNumShufflePartition() throws Exception {
+
+    Thread.sleep(5000);
     KeyValueSet tableOptions = new KeyValueSet();
     tableOptions.set(StorageConstants.TEXT_DELIMITER, StorageConstants.DEFAULT_FIELD_DELIMITER);
     tableOptions.set(StorageConstants.TEXT_NULL, "\\\\N");
@@ -801,17 +803,17 @@ public class TestGroupByQuery extends QueryTestCaseBase {
   }
 
   @Test
+  @Option(sort = true)
+  @SimpleTest
   public final void testGroupbyWithPythonFunc() throws Exception {
-    ResultSet res = executeQuery();
-    assertResultSet(res);
-    cleanupQuery(res);
+    runSimpleTests();
   }
 
   @Test
+  @Option(sort = true)
+  @SimpleTest
   public final void testGroupbyWithPythonFunc2() throws Exception {
-    ResultSet res = executeQuery();
-    assertResultSet(res);
-    cleanupQuery(res);
+    runSimpleTests();
   }
 
   @Test
@@ -829,10 +831,10 @@ public class TestGroupByQuery extends QueryTestCaseBase {
   }
 
   @Test
+  @Option(sort = true)
+  @SimpleTest
   public final void testPythonUdaf3() throws Exception {
-    ResultSet res = executeQuery();
-    assertResultSet(res);
-    cleanupQuery(res);
+    runSimpleTests();
   }
 
   // TODO: this test cannot be executed due to the bug of logical planner (TAJO-1588)

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/test/resources/queries/TestGroupByQuery/testGroupbyWithJson.json
----------------------------------------------------------------------
diff --git a/tajo-core/src/test/resources/queries/TestGroupByQuery/testGroupbyWithJson.json b/tajo-core/src/test/resources/queries/TestGroupByQuery/testGroupbyWithJson.json
index 7a60c64..072cf9b 100644
--- a/tajo-core/src/test/resources/queries/TestGroupByQuery/testGroupbyWithJson.json
+++ b/tajo-core/src/test/resources/queries/TestGroupByQuery/testGroupbyWithJson.json
@@ -42,57 +42,86 @@
         }
     ],
     "Expr": {
-        "HavingCondition": {
-            "LeftExpr": {
-                "LeftExpr": {
-                    "ColumnName": "total",
+        "SortSpecs": [
+            {
+                "SortKey": {
+                    "ColumnName": "l_orderkey",
                     "OpType": "Column"
                 },
-                "RightExpr": {
-                    "Value": "2",
-                    "ValueType": "Unsigned_Integer",
-                    "OpType": "Literal"
+                "IsAsc": true,
+                "IsNullFirst": false
+            },
+            {
+                "SortKey": {
+                    "ColumnName": "total",
+                    "OpType": "Column"
                 },
-                "OpType": "GreaterThanOrEquals"
+                "IsAsc": true,
+                "IsNullFirst": false
             },
-            "RightExpr": {
-                "LeftExpr": {
+            {
+                "SortKey": {
                     "ColumnName": "num",
                     "OpType": "Column"
                 },
+                "IsAsc": true,
+                "IsNullFirst": false
+            }
+        ],
+        "Expr": {
+            "HavingCondition": {
+                "LeftExpr": {
+                    "LeftExpr": {
+                        "ColumnName": "total",
+                        "OpType": "Column"
+                    },
+                    "RightExpr": {
+                        "Value": "2",
+                        "ValueType": "Unsigned_Integer",
+                        "OpType": "Literal"
+                    },
+                    "OpType": "GreaterThanOrEquals"
+                },
                 "RightExpr": {
-                    "Value": "3",
-                    "ValueType": "Unsigned_Integer",
-                    "OpType": "Literal"
+                    "LeftExpr": {
+                        "ColumnName": "num",
+                        "OpType": "Column"
+                    },
+                    "RightExpr": {
+                        "Value": "3",
+                        "ValueType": "Unsigned_Integer",
+                        "OpType": "Literal"
+                    },
+                    "OpType": "Equals"
                 },
-                "OpType": "Equals"
+                "OpType": "Or"
             },
-            "OpType": "Or"
-        },
-        "Expr": {
-            "Groups": [
-                {
-                    "GroupType": "OrdinaryGroup",
-                    "Dimensions": [
-                        {
-                            "ColumnName": "l_orderkey",
-                            "OpType": "Column"
-                        }
-                    ]
-                }
-            ],
             "Expr": {
-                "Relations": [
+                "Groups": [
                     {
-                        "TableName": "lineitem",
-                        "OpType": "Relation"
+                        "GroupType": "OrdinaryGroup",
+                        "Dimensions": [
+                            {
+                                "ColumnName": "l_orderkey",
+                                "OpType": "Column"
+                            }
+                        ]
                     }
                 ],
-                "OpType": "RelationList"
+                "Expr": {
+                    "Relations": [
+                        {
+                            "TableName": "lineitem",
+                            "OpType": "Relation"
+                        }
+                    ],
+                    "OpType": "RelationList"
+                },
+                "OpType": "Aggregation"
             },
-            "OpType": "Aggregation"
+            "OpType": "Having"
         },
-        "OpType": "Having"
+        "OpType": "Sort"
     },
     "OpType": "Projection"
-}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/test/resources/queries/TestGroupByQuery/testGroupbyWithLimit3.sql
----------------------------------------------------------------------
diff --git a/tajo-core/src/test/resources/queries/TestGroupByQuery/testGroupbyWithLimit3.sql b/tajo-core/src/test/resources/queries/TestGroupByQuery/testGroupbyWithLimit3.sql
index 1bb7c7f..fd1e5fb 100644
--- a/tajo-core/src/test/resources/queries/TestGroupByQuery/testGroupbyWithLimit3.sql
+++ b/tajo-core/src/test/resources/queries/TestGroupByQuery/testGroupbyWithLimit3.sql
@@ -1 +1 @@
-select l_orderkey, sum(l_linenumber) from lineitem group by l_orderkey limit 1;
\ No newline at end of file
+select l_orderkey, sum(l_linenumber) from lineitem group by l_orderkey order by l_orderkey limit 1;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/test/resources/queries/TestSelectNestedRecord/testNestedFieldAsGroupbyKey1.sql
----------------------------------------------------------------------
diff --git a/tajo-core/src/test/resources/queries/TestSelectNestedRecord/testNestedFieldAsGroupbyKey1.sql b/tajo-core/src/test/resources/queries/TestSelectNestedRecord/testNestedFieldAsGroupbyKey1.sql
index 057ba05..c19e69e 100644
--- a/tajo-core/src/test/resources/queries/TestSelectNestedRecord/testNestedFieldAsGroupbyKey1.sql
+++ b/tajo-core/src/test/resources/queries/TestSelectNestedRecord/testNestedFieldAsGroupbyKey1.sql
@@ -4,4 +4,6 @@ SELECT
 FROM
   tweets
 GROUP BY
+  user.name
+order by
   user.name;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithJson.result
----------------------------------------------------------------------
diff --git a/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithJson.result b/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithJson.result
index 366b76e..81f1bfd 100644
--- a/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithJson.result
+++ b/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithJson.result
@@ -1,5 +1,5 @@
 l_orderkey,total,num
 -------------------------------
-3,2.5,3
+1,1.0,3
 2,2.0,1
-1,1.0,3
\ No newline at end of file
+3,2.5,3
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithLimit3.result
----------------------------------------------------------------------
diff --git a/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithLimit3.result b/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithLimit3.result
index cb1e141..e882158 100644
--- a/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithLimit3.result
+++ b/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithLimit3.result
@@ -1,3 +1,3 @@
 l_orderkey,?sum
 -------------------------------
-3,3
\ No newline at end of file
+1,3
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithPythonFunc.result
----------------------------------------------------------------------
diff --git a/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithPythonFunc.result b/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithPythonFunc.result
index 2a5fb8a..1e8821c 100644
--- a/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithPythonFunc.result
+++ b/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithPythonFunc.result
@@ -1,7 +1,7 @@
 ?count
 -------------------------------
 4
+4
 5
 5
 5
-4
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithPythonFunc2.result
----------------------------------------------------------------------
diff --git a/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithPythonFunc2.result b/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithPythonFunc2.result
index 08561fd..1413e41 100644
--- a/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithPythonFunc2.result
+++ b/tajo-core/src/test/resources/results/TestGroupByQuery/testGroupbyWithPythonFunc2.result
@@ -1,7 +1,7 @@
 n_regionkey,cnt
 -------------------------------
 0,5
+1,5
+2,5
 3,5
 4,5
-2,5
-1,5
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/test/resources/results/TestGroupByQuery/testHavingWithAggFunction.result
----------------------------------------------------------------------
diff --git a/tajo-core/src/test/resources/results/TestGroupByQuery/testHavingWithAggFunction.result b/tajo-core/src/test/resources/results/TestGroupByQuery/testHavingWithAggFunction.result
index b8369d2..fcd604e 100644
--- a/tajo-core/src/test/resources/results/TestGroupByQuery/testHavingWithAggFunction.result
+++ b/tajo-core/src/test/resources/results/TestGroupByQuery/testHavingWithAggFunction.result
@@ -1,4 +1,4 @@
 l_orderkey,total,num
 -------------------------------
+2,2.0,1
 3,2.5,3
-2,2.0,1
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/test/resources/results/TestGroupByQuery/testPythonUdaf3.result
----------------------------------------------------------------------
diff --git a/tajo-core/src/test/resources/results/TestGroupByQuery/testPythonUdaf3.result b/tajo-core/src/test/resources/results/TestGroupByQuery/testPythonUdaf3.result
index 0607720..7338988 100644
--- a/tajo-core/src/test/resources/results/TestGroupByQuery/testPythonUdaf3.result
+++ b/tajo-core/src/test/resources/results/TestGroupByQuery/testPythonUdaf3.result
@@ -1,5 +1,5 @@
 ?avgpy,?countpy_1,?avg_2,?count_3
 -------------------------------
+173665.47,1,173665.47,1
 193846.25,1,193846.25,1
 46929.18,1,46929.18,1
-173665.47,1,173665.47,1
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/test/resources/results/TestSelectNestedRecord/testNestedFieldAsGroupbyKey1.result
----------------------------------------------------------------------
diff --git a/tajo-core/src/test/resources/results/TestSelectNestedRecord/testNestedFieldAsGroupbyKey1.result b/tajo-core/src/test/resources/results/TestSelectNestedRecord/testNestedFieldAsGroupbyKey1.result
index debf06e..d881f87 100644
--- a/tajo-core/src/test/resources/results/TestSelectNestedRecord/testNestedFieldAsGroupbyKey1.result
+++ b/tajo-core/src/test/resources/results/TestSelectNestedRecord/testNestedFieldAsGroupbyKey1.result
@@ -1,6 +1,6 @@
 user/name,total_retweet
 -------------------------------
 Chaz Martenstein,2
-Thomas John Wakeman,3
+Marty Elmer,4
 Sean Cummings,1
-Marty Elmer,4
\ No newline at end of file
+Thomas John Wakeman,3
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/test/resources/results/TestWindowQuery/testWindowWithAggregation4.result
----------------------------------------------------------------------
diff --git a/tajo-core/src/test/resources/results/TestWindowQuery/testWindowWithAggregation4.result b/tajo-core/src/test/resources/results/TestWindowQuery/testWindowWithAggregation4.result
index c34577c..fffa2dd 100644
--- a/tajo-core/src/test/resources/results/TestWindowQuery/testWindowWithAggregation4.result
+++ b/tajo-core/src/test/resources/results/TestWindowQuery/testWindowWithAggregation4.result
@@ -1,5 +1,5 @@
 l_orderkey,cnt,row_num
 -------------------------------
-3,2,1
-1,2,2
+1,2,1
+3,2,2
 2,1,3
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/test/resources/results/TestWindowQuery/testWindowWithAggregation6.result
----------------------------------------------------------------------
diff --git a/tajo-core/src/test/resources/results/TestWindowQuery/testWindowWithAggregation6.result b/tajo-core/src/test/resources/results/TestWindowQuery/testWindowWithAggregation6.result
index 7dd39ac..c2e02d5 100644
--- a/tajo-core/src/test/resources/results/TestWindowQuery/testWindowWithAggregation6.result
+++ b/tajo-core/src/test/resources/results/TestWindowQuery/testWindowWithAggregation6.result
@@ -1,5 +1,5 @@
 l_orderkey,cnt,row_num
 -------------------------------
-1,2,2
+1,2,1
 2,1,3
-3,2,1
\ No newline at end of file
+3,2,2
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-jdbc/src/main/java/org/apache/tajo/jdbc/MetaDataTuple.java
----------------------------------------------------------------------
diff --git a/tajo-jdbc/src/main/java/org/apache/tajo/jdbc/MetaDataTuple.java b/tajo-jdbc/src/main/java/org/apache/tajo/jdbc/MetaDataTuple.java
index 9ae1837..fad285c 100644
--- a/tajo-jdbc/src/main/java/org/apache/tajo/jdbc/MetaDataTuple.java
+++ b/tajo-jdbc/src/main/java/org/apache/tajo/jdbc/MetaDataTuple.java
@@ -93,6 +93,11 @@ public class MetaDataTuple implements Tuple {
   }
 
   @Override
+  public void clearOffset() {
+    throw new UnsupportedException("clearOffset");
+  }
+
+  @Override
   public Datum asDatum(int fieldId) {
     return values.get(fieldId);
   }

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-plan/src/main/java/org/apache/tajo/plan/LogicalPlanner.java
----------------------------------------------------------------------
diff --git a/tajo-plan/src/main/java/org/apache/tajo/plan/LogicalPlanner.java b/tajo-plan/src/main/java/org/apache/tajo/plan/LogicalPlanner.java
index 5011d87..4a208c2 100644
--- a/tajo-plan/src/main/java/org/apache/tajo/plan/LogicalPlanner.java
+++ b/tajo-plan/src/main/java/org/apache/tajo/plan/LogicalPlanner.java
@@ -1299,7 +1299,7 @@ public class LogicalPlanner extends BaseAlgebraVisitor<LogicalPlanner.PlanContex
     QueryBlock block = context.queryBlock;
 
     ScanNode scanNode = block.getNodeFromExpr(expr);
-    updatePhysicalInfo(scanNode.getTableDesc());
+    updatePhysicalInfo(context, scanNode.getTableDesc());
 
     // Find expression which can be evaluated at this relation node.
     // Except for column references, additional expressions used in select list, where clause, order-by clauses
@@ -1358,12 +1358,12 @@ public class LogicalPlanner extends BaseAlgebraVisitor<LogicalPlanner.PlanContex
     return targets;
   }
 
-  private void updatePhysicalInfo(TableDesc desc) {
+  private void updatePhysicalInfo(PlanContext planContext, TableDesc desc) {
     if (desc.getUri() != null &&
         desc.getMeta().getStoreType() != "SYSTEM" && PlannerUtil.isFileStorageType(desc.getMeta().getStoreType())) {
       try {
         Path path = new Path(desc.getUri());
-        FileSystem fs = path.getFileSystem(new Configuration());
+        FileSystem fs = path.getFileSystem(planContext.queryContext.getConf());
         FileStatus status = fs.getFileStatus(path);
         if (desc.getStats() != null && (status.isDirectory() || status.isFile())) {
           ContentSummary summary = fs.getContentSummary(path);

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-plan/src/main/java/org/apache/tajo/plan/TablePropertyUtil.java
----------------------------------------------------------------------
diff --git a/tajo-plan/src/main/java/org/apache/tajo/plan/TablePropertyUtil.java b/tajo-plan/src/main/java/org/apache/tajo/plan/TablePropertyUtil.java
index 5576889..2fe0cbe 100644
--- a/tajo-plan/src/main/java/org/apache/tajo/plan/TablePropertyUtil.java
+++ b/tajo-plan/src/main/java/org/apache/tajo/plan/TablePropertyUtil.java
@@ -44,8 +44,6 @@ public class TablePropertyUtil {
     if (storeType.equalsIgnoreCase("CSV") || storeType.equalsIgnoreCase("TEXT")) {
       setSessionToProperty(context, SessionVars.NULL_CHAR, property, StorageConstants.TEXT_NULL);
     }
-
-    setSessionToProperty(context, SessionVars.TIMEZONE, property, StorageConstants.TIMEZONE);
   }
 
   private static void setSessionToProperty(OverridableConf context,

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/storage/FrameTuple.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/storage/FrameTuple.java b/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/storage/FrameTuple.java
index ed53832..de39d08 100644
--- a/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/storage/FrameTuple.java
+++ b/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/storage/FrameTuple.java
@@ -125,6 +125,11 @@ public class FrameTuple implements Tuple, Cloneable {
   }
 
   @Override
+  public void clearOffset() {
+    throw new UnsupportedException();
+  }
+
+  @Override
   public void setOffset(long offset) {
     throw new UnsupportedException();
   }

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/storage/LazyTuple.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/storage/LazyTuple.java b/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/storage/LazyTuple.java
index 7bfc166..d4597fa 100644
--- a/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/storage/LazyTuple.java
+++ b/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/storage/LazyTuple.java
@@ -29,6 +29,7 @@ import org.apache.tajo.util.datetime.TimeMeta;
 
 import java.util.Arrays;
 
+@Deprecated
 public class LazyTuple implements Tuple, Cloneable {
   private long offset;
   private Datum[] values;
@@ -122,6 +123,11 @@ public class LazyTuple implements Tuple, Cloneable {
     return get(fieldId).size();
   }
 
+  @Override
+  public void clearOffset() {
+    this.offset = -1;
+  }
+
   //////////////////////////////////////////////////////
   // Getter
   //////////////////////////////////////////////////////

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/storage/RowStoreUtil.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/storage/RowStoreUtil.java b/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/storage/RowStoreUtil.java
index ba9f873..51cedb2 100644
--- a/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/storage/RowStoreUtil.java
+++ b/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/storage/RowStoreUtil.java
@@ -45,7 +45,7 @@ public class RowStoreUtil {
   }
 
   public static Tuple project(Tuple in, Tuple out, int[] targetIds) {
-    out.clear();
+    out.clearOffset();
     for (int idx = 0; idx < targetIds.length; idx++) {
       out.put(idx, in.asDatum(targetIds[idx]));
     }

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/tuple/offheap/HeapTuple.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/tuple/offheap/HeapTuple.java b/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/tuple/offheap/HeapTuple.java
index 1f43ef8..8f36b35 100644
--- a/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/tuple/offheap/HeapTuple.java
+++ b/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/tuple/offheap/HeapTuple.java
@@ -65,6 +65,10 @@ public class HeapTuple implements Tuple {
     return UNSAFE.getInt(data, BASE_OFFSET + checkNullAndGetOffset(fieldId));
   }
 
+  @Override
+  public void clearOffset() {
+  }
+
   public ByteBuffer nioBuffer() {
     return ByteBuffer.wrap(data);
   }

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/tuple/offheap/UnSafeTuple.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/tuple/offheap/UnSafeTuple.java b/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/tuple/offheap/UnSafeTuple.java
index e7bd2aa..4ccba7b 100644
--- a/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/tuple/offheap/UnSafeTuple.java
+++ b/tajo-storage/tajo-storage-common/src/main/java/org/apache/tajo/tuple/offheap/UnSafeTuple.java
@@ -186,6 +186,10 @@ public abstract class UnSafeTuple implements Tuple {
   }
 
   @Override
+  public void clearOffset() {
+  }
+
+  @Override
   public void setOffset(long offset) {
   }
 

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-hbase/src/main/java/org/apache/tajo/storage/hbase/HBaseScanner.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-hbase/src/main/java/org/apache/tajo/storage/hbase/HBaseScanner.java b/tajo-storage/tajo-storage-hbase/src/main/java/org/apache/tajo/storage/hbase/HBaseScanner.java
index 11851ec..1626526 100644
--- a/tajo-storage/tajo-storage-hbase/src/main/java/org/apache/tajo/storage/hbase/HBaseScanner.java
+++ b/tajo-storage/tajo-storage-hbase/src/main/java/org/apache/tajo/storage/hbase/HBaseScanner.java
@@ -85,6 +85,8 @@ public class HBaseScanner implements Scanner {
   private int[] rowKeyFieldIndexes;
   private char rowKeyDelimiter;
 
+  private Tuple outTuple;
+
   public HBaseScanner (Configuration conf, Schema schema, TableMeta meta, Fragment fragment) throws IOException {
     Preconditions.checkNotNull(conf);
     Preconditions.checkNotNull(schema);
@@ -119,6 +121,8 @@ public class HBaseScanner implements Scanner {
       targets = schema.toArray();
     }
 
+    outTuple = new VTuple(targets.length);
+
     columnMapping = new ColumnMapping(schema, meta.getOptions());
     targetIndexes = new int[targets.length];
     int index = 0;
@@ -206,12 +210,11 @@ public class HBaseScanner implements Scanner {
     }
 
     Result result = scanResults[scanResultIndex++];
-    Tuple resultTuple = new VTuple(targetIndexes.length);
     for (int i = 0; i < targetIndexes.length; i++) {
-      resultTuple.put(i, getDatum(result, targetIndexes[i]));
+      outTuple.put(i, getDatum(result, targetIndexes[i]));
     }
     numRows++;
-    return resultTuple;
+    return outTuple;
   }
 
   private Datum getDatum(Result result, int fieldId) throws IOException {

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/CSVFile.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/CSVFile.java b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/CSVFile.java
index 8b8ca76..e55e34b 100644
--- a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/CSVFile.java
+++ b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/CSVFile.java
@@ -18,12 +18,14 @@
 
 package org.apache.tajo.storage;
 
+import io.netty.buffer.ByteBuf;
 import org.apache.commons.lang.StringEscapeUtils;
 import org.apache.commons.lang.StringUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.*;
+import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.io.IOUtils;
 import org.apache.hadoop.io.Text;
 import org.apache.hadoop.io.compress.*;
@@ -40,8 +42,10 @@ import org.apache.tajo.storage.compress.CodecPool;
 import org.apache.tajo.storage.exception.AlreadyExistsStorageException;
 import org.apache.tajo.storage.fragment.Fragment;
 import org.apache.tajo.storage.rcfile.NonSyncByteArrayOutputStream;
+import org.apache.tajo.storage.text.ByteBufLineReader;
+import org.apache.tajo.storage.text.DelimitedTextFile;
+import org.apache.tajo.storage.text.TextLineDeserializer;
 import org.apache.tajo.util.Bytes;
-import org.apache.tajo.util.BytesUtils;
 
 import java.io.*;
 import java.util.ArrayList;
@@ -50,7 +54,6 @@ import java.util.Arrays;
 public class CSVFile {
 
   public static final byte LF = '\n';
-  public static int EOF = -1;
 
   private static final Log LOG = LogFactory.getLog(CSVFile.class);
 
@@ -262,26 +265,9 @@ public class CSVFile {
       if (codec == null || codec instanceof SplittableCompressionCodec) {
         splittable = true;
       }
-
-      //Delimiter
-      this.delimiter = StringEscapeUtils.unescapeJava(
-          meta.getOption(StorageConstants.TEXT_DELIMITER,
-          meta.getOption(StorageConstants.CSVFILE_DELIMITER, StorageConstants.DEFAULT_FIELD_DELIMITER)))
-          .getBytes(Bytes.UTF8_CHARSET);
-
-      String nullCharacters = StringEscapeUtils.unescapeJava(
-          meta.getOption(StorageConstants.TEXT_NULL,
-          meta.getOption(StorageConstants.CSVFILE_NULL, NullDatum.DEFAULT_TEXT)));
-
-      if (StringUtils.isEmpty(nullCharacters)) {
-        nullChars = NullDatum.get().asTextBytes();
-      } else {
-        nullChars = nullCharacters.getBytes(Bytes.UTF8_CHARSET);
-      }
     }
 
     private final static int DEFAULT_PAGE_SIZE = 256 * 1024;
-    private byte[] delimiter;
     private FileSystem fs;
     private FSDataInputStream fis;
     private InputStream is; //decompressd stream
@@ -294,13 +280,14 @@ public class CSVFile {
     private int currentIdx = 0, validIdx = 0, recordCount = 0;
     private int[] targetColumnIndexes;
     private boolean eof = false;
-    private final byte[] nullChars;
     private SplitLineReader reader;
     private ArrayList<Long> fileOffsets;
     private ArrayList<Integer> rowLengthList;
     private ArrayList<Integer> startOffsets;
     private NonSyncByteArrayOutputStream buffer;
-    private SerializerDeserializer serde;
+    private Tuple outTuple;
+    private TextLineDeserializer deserializer;
+    private ByteBuf byteBuf = BufferPool.directBuffer(ByteBufLineReader.DEFAULT_BUFFER);
 
     @Override
     public void init() throws IOException {
@@ -347,22 +334,15 @@ public class CSVFile {
         targets = schema.toArray();
       }
 
+      outTuple = new VTuple(targets.length);
+      deserializer = DelimitedTextFile.getLineSerde(meta).createDeserializer(schema, meta, targets);
+      deserializer.init();
+
       targetColumnIndexes = new int[targets.length];
       for (int i = 0; i < targets.length; i++) {
         targetColumnIndexes[i] = schema.getColumnId(targets[i].getQualifiedName());
       }
 
-      try {
-        //FIXME
-        String serdeClass = this.meta.getOption(StorageConstants.CSVFILE_SERDE,
-            TextSerializerDeserializer.class.getName());
-        serde = (SerializerDeserializer) Class.forName(serdeClass).newInstance();
-        serde.init(schema);
-      } catch (Exception e) {
-        LOG.error(e.getMessage(), e);
-        throw new IOException(e);
-      }
-
       super.init();
       Arrays.sort(targetColumnIndexes);
       if (LOG.isDebugEnabled()) {
@@ -396,7 +376,7 @@ public class CSVFile {
     }
 
     private void page() throws IOException {
-//      // Index initialization
+      // Index initialization
       currentIdx = 0;
       validIdx = 0;
       int currentBufferPos = 0;
@@ -473,15 +453,13 @@ public class CSVFile {
           }
         }
 
-        long offset = -1;
-        if(!isCompress()){
-          offset = fileOffsets.get(currentIdx);
-        }
+        byteBuf.clear();
+        byteBuf.writeBytes(buffer.getData(), startOffsets.get(currentIdx), rowLengthList.get(currentIdx));
+
+        deserializer.deserialize(byteBuf, outTuple);
 
-        byte[][] cells = BytesUtils.splitPreserveAllTokens(buffer.getData(), startOffsets.get(currentIdx),
-            rowLengthList.get(currentIdx), delimiter, targetColumnIndexes, schema.size());
         currentIdx++;
-        return new LazyTuple(schema, cells, offset, nullChars, serde);
+        return outTuple;
       } catch (Throwable t) {
         LOG.error("Tuple list length: " + (fileOffsets != null ? fileOffsets.size() : 0), t);
         LOG.error("Tuple list current index: " + currentIdx, t);
@@ -523,12 +501,16 @@ public class CSVFile {
           CodecPool.returnDecompressor(decompressor);
           decompressor = null;
         }
+        outTuple = null;
+        if (this.byteBuf.refCnt() > 0) {
+          this.byteBuf.release();
+        }
       }
     }
 
     @Override
     public boolean isProjectable() {
-      return false;
+      return true;
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/RawFile.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/RawFile.java b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/RawFile.java
index 3b655be..e3594f9 100644
--- a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/RawFile.java
+++ b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/RawFile.java
@@ -58,7 +58,7 @@ public class RawFile {
 
     private ByteBuffer buffer;
     private ByteBuf buf;
-    private Tuple tuple;
+    private Tuple outTuple;
 
     private int headerSize = 0; // Header size of a tuple
     private BitArray nullFlags;
@@ -105,7 +105,7 @@ public class RawFile {
         columnTypes[i] = schema.getColumn(i).getDataType();
       }
 
-      tuple = new VTuple(columnTypes.length);
+      outTuple = new VTuple(columnTypes.length);
       nullFlags = new BitArray(schema.size());
       headerSize = RECORD_SIZE + 2 + nullFlags.bytesLength(); // The middle 2 bytes is for NullFlagSize
 
@@ -274,51 +274,51 @@ public class RawFile {
       for (int i = 0; i < columnTypes.length; i++) {
         // check if the i'th column is null
         if (nullFlags.get(i)) {
-          tuple.put(i, DatumFactory.createNullDatum());
+          outTuple.put(i, DatumFactory.createNullDatum());
           continue;
         }
 
         switch (columnTypes[i].getType()) {
           case BOOLEAN :
-            tuple.put(i, DatumFactory.createBool(buffer.get()));
+            outTuple.put(i, DatumFactory.createBool(buffer.get()));
             break;
 
           case BIT :
-            tuple.put(i, DatumFactory.createBit(buffer.get()));
+            outTuple.put(i, DatumFactory.createBit(buffer.get()));
             break;
 
           case CHAR :
             int realLen = readRawVarint32();
             byte[] buf = new byte[realLen];
             buffer.get(buf);
-            tuple.put(i, DatumFactory.createChar(buf));
+            outTuple.put(i, DatumFactory.createChar(buf));
             break;
 
           case INT2 :
-            tuple.put(i, DatumFactory.createInt2(buffer.getShort()));
+            outTuple.put(i, DatumFactory.createInt2(buffer.getShort()));
             break;
 
           case INT4 :
-            tuple.put(i, DatumFactory.createInt4(decodeZigZag32(readRawVarint32())));
+            outTuple.put(i, DatumFactory.createInt4(decodeZigZag32(readRawVarint32())));
             break;
 
           case INT8 :
-            tuple.put(i, DatumFactory.createInt8(decodeZigZag64(readRawVarint64())));
+            outTuple.put(i, DatumFactory.createInt8(decodeZigZag64(readRawVarint64())));
             break;
 
           case FLOAT4 :
-            tuple.put(i, DatumFactory.createFloat4(buffer.getFloat()));
+            outTuple.put(i, DatumFactory.createFloat4(buffer.getFloat()));
             break;
 
           case FLOAT8 :
-            tuple.put(i, DatumFactory.createFloat8(buffer.getDouble()));
+            outTuple.put(i, DatumFactory.createFloat8(buffer.getDouble()));
             break;
 
           case TEXT : {
             int len = readRawVarint32();
             byte [] strBytes = new byte[len];
             buffer.get(strBytes);
-            tuple.put(i, DatumFactory.createText(strBytes));
+            outTuple.put(i, DatumFactory.createText(strBytes));
             break;
           }
 
@@ -326,7 +326,7 @@ public class RawFile {
             int len = readRawVarint32();
             byte [] rawBytes = new byte[len];
             buffer.get(rawBytes);
-            tuple.put(i, DatumFactory.createBlob(rawBytes));
+            outTuple.put(i, DatumFactory.createBlob(rawBytes));
             break;
           }
 
@@ -338,22 +338,22 @@ public class RawFile {
             ProtobufDatumFactory factory = ProtobufDatumFactory.get(columnTypes[i]);
             Message.Builder builder = factory.newBuilder();
             builder.mergeFrom(rawBytes);
-            tuple.put(i, factory.createDatum(builder.build()));
+            outTuple.put(i, factory.createDatum(builder.build()));
             break;
           }
 
           case INET4 :
             byte [] ipv4Bytes = new byte[4];
             buffer.get(ipv4Bytes);
-            tuple.put(i, DatumFactory.createInet4(ipv4Bytes));
+            outTuple.put(i, DatumFactory.createInet4(ipv4Bytes));
             break;
 
           case DATE: {
             int val = buffer.getInt();
             if (val < Integer.MIN_VALUE + 1) {
-              tuple.put(i, DatumFactory.createNullDatum());
+              outTuple.put(i, DatumFactory.createNullDatum());
             } else {
-              tuple.put(i, DatumFactory.createFromInt4(columnTypes[i], val));
+              outTuple.put(i, DatumFactory.createFromInt4(columnTypes[i], val));
             }
             break;
           }
@@ -361,14 +361,14 @@ public class RawFile {
           case TIMESTAMP: {
             long val = buffer.getLong();
             if (val < Long.MIN_VALUE + 1) {
-              tuple.put(i, DatumFactory.createNullDatum());
+              outTuple.put(i, DatumFactory.createNullDatum());
             } else {
-              tuple.put(i, DatumFactory.createFromInt8(columnTypes[i], val));
+              outTuple.put(i, DatumFactory.createFromInt8(columnTypes[i], val));
             }
             break;
           }
           case NULL_TYPE:
-            tuple.put(i, NullDatum.get());
+            outTuple.put(i, NullDatum.get());
             break;
 
           default:
@@ -380,7 +380,7 @@ public class RawFile {
       if(filePosition - buffer.remaining() >= endOffset){
         eos = true;
       }
-      return new VTuple(tuple);
+      return outTuple;
     }
 
     private void reSizeBuffer(int writableBytes){

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/RowFile.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/RowFile.java b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/RowFile.java
index 2be2ec0..ef597ea 100644
--- a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/RowFile.java
+++ b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/RowFile.java
@@ -119,6 +119,8 @@ public class RowFile {
         buffer.flip();
       }
 
+      tuple = new VTuple(schema.size());
+
       super.init();
     }
 
@@ -182,7 +184,6 @@ public class RowFile {
       }
 
       int i;
-      tuple = new VTuple(schema.size());
 
       int nullFlagSize = buffer.getShort();
       byte[] nullFlagBytes = new byte[nullFlagSize];

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/avro/AvroScanner.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/avro/AvroScanner.java b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/avro/AvroScanner.java
index 729c237..217acba 100644
--- a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/avro/AvroScanner.java
+++ b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/avro/AvroScanner.java
@@ -54,6 +54,7 @@ public class AvroScanner extends FileScanner {
   private List<Schema.Field> avroFields;
   private DataFileReader<GenericRecord> dataFileReader;
   private int[] projectionMap;
+  private Tuple outTuple;
 
   /**
    * Creates a new AvroScanner.
@@ -78,6 +79,7 @@ public class AvroScanner extends FileScanner {
       targets = schema.toArray();
     }
     prepareProjection(targets);
+    outTuple = new VTuple(projectionMap.length);
 
     avroSchema = AvroUtil.getAvroSchema(meta, conf);
     avroFields = avroSchema.getFields();
@@ -176,13 +178,12 @@ public class AvroScanner extends FileScanner {
       return null;
     }
 
-    Tuple tuple = new VTuple(projectionMap.length);
     GenericRecord record = dataFileReader.next();
     for (int i = 0; i < projectionMap.length; ++i) {
       int columnIndex = projectionMap[i];
       Object value = record.get(columnIndex);
       if (value == null) {
-        tuple.put(i, NullDatum.get());
+        outTuple.put(i, NullDatum.get());
         continue;
       }
 
@@ -197,28 +198,28 @@ public class AvroScanner extends FileScanner {
       TajoDataTypes.Type tajoType = dataType.getType();
       switch (avroType) {
         case NULL:
-          tuple.put(i, NullDatum.get());
+          outTuple.put(i, NullDatum.get());
           break;
         case BOOLEAN:
-          tuple.put(i, DatumFactory.createBool((Boolean)value));
+          outTuple.put(i, DatumFactory.createBool((Boolean) value));
           break;
         case INT:
-          tuple.put(i, convertInt(value, tajoType));
+          outTuple.put(i, convertInt(value, tajoType));
           break;
         case LONG:
-          tuple.put(i, DatumFactory.createInt8((Long)value));
+          outTuple.put(i, DatumFactory.createInt8((Long) value));
           break;
         case FLOAT:
-          tuple.put(i, DatumFactory.createFloat4((Float)value));
+          outTuple.put(i, DatumFactory.createFloat4((Float) value));
           break;
         case DOUBLE:
-          tuple.put(i, DatumFactory.createFloat8((Double)value));
+          outTuple.put(i, DatumFactory.createFloat8((Double) value));
           break;
         case BYTES:
-          tuple.put(i, convertBytes(value, tajoType, dataType));
+          outTuple.put(i, convertBytes(value, tajoType, dataType));
           break;
         case STRING:
-          tuple.put(i, convertString(value, tajoType));
+          outTuple.put(i, convertString(value, tajoType));
           break;
         case RECORD:
           throw new RuntimeException("Avro RECORD not supported.");
@@ -229,13 +230,13 @@ public class AvroScanner extends FileScanner {
         case UNION:
           throw new RuntimeException("Avro UNION not supported.");
         case FIXED:
-          tuple.put(i, new BlobDatum(((GenericFixed)value).bytes()));
+          outTuple.put(i, new BlobDatum(((GenericFixed) value).bytes()));
           break;
         default:
           throw new RuntimeException("Unknown type.");
       }
     }
-    return tuple;
+    return outTuple;
   }
 
   /**
@@ -253,6 +254,7 @@ public class AvroScanner extends FileScanner {
     if (dataFileReader != null) {
       dataFileReader.close();
     }
+    outTuple = null;
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/index/bst/BSTIndex.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/index/bst/BSTIndex.java b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/index/bst/BSTIndex.java
index 81a1ffd..ba81c3e 100644
--- a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/index/bst/BSTIndex.java
+++ b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/index/bst/BSTIndex.java
@@ -126,15 +126,21 @@ public class BSTIndex implements IndexMethod {
     }
 
     @Override
-    public void write(Tuple key, long offset) throws IOException {
-      if (firstKey == null || compartor.compare(key, firstKey) < 0) {
-        firstKey = key;
+    public void write(final Tuple key, final long offset) throws IOException {
+      Tuple keyTuple;
+      try {
+        keyTuple = key.clone();
+      } catch (CloneNotSupportedException e) {
+        throw new IOException(e);
+      }
+      if (firstKey == null || compartor.compare(keyTuple, firstKey) < 0) {
+        firstKey = keyTuple;
       }
-      if (lastKey == null || compartor.compare(lastKey, key) < 0) {
-        lastKey = key;
+      if (lastKey == null || compartor.compare(lastKey, keyTuple) < 0) {
+        lastKey = keyTuple;
       }
 
-      collector.put(key, offset);
+      collector.put(keyTuple, offset);
     }
 
     public TupleComparator getComparator() {
@@ -253,7 +259,7 @@ public class BSTIndex implements IndexMethod {
         map = new TreeMap<Tuple, LinkedList<Long>>(comparator);
       }
 
-      public void put(Tuple key, long offset) {
+      public void put(final Tuple key, final long offset) {
         if (map.containsKey(key)) {
           map.get(key).add(offset);
         } else {

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/rcfile/RCFile.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/rcfile/RCFile.java b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/rcfile/RCFile.java
index 286ee3a..47d0267 100644
--- a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/rcfile/RCFile.java
+++ b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/rcfile/RCFile.java
@@ -1182,6 +1182,8 @@ public class RCFile {
     private byte[] nullChars;
     private SerializerDeserializer serde;
 
+    private Tuple outTuple;
+
     public RCFileScanner(Configuration conf, final Schema schema, final TableMeta meta,
                          final Fragment fragment) throws IOException {
       super(conf, schema, meta, fragment);
@@ -1214,6 +1216,8 @@ public class RCFile {
         targets = schema.toArray();
       }
 
+      outTuple = new VTuple(targets.length);
+
       targetColumnIndexes = new int[targets.length];
       for (int i = 0; i < targets.length; i++) {
         targetColumnIndexes[i] = schema.getColumnId(targets[i].getQualifiedName());
@@ -1641,9 +1645,8 @@ public class RCFile {
         return null;
       }
 
-      Tuple tuple = new VTuple(targets.length);
-      getCurrentRow(tuple);
-      return tuple;
+      getCurrentRow(outTuple);
+      return outTuple;
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/sequencefile/SequenceFileScanner.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/sequencefile/SequenceFileScanner.java b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/sequencefile/SequenceFileScanner.java
index 340e2fa..bac8779 100644
--- a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/sequencefile/SequenceFileScanner.java
+++ b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/sequencefile/SequenceFileScanner.java
@@ -18,6 +18,7 @@
 
 package org.apache.tajo.storage.sequencefile;
 
+import io.netty.buffer.ByteBuf;
 import org.apache.commons.lang.StringEscapeUtils;
 import org.apache.commons.lang.StringUtils;
 import org.apache.commons.logging.Log;
@@ -35,7 +36,10 @@ import org.apache.tajo.exception.UnsupportedException;
 import org.apache.tajo.plan.expr.EvalNode;
 import org.apache.tajo.storage.*;
 import org.apache.tajo.storage.fragment.Fragment;
-import org.apache.tajo.util.BytesUtils;
+import org.apache.tajo.storage.text.ByteBufLineReader;
+import org.apache.tajo.storage.text.DelimitedTextFile;
+import org.apache.tajo.storage.text.TextLineDeserializer;
+import org.apache.tajo.storage.text.TextLineParsingError;
 
 import java.io.IOException;
 
@@ -73,6 +77,11 @@ public class SequenceFileScanner extends FileScanner {
 
   private Writable EMPTY_KEY;
 
+  private TextLineDeserializer deserializer;
+  private ByteBuf byteBuf = BufferPool.directBuffer(ByteBufLineReader.DEFAULT_BUFFER);
+
+  private Tuple outTuple;
+
   public SequenceFileScanner(Configuration conf, Schema schema, TableMeta meta, Fragment fragment) throws IOException {
     super(conf, schema, meta, fragment);
   }
@@ -109,6 +118,9 @@ public class SequenceFileScanner extends FileScanner {
       targets = schema.toArray();
     }
 
+    outTuple = new VTuple(targets.length);
+    deserializer = DelimitedTextFile.getLineSerde(meta).createDeserializer(schema, meta, targets);
+    deserializer.init();
 
     fieldIsNull = new boolean[schema.getRootColumns().size()];
     fieldStart = new int[schema.getRootColumns().size()];
@@ -149,6 +161,8 @@ public class SequenceFileScanner extends FileScanner {
     }
   }
 
+  Text text = new Text();
+
   @Override
   public Tuple next() throws IOException {
     if (!more) return null;
@@ -163,24 +177,25 @@ public class SequenceFileScanner extends FileScanner {
     }
 
     if (more) {
-      Tuple tuple = null;
-      byte[][] cells;
-
       if (hasBinarySerDe) {
         BytesWritable bytesWritable = new BytesWritable();
         reader.getCurrentValue(bytesWritable);
-        tuple = makeTuple(bytesWritable);
+        makeTuple(bytesWritable);
         totalBytes += (long)bytesWritable.getBytes().length;
       } else {
-        Text text = new Text();
         reader.getCurrentValue(text);
-        cells = BytesUtils.splitPreserveAllTokens(text.getBytes(), 
-            delimiter, projectionMap, schema.getRootColumns().size());
-        totalBytes += (long)text.getBytes().length;
-        tuple = new LazyTuple(schema, cells, 0, nullChars, serde);
+
+        byteBuf.clear();
+        byteBuf.writeBytes(text.getBytes(), 0, text.getLength());
+
+        try {
+          deserializer.deserialize(byteBuf, outTuple);
+        } catch (TextLineParsingError e) {
+          throw new IOException(e);
+        }
       }
       currentIdx++;
-      return tuple;
+      return outTuple;
     } else {
       return null;
     }
@@ -200,8 +215,6 @@ public class SequenceFileScanner extends FileScanner {
    * So, tajo must make a tuple after parsing hive style BinarySerDe.
    */
   private Tuple makeTuple(BytesWritable value) throws IOException{
-    Tuple tuple = new VTuple(schema.getRootColumns().size());
-
     int start = 0;
     int length = value.getLength();
 
@@ -229,7 +242,7 @@ public class SequenceFileScanner extends FileScanner {
         for (int j = 0; j < projectionMap.length; j++) {
           if (projectionMap[j] == i) {
             Datum datum = serde.deserialize(i, bytes, fieldStart[i], fieldLength[i], nullChars);
-            tuple.put(i, datum);
+            outTuple.put(i, datum);
           }
         }
       }
@@ -247,7 +260,7 @@ public class SequenceFileScanner extends FileScanner {
       }
     }
 
-    return tuple;
+    return outTuple;
   }
 
   /**
@@ -321,11 +334,16 @@ public class SequenceFileScanner extends FileScanner {
       tableStats.setReadBytes(totalBytes);
       tableStats.setNumRows(currentIdx);
     }
+
+    outTuple = null;
+    if (this.byteBuf.refCnt() > 0) {
+      this.byteBuf.release();
+    }
   }
 
   @Override
   public boolean isProjectable() {
-    return false;
+    return true;
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/ByteBufLineReader.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/ByteBufLineReader.java b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/ByteBufLineReader.java
index e23e8f8..3c667bf 100644
--- a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/ByteBufLineReader.java
+++ b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/ByteBufLineReader.java
@@ -29,7 +29,7 @@ import java.io.IOException;
 import java.util.concurrent.atomic.AtomicInteger;
 
 public class ByteBufLineReader implements Closeable {
-  private static int DEFAULT_BUFFER = 64 * 1024;
+  public static int DEFAULT_BUFFER = 64 * 1024;
 
   private int bufferSize;
   private long readBytes;

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/CSVLineSerializer.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/CSVLineSerializer.java b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/CSVLineSerializer.java
index 21984f2..3445676 100644
--- a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/CSVLineSerializer.java
+++ b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/CSVLineSerializer.java
@@ -21,6 +21,7 @@ package org.apache.tajo.storage.text;
 import org.apache.tajo.catalog.Schema;
 import org.apache.tajo.catalog.TableMeta;
 import org.apache.tajo.storage.FieldSerializerDeserializer;
+import org.apache.tajo.storage.StorageConstants;
 import org.apache.tajo.storage.Tuple;
 
 import java.io.IOException;

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/DelimitedTextFile.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/DelimitedTextFile.java b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/DelimitedTextFile.java
index fdeba4e..c68690a 100644
--- a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/DelimitedTextFile.java
+++ b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/DelimitedTextFile.java
@@ -286,6 +286,8 @@ public class DelimitedTextFile {
     /** How many errors have occurred? */
     private int errorNum;
 
+    private VTuple outTuple;
+
     public DelimitedTextFileScanner(Configuration conf, final Schema schema, final TableMeta meta,
                                     final Fragment fragment)
         throws IOException {
@@ -321,6 +323,8 @@ public class DelimitedTextFile {
         targets = schema.toArray();
       }
 
+      outTuple = new VTuple(targets.length);
+
       super.init();
       if (LOG.isDebugEnabled()) {
         LOG.debug("DelimitedTextFileScanner open:" + fragment.getPath() + "," + startOffset + "," + endOffset);
@@ -375,7 +379,6 @@ public class DelimitedTextFile {
 
     @Override
     public Tuple next() throws IOException {
-      VTuple tuple;
 
       if (!reader.isReadable()) {
         return null;
@@ -400,11 +403,10 @@ public class DelimitedTextFile {
             return EmptyTuple.get();
           }
 
-          tuple = new VTuple(targets.length);
-          tuple.setOffset(offset);
+          outTuple.setOffset(offset);
 
           try {
-            deserializer.deserialize(buf, tuple);
+            deserializer.deserialize(buf, outTuple);
             // if a line is read normally, it exits this loop.
             break;
 
@@ -429,7 +431,7 @@ public class DelimitedTextFile {
         // recordCount means the number of actual read records. We increment the count here.
         recordCount++;
 
-        return tuple;
+        return outTuple;
 
       } catch (Throwable t) {
         LOG.error(t);
@@ -459,6 +461,7 @@ public class DelimitedTextFile {
       } finally {
         IOUtils.cleanup(LOG, reader);
         reader = null;
+        outTuple = null;
       }
     }
 

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/TextLineSerDe.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/TextLineSerDe.java b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/TextLineSerDe.java
index c09a83b..4cdf7df 100644
--- a/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/TextLineSerDe.java
+++ b/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/text/TextLineSerDe.java
@@ -42,7 +42,12 @@ public abstract class TextLineSerDe {
   public abstract TextLineSerializer createSerializer(Schema schema, TableMeta meta);
 
   public static ByteBuf getNullChars(TableMeta meta) {
-    byte[] nullCharByteArray = getNullCharsAsBytes(meta);
+    byte[] nullCharByteArray;
+    if (meta.getStoreType().equals("SEQUENCEFILE")) {
+      nullCharByteArray = getNullCharsAsBytes(meta, StorageConstants.SEQUENCEFILE_NULL, "\\");
+    } else {
+      nullCharByteArray = getNullCharsAsBytes(meta);
+    }
 
     ByteBuf nullChars = BufferPool.directBuffer(nullCharByteArray.length, nullCharByteArray.length);
     nullChars.writeBytes(nullCharByteArray);
@@ -51,10 +56,13 @@ public abstract class TextLineSerDe {
   }
 
   public static byte [] getNullCharsAsBytes(TableMeta meta) {
+    return getNullCharsAsBytes(meta, StorageConstants.TEXT_NULL, NullDatum.DEFAULT_TEXT);
+  }
+
+  public static byte[] getNullCharsAsBytes(TableMeta meta, String key, String defaultVal) {
     byte [] nullChars;
 
-    String nullCharacters = StringEscapeUtils.unescapeJava(meta.getOption(StorageConstants.TEXT_NULL,
-        NullDatum.DEFAULT_TEXT));
+    String nullCharacters = StringEscapeUtils.unescapeJava(meta.getOption(key, defaultVal));
     if (StringUtils.isEmpty(nullCharacters)) {
       nullChars = NullDatum.get().asTextBytes();
     } else {

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-hdfs/src/test/java/org/apache/tajo/storage/TestMergeScanner.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-hdfs/src/test/java/org/apache/tajo/storage/TestMergeScanner.java b/tajo-storage/tajo-storage-hdfs/src/test/java/org/apache/tajo/storage/TestMergeScanner.java
index 35a5ea4..0ba75dd 100644
--- a/tajo-storage/tajo-storage-hdfs/src/test/java/org/apache/tajo/storage/TestMergeScanner.java
+++ b/tajo-storage/tajo-storage-hdfs/src/test/java/org/apache/tajo/storage/TestMergeScanner.java
@@ -109,8 +109,7 @@ public class TestMergeScanner {
     TableMeta meta = CatalogUtil.newTableMeta(storeType, options);
     meta.setOptions(CatalogUtil.newDefaultProperty(storeType));
     if (storeType.equalsIgnoreCase("AVRO")) {
-      meta.putOption(StorageConstants.AVRO_SCHEMA_LITERAL,
-                     TEST_MULTIPLE_FILES_AVRO_SCHEMA);
+      meta.putOption(StorageConstants.AVRO_SCHEMA_LITERAL, TEST_MULTIPLE_FILES_AVRO_SCHEMA);
     }
 
     Path table1Path = new Path(testDir, storeType + "_1.data");
@@ -201,6 +200,8 @@ public class TestMergeScanner {
   private static boolean isProjectableStorage(String type) {
     if (type.equalsIgnoreCase("RCFILE") ||
         type.equalsIgnoreCase("PARQUET") ||
+        type.equalsIgnoreCase("CSV") ||
+        type.equalsIgnoreCase("SEQUENCEFILE") ||
         type.equalsIgnoreCase("AVRO")) {
       return true;
     } else {

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-storage/tajo-storage-hdfs/src/test/java/org/apache/tajo/storage/TestStorages.java
----------------------------------------------------------------------
diff --git a/tajo-storage/tajo-storage-hdfs/src/test/java/org/apache/tajo/storage/TestStorages.java b/tajo-storage/tajo-storage-hdfs/src/test/java/org/apache/tajo/storage/TestStorages.java
index b53dbec..c3f31a0 100644
--- a/tajo-storage/tajo-storage-hdfs/src/test/java/org/apache/tajo/storage/TestStorages.java
+++ b/tajo-storage/tajo-storage-hdfs/src/test/java/org/apache/tajo/storage/TestStorages.java
@@ -369,6 +369,7 @@ public class TestStorages {
         DatumFactory.createInet4("192.168.0.1"),
         NullDatum.get()
     });
+
     if (handleProtobuf) {
       tuple.put(11, factory.createDatum(queryid.getProto()));
     }
@@ -420,8 +421,7 @@ public class TestStorages {
     meta.putOption(StorageConstants.RCFILE_SERDE, TextSerializerDeserializer.class.getName());
     meta.putOption(StorageConstants.SEQUENCEFILE_NULL, "\\");
     if (storeType.equalsIgnoreCase("AVRO")) {
-      meta.putOption(StorageConstants.AVRO_SCHEMA_LITERAL,
-                     TEST_NULL_HANDLING_TYPES_AVRO_SCHEMA);
+      meta.putOption(StorageConstants.AVRO_SCHEMA_LITERAL, TEST_NULL_HANDLING_TYPES_AVRO_SCHEMA);
     }
 
     Path tablePath = new Path(testDir, "testVariousTypes.data");


[2/3] tajo git commit: TAJO-1343: Improve the memory usage of physical executors. (jihoon)

Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/ExternalSortExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/ExternalSortExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/ExternalSortExec.java
index 13b5a3a..adbafd9 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/ExternalSortExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/ExternalSortExec.java
@@ -19,7 +19,6 @@
 package org.apache.tajo.engine.planner.physical;
 
 import com.google.common.annotations.VisibleForTesting;
-
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.fs.LocalDirAllocator;
@@ -31,13 +30,11 @@ import org.apache.tajo.catalog.CatalogUtil;
 import org.apache.tajo.catalog.Schema;
 import org.apache.tajo.catalog.TableMeta;
 import org.apache.tajo.catalog.proto.CatalogProtos;
-import org.apache.tajo.catalog.proto.CatalogProtos.StoreType;
 import org.apache.tajo.catalog.statistics.TableStats;
 import org.apache.tajo.conf.TajoConf.ConfVars;
 import org.apache.tajo.engine.planner.PhysicalPlanningException;
 import org.apache.tajo.plan.logical.SortNode;
 import org.apache.tajo.storage.*;
-import org.apache.tajo.storage.Scanner;
 import org.apache.tajo.storage.fragment.FileFragment;
 import org.apache.tajo.storage.fragment.FragmentConvertor;
 import org.apache.tajo.unit.StorageUnit;
@@ -47,7 +44,9 @@ import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.File;
 import java.io.IOException;
-import java.util.*;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
 import java.util.concurrent.*;
 
 import static org.apache.tajo.storage.RawFile.RawFileAppender;
@@ -81,7 +80,7 @@ public class ExternalSortExec extends SortExec {
   /** If there are available multiple cores, it tries parallel merge. */
   private ExecutorService executorService;
   /** used for in-memory sort of each chunk. */
-  private List<Tuple> inMemoryTable;
+  private TupleList inMemoryTable;
   /** temporal dir */
   private final Path sortTmpDir;
   /** It enables round-robin disks allocation */
@@ -120,7 +119,7 @@ public class ExternalSortExec extends SortExec {
     this.sortBufferBytesNum = context.getQueryContext().getLong(SessionVars.EXTSORT_BUFFER_SIZE) * StorageUnit.MB;
     this.allocatedCoreNum = context.getConf().getIntVar(ConfVars.EXECUTOR_EXTERNAL_SORT_THREAD_NUM);
     this.executorService = Executors.newFixedThreadPool(this.allocatedCoreNum);
-    this.inMemoryTable = new ArrayList<Tuple>(100000);
+    this.inMemoryTable = new TupleList(100000);
 
     this.sortTmpDir = getExecutorTmpDir();
     localDirAllocator = new LocalDirAllocator(ConfVars.WORKER_TEMPORAL_DIR.varname);
@@ -161,7 +160,7 @@ public class ExternalSortExec extends SortExec {
   /**
    * Sort a tuple block and store them into a chunk file
    */
-  private Path sortAndStoreChunk(int chunkId, List<Tuple> tupleBlock)
+  private Path sortAndStoreChunk(int chunkId, TupleList tupleBlock)
       throws IOException {
     TableMeta meta = CatalogUtil.newTableMeta("RAW");
     int rowNum = tupleBlock.size();
@@ -203,9 +202,8 @@ public class ExternalSortExec extends SortExec {
     int chunkId = 0;
     long runStartTime = System.currentTimeMillis();
     while (!context.isStopped() && (tuple = child.next()) != null) { // partition sort start
-      Tuple vtuple = new VTuple(tuple);
-      inMemoryTable.add(vtuple);
-      memoryConsumption += MemoryUtil.calculateMemorySize(vtuple);
+      inMemoryTable.add(tuple);
+      memoryConsumption += MemoryUtil.calculateMemorySize(tuple);
 
       if (memoryConsumption > sortBufferBytesNum) {
         long runEndTime = System.currentTimeMillis();
@@ -645,6 +643,8 @@ public class ExternalSortExec extends SortExec {
     private Tuple leftTuple;
     private Tuple rightTuple;
 
+    private final Tuple outTuple;
+
     private float mergerProgress;
     private TableStats mergerInputStats;
 
@@ -656,6 +656,7 @@ public class ExternalSortExec extends SortExec {
       this.leftScan = leftScanner;
       this.rightScan = rightScanner;
       this.comparator = comparator;
+      this.outTuple = new VTuple(schema.size());
     }
 
     private void setState(State state) {
@@ -685,25 +686,26 @@ public class ExternalSortExec extends SortExec {
     }
 
     protected Tuple prepare(int index, Tuple tuple) {
-      return tuple == null ? null : new VTuple(tuple);
+      return tuple;
     }
 
     protected int compare() {
       return comparator.compare(leftTuple, rightTuple);
     }
 
+    @Override
     public Tuple next() throws IOException {
       if (leftTuple == null && rightTuple == null) {
         return null;
       }
       if (rightTuple == null || (leftTuple != null && compare() < 0)) {
-        Tuple tuple = leftTuple;
+        outTuple.put(leftTuple.getValues());
         leftTuple = prepare(0, leftScan.next());
-        return tuple;
+        return outTuple;
       }
-      Tuple tuple = rightTuple;
+      outTuple.put(rightTuple.getValues());
       rightTuple = prepare(1, rightScan.next());
-      return tuple;
+      return outTuple;
     }
 
     @Override
@@ -726,6 +728,8 @@ public class ExternalSortExec extends SortExec {
       IOUtils.cleanup(LOG, leftScan, rightScan);
       getInputStats();
       mergerProgress = 1.0f;
+      leftTuple = null;
+      rightTuple = null;
       setState(State.CLOSED);
     }
 

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashAggregateExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashAggregateExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashAggregateExec.java
index e6d1a96..b657622 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashAggregateExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashAggregateExec.java
@@ -18,6 +18,7 @@
 
 package org.apache.tajo.engine.planner.physical;
 
+import org.apache.tajo.engine.planner.KeyProjector;
 import org.apache.tajo.plan.function.FunctionContext;
 import org.apache.tajo.plan.logical.GroupbyNode;
 import org.apache.tajo.storage.Tuple;
@@ -25,9 +26,7 @@ import org.apache.tajo.storage.VTuple;
 import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
-import java.util.HashMap;
 import java.util.Iterator;
-import java.util.Map;
 import java.util.Map.Entry;
 
 /**
@@ -35,25 +34,23 @@ import java.util.Map.Entry;
  */
 public class HashAggregateExec extends AggregationExec {
   private Tuple tuple = null;
-  private Map<Tuple, FunctionContext[]> hashTable;
+  private TupleMap<FunctionContext[]> hashTable;
+  private KeyProjector hashKeyProjector;
   private boolean computed = false;
-  private Iterator<Entry<Tuple, FunctionContext []>> iterator = null;
+  private Iterator<Entry<KeyTuple, FunctionContext []>> iterator = null;
 
   public HashAggregateExec(TaskAttemptContext ctx, GroupbyNode plan, PhysicalExec subOp) throws IOException {
     super(ctx, plan, subOp);
-    hashTable = new HashMap<Tuple, FunctionContext []>(100000);
+    hashKeyProjector = new KeyProjector(inSchema, plan.getGroupingColumns());
+    hashTable = new TupleMap<FunctionContext []>(10000);
     this.tuple = new VTuple(plan.getOutSchema().size());
   }
 
   private void compute() throws IOException {
     Tuple tuple;
-    Tuple keyTuple;
+    KeyTuple keyTuple;
     while(!context.isStopped() && (tuple = child.next()) != null) {
-      keyTuple = new VTuple(groupingKeyIds.length);
-      // build one key tuple
-      for(int i = 0; i < groupingKeyIds.length; i++) {
-        keyTuple.put(i, tuple.asDatum(groupingKeyIds[i]));
-      }
+      keyTuple = hashKeyProjector.project(tuple);
 
       FunctionContext [] contexts = hashTable.get(keyTuple);
       if(contexts != null) {
@@ -92,7 +89,7 @@ public class HashAggregateExec extends AggregationExec {
     FunctionContext [] contexts;
 
     if (iterator.hasNext()) {
-      Entry<Tuple, FunctionContext []> entry = iterator.next();
+      Entry<KeyTuple, FunctionContext []> entry = iterator.next();
       Tuple keyTuple = entry.getKey();
       contexts =  entry.getValue();
 

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashFullOuterJoinExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashFullOuterJoinExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashFullOuterJoinExec.java
index 1645263..c0a8622 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashFullOuterJoinExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashFullOuterJoinExec.java
@@ -25,22 +25,26 @@ import org.apache.tajo.util.Pair;
 import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
-import java.util.*;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
 
-public class HashFullOuterJoinExec extends CommonHashJoinExec<Pair<Boolean, List<Tuple>>> {
+public class HashFullOuterJoinExec extends CommonHashJoinExec<Pair<Boolean, TupleList>> {
 
   private boolean finalLoop; // final loop for right unmatched
+  private final List<Tuple> nullTupleList;
 
   public HashFullOuterJoinExec(TaskAttemptContext context, JoinNode plan, PhysicalExec outer,
                                PhysicalExec inner) {
     super(context, plan, outer, inner);
+    nullTupleList = nullTupleList(rightNumCols);
   }
 
   public Iterator<Tuple> getUnmatchedRight() {
 
     return new Iterator<Tuple>() {
 
-      private Iterator<Pair<Boolean, List<Tuple>>> iterator1 = tupleSlots.values().iterator();
+      private Iterator<Pair<Boolean, TupleList>> iterator1 = tupleSlots.values().iterator();
       private Iterator<Tuple> iterator2;
 
       @Override
@@ -49,7 +53,7 @@ public class HashFullOuterJoinExec extends CommonHashJoinExec<Pair<Boolean, List
           return true;
         }
         for (iterator2 = null; !hasMore() && iterator1.hasNext();) {
-          Pair<Boolean, List<Tuple>> next = iterator1.next();
+          Pair<Boolean, TupleList> next = iterator1.next();
           if (!next.getFirst()) {
             iterator2 = next.getSecond().iterator();
           }
@@ -81,8 +85,7 @@ public class HashFullOuterJoinExec extends CommonHashJoinExec<Pair<Boolean, List
     while (!context.isStopped() && !finished) {
       if (iterator != null && iterator.hasNext()) {
         frameTuple.setRight(iterator.next());
-        projector.eval(frameTuple, outTuple);
-        return outTuple;
+        return projector.eval(frameTuple);
       }
       if (finalLoop) {
         finished = true;
@@ -100,18 +103,18 @@ public class HashFullOuterJoinExec extends CommonHashJoinExec<Pair<Boolean, List
       frameTuple.setLeft(leftTuple);
 
       if (leftFiltered(leftTuple)) {
-        iterator = nullIterator(rightNumCols);
+        iterator = nullTupleList.iterator();
         continue;
       }
       // getting corresponding right
-      Pair<Boolean, List<Tuple>> hashed = tupleSlots.get(toKey(leftTuple));
+      Pair<Boolean, TupleList> hashed = tupleSlots.get(leftKeyExtractor.project(leftTuple));
       if (hashed == null) {
-        iterator = nullIterator(rightNumCols);
+        iterator = nullTupleList.iterator();
         continue;
       }
       Iterator<Tuple> rightTuples = rightFiltered(hashed.getSecond());
       if (!rightTuples.hasNext()) {
-        iterator = nullIterator(rightNumCols);
+        iterator = nullTupleList.iterator();
         continue;
       }
       iterator = rightTuples;
@@ -122,12 +125,12 @@ public class HashFullOuterJoinExec extends CommonHashJoinExec<Pair<Boolean, List
   }
 
   @Override
-  protected Map<Tuple, Pair<Boolean, List<Tuple>>> convert(Map<Tuple, List<Tuple>> hashed,
-                                                           boolean fromCache) throws IOException {
-    Map<Tuple, Pair<Boolean, List<Tuple>>> tuples = new HashMap<Tuple, Pair<Boolean, List<Tuple>>>(hashed.size());
-    for (Map.Entry<Tuple, List<Tuple>> entry : hashed.entrySet()) {
+  protected TupleMap<Pair<Boolean, TupleList>> convert(TupleMap<TupleList> hashed,
+                                                       boolean fromCache) throws IOException {
+    TupleMap<Pair<Boolean, TupleList>> tuples = new TupleMap<Pair<Boolean, TupleList>>(hashed.size());
+    for (Map.Entry<KeyTuple, TupleList> entry : hashed.entrySet()) {
       // flag: initially false (whether this join key had at least one match on the counter part)
-      tuples.put(entry.getKey(), new Pair<Boolean, List<Tuple>>(false, entry.getValue()));
+      tuples.putWihtoutKeyCopy(entry.getKey(), new Pair<Boolean, TupleList>(false, entry.getValue()));
     }
     return tuples;
   }
@@ -135,7 +138,7 @@ public class HashFullOuterJoinExec extends CommonHashJoinExec<Pair<Boolean, List
   @Override
   public void rescan() throws IOException {
     super.rescan();
-    for (Pair<Boolean, List<Tuple>> value : tupleSlots.values()) {
+    for (Pair<Boolean, TupleList> value : tupleSlots.values()) {
       value.setFirst(false);
     }
     finalLoop = false;

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashJoinExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashJoinExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashJoinExec.java
index 3065c15..bd817bb 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashJoinExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashJoinExec.java
@@ -23,12 +23,9 @@ import org.apache.tajo.storage.Tuple;
 import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
-import java.util.HashMap;
 import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
 
-public class HashJoinExec extends CommonHashJoinExec<List<Tuple>> {
+public class HashJoinExec extends CommonHashJoinExec<TupleList> {
 
   public HashJoinExec(TaskAttemptContext context, JoinNode plan, PhysicalExec leftExec,
       PhysicalExec rightExec) {
@@ -36,9 +33,9 @@ public class HashJoinExec extends CommonHashJoinExec<List<Tuple>> {
   }
 
   @Override
-  protected Map<Tuple, List<Tuple>> convert(Map<Tuple, List<Tuple>> hashed, boolean fromCache)
+  protected TupleMap<TupleList> convert(TupleMap<TupleList> hashed, boolean fromCache)
       throws IOException {
-    return fromCache ? new HashMap<Tuple, List<Tuple>>(hashed) : hashed;
+    return fromCache ? new TupleMap<TupleList>(hashed) : hashed;
   }
 
   @Override
@@ -50,8 +47,7 @@ public class HashJoinExec extends CommonHashJoinExec<List<Tuple>> {
     while (!context.isStopped() && !finished) {
       if (iterator != null && iterator.hasNext()) {
         frameTuple.setRight(iterator.next());
-        projector.eval(frameTuple, outTuple);
-        return outTuple;
+        return projector.eval(frameTuple);
       }
 
       Tuple leftTuple = leftChild.next(); // it comes from a disk
@@ -63,7 +59,7 @@ public class HashJoinExec extends CommonHashJoinExec<List<Tuple>> {
       frameTuple.setLeft(leftTuple);
 
       // getting corresponding right
-      Iterable<Tuple> hashed = getRights(toKey(leftTuple));
+      Iterable<Tuple> hashed = tupleSlots.get(leftKeyExtractor.project(leftTuple));
       Iterator<Tuple> rightTuples = rightFiltered(hashed);
       if (rightTuples.hasNext()) {
         iterator = rightTuples;
@@ -72,9 +68,4 @@ public class HashJoinExec extends CommonHashJoinExec<List<Tuple>> {
 
     return null;
   }
-
-  private Iterable<Tuple> getRights(Tuple key) {
-    return tupleSlots.get(key);
-  }
-
 }

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashLeftAntiJoinExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashLeftAntiJoinExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashLeftAntiJoinExec.java
index 8239270..746bdb9 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashLeftAntiJoinExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashLeftAntiJoinExec.java
@@ -18,9 +18,9 @@
 
 package org.apache.tajo.engine.planner.physical;
 
-import org.apache.tajo.worker.TaskAttemptContext;
 import org.apache.tajo.plan.logical.JoinNode;
 import org.apache.tajo.storage.Tuple;
+import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
 import java.util.List;
@@ -32,6 +32,8 @@ import java.util.List;
  */
 public class HashLeftAntiJoinExec extends HashJoinExec {
 
+  private final List<Tuple> nullTupleList = nullTupleList(0);
+
   public HashLeftAntiJoinExec(TaskAttemptContext context, JoinNode plan, PhysicalExec fromSideChild,
                               PhysicalExec notInSideChild) {
     super(context, plan, fromSideChild, notInSideChild);
@@ -57,8 +59,7 @@ public class HashLeftAntiJoinExec extends HashJoinExec {
     while(!context.isStopped() && !finished) {
       if (iterator != null && iterator.hasNext()) {
         frameTuple.setRight(iterator.next());
-        projector.eval(frameTuple, outTuple);
-        return outTuple;
+        return projector.eval(frameTuple);
       }
       // getting new outer
       Tuple leftTuple = leftChild.next(); // it comes from a disk
@@ -70,9 +71,9 @@ public class HashLeftAntiJoinExec extends HashJoinExec {
       frameTuple.setLeft(leftTuple);
 
       // Try to find a hash bucket in in-memory hash table
-      List<Tuple> hashed = tupleSlots.get(toKey(leftTuple));
+      TupleList hashed = tupleSlots.get(leftKeyExtractor.project(leftTuple));
       if (hashed == null || !rightFiltered(hashed).hasNext()) {
-        iterator = nullIterator(0);
+        iterator = nullTupleList.iterator();
       }
     }
     return null;

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashLeftOuterJoinExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashLeftOuterJoinExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashLeftOuterJoinExec.java
index 27f683b..b652c3c 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashLeftOuterJoinExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashLeftOuterJoinExec.java
@@ -31,10 +31,12 @@ import java.util.List;
 public class HashLeftOuterJoinExec extends HashJoinExec {
 
   private static final Log LOG = LogFactory.getLog(HashLeftOuterJoinExec.class);
+  private final List<Tuple> nullTupleList;
 
   public HashLeftOuterJoinExec(TaskAttemptContext context, JoinNode plan, PhysicalExec leftChild,
                                PhysicalExec rightChild) {
     super(context, plan, leftChild, rightChild);
+    nullTupleList = nullTupleList(rightNumCols);
   }
 
   @Override
@@ -46,8 +48,7 @@ public class HashLeftOuterJoinExec extends HashJoinExec {
     while (!context.isStopped() && !finished) {
       if (iterator != null && iterator.hasNext()) {
         frameTuple.setRight(iterator.next());
-        projector.eval(frameTuple, outTuple);
-        return outTuple;
+        return projector.eval(frameTuple);
       }
       Tuple leftTuple = leftChild.next(); // it comes from a disk
       if (leftTuple == null) { // if no more tuples in left tuples on disk, a join is completed.
@@ -57,17 +58,17 @@ public class HashLeftOuterJoinExec extends HashJoinExec {
       frameTuple.setLeft(leftTuple);
 
       if (leftFiltered(leftTuple)) {
-        iterator = nullIterator(rightNumCols);
+        iterator = nullTupleList.iterator();
         continue;
       }
 
       // getting corresponding right
-      List<Tuple> hashed = tupleSlots.get(toKey(leftTuple));
+      TupleList hashed = tupleSlots.get(leftKeyExtractor.project(leftTuple));
       Iterator<Tuple> rightTuples = rightFiltered(hashed);
       if (!rightTuples.hasNext()) {
         //this left tuple doesn't have a match on the right.But full outer join => we should keep it anyway
         //output a tuple with the nulls padded rightTuple
-        iterator = nullIterator(rightNumCols);
+        iterator = nullTupleList.iterator();
         continue;
       }
       iterator = rightTuples;

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashLeftSemiJoinExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashLeftSemiJoinExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashLeftSemiJoinExec.java
index 41e842a..42b78e8 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashLeftSemiJoinExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashLeftSemiJoinExec.java
@@ -18,9 +18,9 @@
 
 package org.apache.tajo.engine.planner.physical;
 
-import org.apache.tajo.worker.TaskAttemptContext;
 import org.apache.tajo.plan.logical.JoinNode;
 import org.apache.tajo.storage.Tuple;
+import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
 import java.util.List;
@@ -32,6 +32,8 @@ import java.util.List;
  */
 public class HashLeftSemiJoinExec extends HashJoinExec {
 
+  private final List<Tuple> nullTupleList = nullTupleList(0);
+
   public HashLeftSemiJoinExec(TaskAttemptContext context, JoinNode plan, PhysicalExec fromSideChild,
                               PhysicalExec inSideChild) {
     super(context, plan, fromSideChild, inSideChild);
@@ -59,8 +61,7 @@ public class HashLeftSemiJoinExec extends HashJoinExec {
     while(!context.isStopped() && !finished) {
       if (iterator != null && iterator.hasNext()) {
         frameTuple.setRight(iterator.next());
-        projector.eval(frameTuple, outTuple);
-        return outTuple;
+        return projector.eval(frameTuple);
       }
       // getting new outer
       Tuple leftTuple = leftChild.next(); // it comes from a disk
@@ -72,10 +73,10 @@ public class HashLeftSemiJoinExec extends HashJoinExec {
       frameTuple.setLeft(leftTuple);
 
       // Try to find a hash bucket in in-memory hash table
-      List<Tuple> hashed = tupleSlots.get(toKey(leftTuple));
+      TupleList hashed = tupleSlots.get(leftKeyExtractor.project(leftTuple));
       if (hashed != null && rightFiltered(hashed).hasNext()) {
         // if found, it gets a hash bucket from the hash table.
-        iterator = nullIterator(0);
+        iterator = nullTupleList.iterator();
       }
     }
     return null;

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashShuffleFileWriteExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashShuffleFileWriteExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashShuffleFileWriteExec.java
index 1a92a7a..bc4382e 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashShuffleFileWriteExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/HashShuffleFileWriteExec.java
@@ -33,9 +33,7 @@ import org.apache.tajo.storage.Tuple;
 import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
-import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
 
 /**
@@ -47,7 +45,6 @@ public final class HashShuffleFileWriteExec extends UnaryPhysicalExec {
   private ShuffleFileWriteNode plan;
   private final TableMeta meta;
   private Partitioner partitioner;
-//  private final Path storeTablePath;
   private Map<Integer, HashShuffleAppender> appenderMap = new HashMap<Integer, HashShuffleAppender>();
   private final int numShuffleOutputs;
   private final int [] shuffleKeyIds;
@@ -92,8 +89,7 @@ public final class HashShuffleFileWriteExec extends UnaryPhysicalExec {
     return appender;
   }
 
-//  Map<Integer, Long> partitionStats = new HashMap<Integer, Long>();
-  Map<Integer, List<Tuple>> partitionTuples = new HashMap<Integer, List<Tuple>>();
+  Map<Integer, TupleList> partitionTuples = new HashMap<Integer, TupleList>();
   long writtenBytes = 0L;
 
   @Override
@@ -108,17 +104,14 @@ public final class HashShuffleFileWriteExec extends UnaryPhysicalExec {
         numRows++;
 
         partId = partitioner.getPartition(tuple);
-        List<Tuple> partitionTupleList = partitionTuples.get(partId);
+        TupleList partitionTupleList = partitionTuples.get(partId);
         if (partitionTupleList == null) {
-          partitionTupleList = new ArrayList<Tuple>(1000);
+          partitionTupleList = new TupleList(1000);
           partitionTuples.put(partId, partitionTupleList);
         }
-        try {
-          partitionTupleList.add(tuple.clone());
-        } catch (CloneNotSupportedException e) {
-        }
+        partitionTupleList.add(tuple);
         if (tupleCount >= numHashShuffleBufferTuples) {
-          for (Map.Entry<Integer, List<Tuple>> entry : partitionTuples.entrySet()) {
+          for (Map.Entry<Integer, TupleList> entry : partitionTuples.entrySet()) {
             int appendPartId = entry.getKey();
             HashShuffleAppender appender = getAppender(appendPartId);
             int appendedSize = appender.addTuples(context.getTaskId(), entry.getValue());
@@ -130,7 +123,7 @@ public final class HashShuffleFileWriteExec extends UnaryPhysicalExec {
       }
 
       // processing remained tuples
-      for (Map.Entry<Integer, List<Tuple>> entry : partitionTuples.entrySet()) {
+      for (Map.Entry<Integer, TupleList> entry : partitionTuples.entrySet()) {
         int appendPartId = entry.getKey();
         HashShuffleAppender appender = getAppender(appendPartId);
         int appendedSize = appender.addTuples(context.getTaskId(), entry.getValue());
@@ -168,6 +161,12 @@ public final class HashShuffleFileWriteExec extends UnaryPhysicalExec {
       appenderMap = null;
     }
 
+    for (TupleList eachList : partitionTuples.values()) {
+      eachList.clear();
+    }
+    partitionTuples.clear();
+    partitionTuples = null;
+
     partitioner = null;
     plan = null;
 

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/KeyTuple.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/KeyTuple.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/KeyTuple.java
new file mode 100644
index 0000000..39b13f8
--- /dev/null
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/KeyTuple.java
@@ -0,0 +1,85 @@
+/**
+ * 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.tajo.engine.planner.physical;
+
+import org.apache.tajo.datum.Datum;
+import org.apache.tajo.storage.Tuple;
+import org.apache.tajo.storage.VTuple;
+
+/**
+ * KeyTuple is to keep its hash value in memory to avoid frequent expensive hash calculation.
+ * Datum.hashCode() uses MurmurHash, so its cost is not so cheap.
+ *
+ */
+public class KeyTuple extends VTuple {
+  private int hashCode;
+
+  public KeyTuple(int size) {
+    super(size);
+    updateHashCode();
+  }
+
+  public KeyTuple(Tuple tuple) {
+    super(tuple);
+    updateHashCode();
+  }
+
+  public KeyTuple(Datum[] datums) {
+    super(datums);
+    updateHashCode();
+  }
+
+  @Override
+  public void put(int fieldId, Tuple tuple) {
+    super.put(fieldId, tuple);
+    updateHashCode();
+  }
+
+  private void updateHashCode() {
+    this.hashCode = super.hashCode();
+  }
+
+  @Override
+  public void put(int fieldId, Datum value) {
+    super.put(fieldId, value);
+    updateHashCode();
+  }
+
+  @Override
+  public void clear() {
+    super.clear();
+    updateHashCode();
+  }
+
+  @Override
+  public void put(Datum [] values) {
+    super.put(values);
+    updateHashCode();
+  }
+
+  @Override
+  public int hashCode() {
+    return hashCode;
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    return super.equals(obj);
+  }
+}

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/MemSortExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/MemSortExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/MemSortExec.java
index f76e356..029592a 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/MemSortExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/MemSortExec.java
@@ -18,19 +18,16 @@
 
 package org.apache.tajo.engine.planner.physical;
 
-import org.apache.tajo.worker.TaskAttemptContext;
 import org.apache.tajo.plan.logical.SortNode;
 import org.apache.tajo.storage.Tuple;
-import org.apache.tajo.storage.VTuple;
+import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
-import java.util.ArrayList;
 import java.util.Iterator;
-import java.util.List;
 
 public class MemSortExec extends SortExec {
   private SortNode plan;
-  private List<Tuple> tupleSlots;
+  private TupleList tupleSlots;
   private boolean sorted = false;
   private Iterator<Tuple> iterator;
 
@@ -42,7 +39,7 @@ public class MemSortExec extends SortExec {
 
   public void init() throws IOException {
     super.init();
-    this.tupleSlots = new ArrayList<Tuple>(10000);
+    this.tupleSlots = new TupleList(10000);
   }
 
   @Override
@@ -51,7 +48,7 @@ public class MemSortExec extends SortExec {
     if (!sorted) {
       Tuple tuple;
       while (!context.isStopped() && (tuple = child.next()) != null) {
-        tupleSlots.add(new VTuple(tuple));
+        tupleSlots.add(tuple);
       }
       iterator = getSorter(tupleSlots).sort().iterator();
       sorted = true;

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/MergeFullOuterJoinExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/MergeFullOuterJoinExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/MergeFullOuterJoinExec.java
index 13b73c3..41e3648 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/MergeFullOuterJoinExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/MergeFullOuterJoinExec.java
@@ -20,30 +20,27 @@ package org.apache.tajo.engine.planner.physical;
 
 import com.google.common.base.Preconditions;
 import org.apache.tajo.catalog.SortSpec;
-import org.apache.tajo.engine.utils.TupleUtil;
 import org.apache.tajo.plan.logical.JoinNode;
-import org.apache.tajo.storage.FrameTuple;
+import org.apache.tajo.storage.NullTuple;
 import org.apache.tajo.storage.Tuple;
 import org.apache.tajo.storage.TupleComparator;
 import org.apache.tajo.storage.VTuple;
 import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
 
 
 public class MergeFullOuterJoinExec extends CommonJoinExec {
 
   // temporal tuples and states for nested loop join
-  private FrameTuple frameTuple;
   private Tuple leftTuple = null;
   private Tuple rightTuple = null;
-  private Tuple outTuple = null;
   private Tuple leftNext = null;
+  private Tuple prevLeftTuple = null;
+  private Tuple prevRightTuple = null;
 
-  private List<Tuple> leftTupleSlots;
-  private List<Tuple> rightTupleSlots;
+  private TupleList leftTupleSlots;
+  private TupleList rightTupleSlots;
 
   private JoinTupleComparator joincomparator = null;
   private TupleComparator[] tupleComparator = null;
@@ -59,13 +56,16 @@ public class MergeFullOuterJoinExec extends CommonJoinExec {
   boolean endInPopulationStage = false;
   private boolean initRightDone = false;
 
+  private final Tuple leftNullTuple;
+  private final Tuple rightNullTuple;
+
   public MergeFullOuterJoinExec(TaskAttemptContext context, JoinNode plan, PhysicalExec leftChild,
                                 PhysicalExec rightChild, SortSpec[] leftSortKey, SortSpec[] rightSortKey) {
     super(context, plan, leftChild, rightChild);
     Preconditions.checkArgument(plan.hasJoinQual(), "Sort-merge join is only used for the equi-join, " +
         "but there is no join condition");
-    this.leftTupleSlots = new ArrayList<Tuple>(INITIAL_TUPLE_SLOT);
-    this.rightTupleSlots = new ArrayList<Tuple>(INITIAL_TUPLE_SLOT);
+    this.leftTupleSlots = new TupleList(INITIAL_TUPLE_SLOT);
+    this.rightTupleSlots = new TupleList(INITIAL_TUPLE_SLOT);
     SortSpec[][] sortSpecs = new SortSpec[2][];
     sortSpecs[0] = leftSortKey;
     sortSpecs[1] = rightSortKey;
@@ -75,16 +75,18 @@ public class MergeFullOuterJoinExec extends CommonJoinExec {
     this.tupleComparator = PhysicalPlanUtil.getComparatorsFromJoinQual(
         plan.getJoinQual(), leftChild.getSchema(), rightChild.getSchema());
 
-    // for join
-    frameTuple = new FrameTuple();
-    outTuple = new VTuple(outSchema.size());
-
     leftNumCols = leftChild.getSchema().size();
     rightNumCols = rightChild.getSchema().size();
+
+    prevLeftTuple = new VTuple(leftChild.getSchema().size());
+    prevRightTuple = new VTuple(rightChild.getSchema().size());
+
+    leftNullTuple = NullTuple.create(leftNumCols);
+    rightNullTuple = NullTuple.create(rightNumCols);
   }
 
   public Tuple next() throws IOException {
-    Tuple previous;
+    Tuple outTuple;
 
     while (!context.isStopped()) {
       boolean newRound = false;
@@ -122,9 +124,8 @@ public class MergeFullOuterJoinExec extends CommonJoinExec {
 
           if((leftTuple == null) && (rightTuple != null)){
             // output a tuple with the nulls padded leftTuple
-            Tuple nullPaddedTuple = TupleUtil.createNullPaddedTuple(leftNumCols);
-            frameTuple.set(nullPaddedTuple, rightTuple);
-            projector.eval(frameTuple, outTuple);
+            frameTuple.set(leftNullTuple, rightTuple);
+            outTuple = projector.eval(frameTuple);
             // we simulate we found a match, which is exactly the null padded one
             rightTuple = rightChild.next();
             return outTuple;
@@ -132,9 +133,8 @@ public class MergeFullOuterJoinExec extends CommonJoinExec {
 
           if((leftTuple != null) && (rightTuple == null)){
             // output a tuple with the nulls padded leftTuple
-            Tuple nullPaddedTuple = TupleUtil.createNullPaddedTuple(rightNumCols);
-            frameTuple.set(leftTuple, nullPaddedTuple);
-            projector.eval(frameTuple, outTuple);
+            frameTuple.set(leftTuple, rightNullTuple);
+            outTuple = projector.eval(frameTuple);
             // we simulate we found a match, which is exactly the null padded one
             leftTuple = leftChild.next();
             return outTuple;
@@ -178,9 +178,9 @@ public class MergeFullOuterJoinExec extends CommonJoinExec {
 
             //before getting a new tuple from the right,  a leftnullpadded tuple should be built
             //output a tuple with the nulls padded leftTuple
-            Tuple nullPaddedTuple = TupleUtil.createNullPaddedTuple(leftNumCols);
+            Tuple nullPaddedTuple = leftNullTuple;
             frameTuple.set(nullPaddedTuple, rightTuple);
-            projector.eval(frameTuple, outTuple);
+            outTuple = projector.eval(frameTuple);
             // BEFORE RETURN, MOVE FORWARD
             rightTuple = rightChild.next();
             if(rightTuple == null) {
@@ -192,9 +192,9 @@ public class MergeFullOuterJoinExec extends CommonJoinExec {
           } else if (cmp < 0) {
             // before getting a new tuple from the left,  a rightnullpadded tuple should be built
             // output a tuple with the nulls padded rightTuple
-            Tuple nullPaddedTuple = TupleUtil.createNullPaddedTuple(rightNumCols);
+            Tuple nullPaddedTuple = rightNullTuple;
             frameTuple.set(leftTuple, nullPaddedTuple);
-            projector.eval(frameTuple, outTuple);
+            outTuple = projector.eval(frameTuple);
             // we simulate we found a match, which is exactly the null padded one
             // BEFORE RETURN, MOVE FORWARD
             leftTuple = leftChild.next();
@@ -219,28 +219,27 @@ public class MergeFullOuterJoinExec extends CommonJoinExec {
           boolean endLeft = false;
           boolean endRight = false;
 
-          previous = new VTuple(leftTuple);
+          prevLeftTuple.put(leftTuple.getValues());
           do {
-            leftTupleSlots.add(new VTuple(leftTuple));
+            leftTupleSlots.add(leftTuple);
             leftTuple = leftChild.next();
             if(leftTuple == null) {
               endLeft = true;
             }
 
 
-          } while ((endLeft != true) && (tupleComparator[0].compare(previous, leftTuple) == 0));
+          } while ((endLeft != true) && (tupleComparator[0].compare(prevLeftTuple, leftTuple) == 0));
           posLeftTupleSlots = 0;
 
-
-          previous = new VTuple(rightTuple);
+          prevRightTuple.put(rightTuple.getValues());
           do {
-            rightTupleSlots.add(new VTuple(rightTuple));
+            rightTupleSlots.add(rightTuple);
             rightTuple = rightChild.next();
             if(rightTuple == null) {
               endRight = true;
             }
 
-          } while ((endRight != true) && (tupleComparator[1].compare(previous, rightTuple) == 0) );
+          } while ((endRight != true) && (tupleComparator[1].compare(prevRightTuple, rightTuple) == 0) );
           posRightTupleSlots = 0;
 
           if ((endLeft == true) || (endRight == true)) {
@@ -261,31 +260,29 @@ public class MergeFullOuterJoinExec extends CommonJoinExec {
       // (i.e. refers to next round)
       if(!end || (end && endInPopulationStage)){
         if(posLeftTupleSlots == 0){
-          leftNext = new VTuple (leftTupleSlots.get(posLeftTupleSlots));
+          leftNext = leftTupleSlots.get(posLeftTupleSlots);
           posLeftTupleSlots = posLeftTupleSlots + 1;
         }
 
         if(posRightTupleSlots <= (rightTupleSlots.size() -1)) {
-          Tuple aTuple = new VTuple(rightTupleSlots.get(posRightTupleSlots));
+          Tuple aTuple = rightTupleSlots.get(posRightTupleSlots);
           posRightTupleSlots = posRightTupleSlots + 1;
           frameTuple.set(leftNext, aTuple);
           joinQual.eval(frameTuple);
-          projector.eval(frameTuple, outTuple);
-          return outTuple;
+          return projector.eval(frameTuple);
         } else {
           // right (inner) slots reached end and should be rewind if there are still tuples in the outer slots
           if(posLeftTupleSlots <= (leftTupleSlots.size()-1)) {
             //rewind the right slots position
             posRightTupleSlots = 0;
-            Tuple aTuple = new VTuple(rightTupleSlots.get(posRightTupleSlots));
+            Tuple aTuple = rightTupleSlots.get(posRightTupleSlots);
             posRightTupleSlots = posRightTupleSlots + 1;
-            leftNext = new VTuple (leftTupleSlots.get(posLeftTupleSlots));
+            leftNext = leftTupleSlots.get(posLeftTupleSlots);
             posLeftTupleSlots = posLeftTupleSlots + 1;
 
             frameTuple.set(leftNext, aTuple);
             joinQual.eval(frameTuple);
-            projector.eval(frameTuple, outTuple);
-            return outTuple;
+            return projector.eval(frameTuple);
           }
         }
       } // the second if end false

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/MergeJoinExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/MergeJoinExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/MergeJoinExec.java
index bf9b4cd..3d8c108 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/MergeJoinExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/MergeJoinExec.java
@@ -21,28 +21,25 @@ package org.apache.tajo.engine.planner.physical;
 import com.google.common.base.Preconditions;
 import org.apache.tajo.catalog.SortSpec;
 import org.apache.tajo.plan.logical.JoinNode;
-import org.apache.tajo.storage.FrameTuple;
 import org.apache.tajo.storage.Tuple;
 import org.apache.tajo.storage.TupleComparator;
 import org.apache.tajo.storage.VTuple;
 import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
-import java.util.ArrayList;
 import java.util.Iterator;
-import java.util.List;
 
 public class MergeJoinExec extends CommonJoinExec {
 
   // temporal tuples and states for nested loop join
-  private FrameTuple frameTuple;
   private Tuple outerTuple = null;
   private Tuple innerTuple = null;
-  private Tuple outTuple = null;
   private Tuple outerNext = null;
+  private final Tuple prevOuterTuple;
+  private final Tuple prevInnerTuple;
 
-  private List<Tuple> outerTupleSlots;
-  private List<Tuple> innerTupleSlots;
+  private TupleList outerTupleSlots;
+  private TupleList innerTupleSlots;
   private Iterator<Tuple> outerIterator;
   private Iterator<Tuple> innerIterator;
 
@@ -59,8 +56,8 @@ public class MergeJoinExec extends CommonJoinExec {
     Preconditions.checkArgument(plan.hasJoinQual(), "Sort-merge join is only used for the equi-join, " +
         "but there is no join condition");
 
-    this.outerTupleSlots = new ArrayList<Tuple>(INITIAL_TUPLE_SLOT);
-    this.innerTupleSlots = new ArrayList<Tuple>(INITIAL_TUPLE_SLOT);
+    this.outerTupleSlots = new TupleList(INITIAL_TUPLE_SLOT);
+    this.innerTupleSlots = new TupleList(INITIAL_TUPLE_SLOT);
     SortSpec[][] sortSpecs = new SortSpec[2][];
     sortSpecs[0] = outerSortKey;
     sortSpecs[1] = innerSortKey;
@@ -71,14 +68,12 @@ public class MergeJoinExec extends CommonJoinExec {
         plan.getJoinQual(), outer.getSchema(), inner.getSchema());
     this.outerIterator = outerTupleSlots.iterator();
     this.innerIterator = innerTupleSlots.iterator();
-    
-    // for join
-    frameTuple = new FrameTuple();
-    outTuple = new VTuple(outSchema.size());
+
+    prevOuterTuple = new VTuple(leftChild.getSchema().size());
+    prevInnerTuple = new VTuple(rightChild.getSchema().size());
   }
 
   public Tuple next() throws IOException {
-    Tuple previous;
 
     while (!context.isStopped()) {
       if (!outerIterator.hasNext() && !innerIterator.hasNext()) {
@@ -108,32 +103,28 @@ public class MergeJoinExec extends CommonJoinExec {
           }
         }
 
-        try {
-          previous = outerTuple.clone();
-          do {
-            outerTupleSlots.add(outerTuple.clone());
-            outerTuple = leftChild.next();
-            if (outerTuple == null) {
-              end = true;
-              break;
-            }
-          } while (tupleComparator[0].compare(previous, outerTuple) == 0);
-          outerIterator = outerTupleSlots.iterator();
-          outerNext = outerIterator.next();
-
-          previous = innerTuple.clone();
-          do {
-            innerTupleSlots.add(innerTuple.clone());
-            innerTuple = rightChild.next();
-            if (innerTuple == null) {
-              end = true;
-              break;
-            }
-          } while (tupleComparator[1].compare(previous, innerTuple) == 0);
-          innerIterator = innerTupleSlots.iterator();
-        } catch (CloneNotSupportedException e) {
+        prevOuterTuple.put(outerTuple.getValues());
+        do {
+          outerTupleSlots.add(outerTuple);
+          outerTuple = leftChild.next();
+          if (outerTuple == null) {
+            end = true;
+            break;
+          }
+        } while (tupleComparator[0].compare(prevOuterTuple, outerTuple) == 0);
+        outerIterator = outerTupleSlots.iterator();
+        outerNext = outerIterator.next();
 
-        }
+        prevInnerTuple.put(innerTuple.getValues());
+        do {
+          innerTupleSlots.add(innerTuple);
+          innerTuple = rightChild.next();
+          if (innerTuple == null) {
+            end = true;
+            break;
+          }
+        } while (tupleComparator[1].compare(prevInnerTuple, innerTuple) == 0);
+        innerIterator = innerTupleSlots.iterator();
       }
 
       if(!innerIterator.hasNext()){
@@ -144,8 +135,7 @@ public class MergeJoinExec extends CommonJoinExec {
       frameTuple.set(outerNext, innerIterator.next());
 
       if (joinQual.eval(frameTuple).isTrue()) {
-        projector.eval(frameTuple, outTuple);
-        return outTuple;
+        return projector.eval(frameTuple);
       }
     }
     return null;

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/NLJoinExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/NLJoinExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/NLJoinExec.java
index 964a523..d3214c3 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/NLJoinExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/NLJoinExec.java
@@ -19,9 +19,7 @@
 package org.apache.tajo.engine.planner.physical;
 
 import org.apache.tajo.plan.logical.JoinNode;
-import org.apache.tajo.storage.FrameTuple;
 import org.apache.tajo.storage.Tuple;
-import org.apache.tajo.storage.VTuple;
 import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
@@ -30,18 +28,14 @@ public class NLJoinExec extends CommonJoinExec {
 
   // temporal tuples and states for nested loop join
   private boolean needNewOuter;
-  private FrameTuple frameTuple;
   private Tuple outerTuple = null;
   private Tuple innerTuple = null;
-  private Tuple outTuple = null;
 
   public NLJoinExec(TaskAttemptContext context, JoinNode plan, PhysicalExec outer,
       PhysicalExec inner) {
     super(context, plan, outer, inner);
     // for join
     needNewOuter = true;
-    frameTuple = new FrameTuple();
-    outTuple = new VTuple(outSchema.size());
   }
 
   public Tuple next() throws IOException {
@@ -64,12 +58,10 @@ public class NLJoinExec extends CommonJoinExec {
       frameTuple.set(outerTuple, innerTuple);
       if (hasJoinQual) {
         if (joinQual.eval(frameTuple).isTrue()) {
-          projector.eval(frameTuple, outTuple);
-          return outTuple;
+          return projector.eval(frameTuple);
         }
       } else {
-        projector.eval(frameTuple, outTuple);
-        return outTuple;
+        return projector.eval(frameTuple);
       }
     }
     return null;

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/ProjectionExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/ProjectionExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/ProjectionExec.java
index 72a667d..8a79005 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/ProjectionExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/ProjectionExec.java
@@ -24,7 +24,6 @@ package org.apache.tajo.engine.planner.physical;
 import org.apache.tajo.engine.planner.Projector;
 import org.apache.tajo.plan.logical.Projectable;
 import org.apache.tajo.storage.Tuple;
-import org.apache.tajo.storage.VTuple;
 import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
@@ -33,7 +32,6 @@ public class ProjectionExec extends UnaryPhysicalExec {
   private Projectable plan;
 
   // for projection
-  private Tuple outTuple;
   private Projector projector;
   
   public ProjectionExec(TaskAttemptContext context, Projectable plan,
@@ -45,7 +43,6 @@ public class ProjectionExec extends UnaryPhysicalExec {
   public void init() throws IOException {
     super.init();
 
-    this.outTuple = new VTuple(outSchema.size());
     this.projector = new Projector(context, inSchema, outSchema, this.plan.getTargets());
   }
 
@@ -57,8 +54,7 @@ public class ProjectionExec extends UnaryPhysicalExec {
       return null;
     }
 
-    projector.eval(tuple, outTuple);
-    return outTuple;
+    return projector.eval(tuple);
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/RangeShuffleFileWriteExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/RangeShuffleFileWriteExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/RangeShuffleFileWriteExec.java
index bbb21fe..ac3d1b2 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/RangeShuffleFileWriteExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/RangeShuffleFileWriteExec.java
@@ -24,8 +24,12 @@ import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.fs.RawLocalFileSystem;
 import org.apache.hadoop.io.IOUtils;
-import org.apache.tajo.catalog.*;
+import org.apache.tajo.catalog.CatalogUtil;
+import org.apache.tajo.catalog.Schema;
+import org.apache.tajo.catalog.SortSpec;
+import org.apache.tajo.catalog.TableMeta;
 import org.apache.tajo.conf.TajoConf;
+import org.apache.tajo.engine.planner.KeyProjector;
 import org.apache.tajo.plan.util.PlannerUtil;
 import org.apache.tajo.storage.*;
 import org.apache.tajo.storage.index.bst.BSTIndex;
@@ -40,9 +44,8 @@ import java.io.IOException;
  * specified order of shuffle keys.
  */
 public class RangeShuffleFileWriteExec extends UnaryPhysicalExec {
-  private static Log LOG = LogFactory.getLog(RangeShuffleFileWriteExec.class);
+  private final static Log LOG = LogFactory.getLog(RangeShuffleFileWriteExec.class);
   private final SortSpec[] sortSpecs;
-  private int [] indexKeys = null;
   private Schema keySchema;
 
   private BSTIndex.BSTIndexWriter indexWriter;
@@ -50,6 +53,8 @@ public class RangeShuffleFileWriteExec extends UnaryPhysicalExec {
   private FileAppender appender;
   private TableMeta meta;
 
+  private KeyProjector keyProjector;
+
   public RangeShuffleFileWriteExec(final TaskAttemptContext context,
                                    final PhysicalExec child, final Schema inSchema, final Schema outSchema,
                                    final SortSpec[] sortSpecs) throws IOException {
@@ -60,14 +65,8 @@ public class RangeShuffleFileWriteExec extends UnaryPhysicalExec {
   public void init() throws IOException {
     super.init();
 
-    indexKeys = new int[sortSpecs.length];
     keySchema = PlannerUtil.sortSpecsToSchema(sortSpecs);
-
-    Column col;
-    for (int i = 0 ; i < sortSpecs.length; i++) {
-      col = sortSpecs[i].getSortKey();
-      indexKeys[i] = inSchema.getColumnId(col.getQualifiedName());
-    }
+    keyProjector = new KeyProjector(inSchema, keySchema.toArray());
 
     BSTIndex bst = new BSTIndex(new TajoConf());
     this.comp = new BaseTupleComparator(keySchema, sortSpecs);
@@ -91,24 +90,17 @@ public class RangeShuffleFileWriteExec extends UnaryPhysicalExec {
   public Tuple next() throws IOException {
     Tuple tuple;
     Tuple keyTuple;
-    Tuple prevKeyTuple = null;
+    Tuple prevKeyTuple = new VTuple(keySchema.size());
     long offset;
 
-
-    try {
-      while(!context.isStopped() && (tuple = child.next()) != null) {
-        offset = appender.getOffset();
-        appender.addTuple(tuple);
-        keyTuple = new VTuple(keySchema.size());
-        RowStoreUtil.project(tuple, keyTuple, indexKeys);
-        if (prevKeyTuple == null || !prevKeyTuple.equals(keyTuple)) {
-          indexWriter.write(keyTuple, offset);
-          prevKeyTuple = keyTuple;
-        }
+    while(!context.isStopped() && (tuple = child.next()) != null) {
+      offset = appender.getOffset();
+      appender.addTuple(tuple);
+      keyTuple = keyProjector.project(tuple);
+      if (!prevKeyTuple.equals(keyTuple)) {
+        indexWriter.write(keyTuple, offset);
+        prevKeyTuple.put(keyTuple.getValues());
       }
-    } catch (RuntimeException e) {
-      e.printStackTrace();
-      throw e;
     }
 
     return null;

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/RightOuterMergeJoinExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/RightOuterMergeJoinExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/RightOuterMergeJoinExec.java
index fd825b1..239c6ab 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/RightOuterMergeJoinExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/RightOuterMergeJoinExec.java
@@ -20,29 +20,26 @@ package org.apache.tajo.engine.planner.physical;
 
 import com.google.common.base.Preconditions;
 import org.apache.tajo.catalog.SortSpec;
-import org.apache.tajo.datum.DatumFactory;
-import org.apache.tajo.engine.utils.TupleUtil;
 import org.apache.tajo.plan.logical.JoinNode;
-import org.apache.tajo.storage.FrameTuple;
+import org.apache.tajo.storage.NullTuple;
 import org.apache.tajo.storage.Tuple;
 import org.apache.tajo.storage.TupleComparator;
 import org.apache.tajo.storage.VTuple;
 import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
 
 public class RightOuterMergeJoinExec extends CommonJoinExec {
   // temporal tuples and states for nested loop join
-  private FrameTuple frameTuple;
   private Tuple leftTuple = null;
   private Tuple rightTuple = null;
-  private Tuple outTuple = null;
+  private Tuple prevLeftTuple;
+  private Tuple prevRightTuple;
   private Tuple nextLeft = null;
+  private Tuple nullPaddedTuple;
 
-  private List<Tuple> leftTupleSlots;
-  private List<Tuple> innerTupleSlots;
+  private TupleList leftTupleSlots;
+  private TupleList innerTupleSlots;
 
   private JoinTupleComparator joinComparator = null;
   private TupleComparator [] tupleComparator = null;
@@ -62,8 +59,8 @@ public class RightOuterMergeJoinExec extends CommonJoinExec {
     super(context, plan, outer, inner);
     Preconditions.checkArgument(plan.hasJoinQual(), "Sort-merge join is only used for the equi-join, " +
         "but there is no join condition");
-    this.leftTupleSlots = new ArrayList<Tuple>(INITIAL_TUPLE_SLOT);
-    this.innerTupleSlots = new ArrayList<Tuple>(INITIAL_TUPLE_SLOT);
+    this.leftTupleSlots = new TupleList(INITIAL_TUPLE_SLOT);
+    this.innerTupleSlots = new TupleList(INITIAL_TUPLE_SLOT);
     SortSpec[][] sortSpecs = new SortSpec[2][];
     sortSpecs[0] = outerSortKey;
     sortSpecs[1] = innerSortKey;
@@ -72,22 +69,8 @@ public class RightOuterMergeJoinExec extends CommonJoinExec {
     this.tupleComparator = PhysicalPlanUtil.getComparatorsFromJoinQual(
         plan.getJoinQual(), outer.getSchema(), inner.getSchema());
 
-    // for join
-    frameTuple = new FrameTuple();
-    outTuple = new VTuple(outSchema.size());
-
     leftNumCols = outer.getSchema().size();
-  }
-
-  /**
-   * creates a tuple of a given size filled with NULL values in all fields
-   */
-  private Tuple createNullPaddedTuple(int columnNum){
-    VTuple tuple = new VTuple(columnNum);
-    for (int i = 0; i < columnNum; i++) {
-      tuple.put(i, DatumFactory.createNullDatum());
-    }
-    return tuple;
+    nullPaddedTuple = NullTuple.create(leftNumCols);
   }
 
   /**
@@ -101,7 +84,9 @@ public class RightOuterMergeJoinExec extends CommonJoinExec {
    * @return
    * @throws IOException
    */
+  @Override
   public Tuple next() throws IOException {
+    Tuple outTuple;
 
     while (!context.isStopped()) {
       boolean newRound = false;
@@ -130,9 +115,8 @@ public class RightOuterMergeJoinExec extends CommonJoinExec {
             return null;
           } else {
             // output a tuple with the nulls padded leftTuple
-            Tuple nullPaddedTuple = createNullPaddedTuple(leftNumCols);
             frameTuple.set(nullPaddedTuple, rightTuple);
-            projector.eval(frameTuple, outTuple);
+            outTuple = projector.eval(frameTuple);
 
             // we simulate we found a match, which is exactly the null padded one
             rightTuple = rightChild.next();
@@ -168,11 +152,10 @@ public class RightOuterMergeJoinExec extends CommonJoinExec {
           }
         }
         if (rightFiltered(rightTuple)) {
-          Tuple nullPaddedTuple = createNullPaddedTuple(leftNumCols);
           frameTuple.set(nullPaddedTuple, rightTuple);
-          projector.eval(frameTuple, outTuple);
-
+          outTuple = projector.eval(frameTuple);
           rightTuple = null;
+
           return outTuple;
         }
         initRightDone = true;
@@ -202,9 +185,8 @@ public class RightOuterMergeJoinExec extends CommonJoinExec {
           if (cmp > 0) {
             // before getting a new tuple from the right,  a left null padded tuple should be built
             // output a tuple with the nulls padded left tuple
-            Tuple nullPaddedTuple = createNullPaddedTuple(leftNumCols);
             frameTuple.set(nullPaddedTuple, rightTuple);
-            projector.eval(frameTuple, outTuple);
+            outTuple = projector.eval(frameTuple);
 
             // we simulate we found a match, which is exactly the null padded one
             // BEFORE RETURN, MOVE FORWARD
@@ -225,7 +207,6 @@ public class RightOuterMergeJoinExec extends CommonJoinExec {
         // END MOVE FORWARDING STAGE
         //////////////////////////////////////////////////////////////////////
 
-        Tuple previous = null;
         // once a match is found, retain all tuples with this key in tuple slots on each side
         if(!end) {
           endInPopulationStage = false;
@@ -233,26 +214,33 @@ public class RightOuterMergeJoinExec extends CommonJoinExec {
           boolean endOuter = false;
           boolean endInner = false;
 
-          previous = new VTuple(leftTuple);
+          if (prevLeftTuple == null) {
+            prevLeftTuple = new VTuple(leftTuple.getValues());
+          } else {
+            prevLeftTuple.put(leftTuple.getValues());
+          }
           do {
-            leftTupleSlots.add(new VTuple(leftTuple));
+            leftTupleSlots.add(leftTuple);
             leftTuple = leftChild.next();
             if( leftTuple == null) {
               endOuter = true;
             }
-          } while ((endOuter != true) && (tupleComparator[0].compare(previous, leftTuple) == 0));
+          } while ((endOuter != true) && (tupleComparator[0].compare(prevLeftTuple, leftTuple) == 0));
           posLeftTupleSlots = 0;
 
-          previous = new VTuple(rightTuple);
-
+          if (prevRightTuple == null) {
+            prevRightTuple = new VTuple(rightTuple.getValues());
+          } else {
+            prevRightTuple.put(rightTuple.getValues());
+          }
           do {
-            innerTupleSlots.add(new VTuple(rightTuple));
+            innerTupleSlots.add(rightTuple);
             rightTuple = rightChild.next();
             if(rightTuple == null) {
               endInner = true;
             }
 
-          } while ((endInner != true) && (tupleComparator[1].compare(previous, rightTuple) == 0) );
+          } while ((endInner != true) && (tupleComparator[1].compare(prevRightTuple, rightTuple) == 0) );
           posRightTupleSlots = 0;
 
           if ((endOuter == true) || (endInner == true)) {
@@ -260,10 +248,9 @@ public class RightOuterMergeJoinExec extends CommonJoinExec {
             endInPopulationStage = true;
           }
         } // if end false
-        if (previous != null && rightFiltered(previous)) {
-          Tuple nullPaddedTuple = createNullPaddedTuple(leftNumCols);
-          frameTuple.set(nullPaddedTuple, previous);
-          projector.eval(frameTuple, outTuple);
+        if (prevRightTuple != null && rightFiltered(prevRightTuple)) {
+          frameTuple.set(nullPaddedTuple, prevRightTuple);
+          outTuple = projector.eval(frameTuple);
 
           // reset tuple slots for a new round
           leftTupleSlots.clear();
@@ -283,48 +270,42 @@ public class RightOuterMergeJoinExec extends CommonJoinExec {
       if ((end == false) || ((end == true) && (endInPopulationStage == true))){
 
         if(posLeftTupleSlots == 0){
-          nextLeft = new VTuple (leftTupleSlots.get(posLeftTupleSlots));
+          nextLeft = leftTupleSlots.get(posLeftTupleSlots);
           posLeftTupleSlots = posLeftTupleSlots + 1;
         }
 
 
         if(posRightTupleSlots <= (innerTupleSlots.size() -1)) {
 
-          Tuple aTuple = new VTuple(innerTupleSlots.get(posRightTupleSlots));
+          Tuple aTuple = innerTupleSlots.get(posRightTupleSlots);
           posRightTupleSlots = posRightTupleSlots + 1;
 
           frameTuple.set(nextLeft, aTuple);
           if (joinQual.eval(frameTuple).asBool()) {
-            projector.eval(frameTuple, outTuple);
-            return outTuple;
+            return projector.eval(frameTuple);
           } else {
             // padding null
-            Tuple nullPaddedTuple = TupleUtil.createNullPaddedTuple(leftNumCols);
             frameTuple.set(nullPaddedTuple, aTuple);
-            projector.eval(frameTuple, outTuple);
-            return outTuple;
+            return projector.eval(frameTuple);
           }
         } else {
           // right (inner) slots reached end and should be rewind if there are still tuples in the outer slots
           if(posLeftTupleSlots <= (leftTupleSlots.size() - 1)) {
             //rewind the right slots position
             posRightTupleSlots = 0;
-            Tuple aTuple = new VTuple(innerTupleSlots.get(posRightTupleSlots));
+            Tuple aTuple = innerTupleSlots.get(posRightTupleSlots);
             posRightTupleSlots = posRightTupleSlots + 1;
-            nextLeft = new VTuple (leftTupleSlots.get(posLeftTupleSlots));
+            nextLeft = leftTupleSlots.get(posLeftTupleSlots);
             posLeftTupleSlots = posLeftTupleSlots + 1;
 
             frameTuple.set(nextLeft, aTuple);
 
             if (joinQual.eval(frameTuple).asBool()) {
-              projector.eval(frameTuple, outTuple);
-              return outTuple;
+              return projector.eval(frameTuple);
             } else {
               // padding null
-              Tuple nullPaddedTuple = TupleUtil.createNullPaddedTuple(leftNumCols);
               frameTuple.set(nullPaddedTuple, aTuple);
-              projector.eval(frameTuple, outTuple);
-              return outTuple;
+              return projector.eval(frameTuple);
             }
           }
         }
@@ -340,6 +321,9 @@ public class RightOuterMergeJoinExec extends CommonJoinExec {
     innerTupleSlots.clear();
     posRightTupleSlots = -1;
     posLeftTupleSlots = -1;
+    leftTuple = rightTuple = null;
+    prevLeftTuple = prevRightTuple = null;
+    nextLeft = null;
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SeqScanExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SeqScanExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SeqScanExec.java
index b4f7a38..b49fa40 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SeqScanExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SeqScanExec.java
@@ -247,9 +247,8 @@ public class SeqScanExec extends ScanExec {
   public Tuple next() throws IOException {
 
     while(scanIt.hasNext()) {
-      Tuple outTuple = new VTuple(outColumnNum);
       Tuple t = scanIt.next();
-      projector.eval(t, outTuple);
+      Tuple outTuple = projector.eval(t);
       outTuple.setOffset(t.getOffset());
       return outTuple;
     }

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SortAggregateExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SortAggregateExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SortAggregateExec.java
index 2feecd1..71602b8 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SortAggregateExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SortAggregateExec.java
@@ -18,6 +18,7 @@
 
 package org.apache.tajo.engine.planner.physical;
 
+import org.apache.tajo.catalog.Column;
 import org.apache.tajo.plan.function.FunctionContext;
 import org.apache.tajo.plan.logical.GroupbyNode;
 import org.apache.tajo.storage.Tuple;
@@ -41,24 +42,38 @@ import java.io.IOException;
  * it makes an output tuple.
  */
 public class SortAggregateExec extends AggregationExec {
+  private final int groupingKeyIds[];
   private Tuple lastKey = null;
+  private final Tuple currentKey;
+  private final Tuple outTuple;
   private boolean finished = false;
   private FunctionContext contexts[];
 
   public SortAggregateExec(TaskAttemptContext context, GroupbyNode plan, PhysicalExec child) throws IOException {
     super(context, plan, child);
     contexts = new FunctionContext[plan.getAggFunctions() == null ? 0 : plan.getAggFunctions().length];
+
+    final Column [] keyColumns = plan.getGroupingColumns();
+    groupingKeyIds = new int[groupingKeyNum];
+    Column col;
+    for (int idx = 0; idx < plan.getGroupingColumns().length; idx++) {
+      col = keyColumns[idx];
+      if (col.hasQualifier()) {
+        groupingKeyIds[idx] = inSchema.getColumnId(col.getQualifiedName());
+      } else {
+        groupingKeyIds[idx] = inSchema.getColumnIdByName(col.getSimpleName());
+      }
+    }
+    currentKey = new VTuple(groupingKeyNum);
+    outTuple = new VTuple(outSchema.size());
   }
 
   @Override
   public Tuple next() throws IOException {
-    Tuple currentKey;
     Tuple tuple = null;
-    Tuple outputTuple = null;
 
     while(!context.isStopped() && (tuple = child.next()) != null) {
       // get a key tuple
-      currentKey = new VTuple(groupingKeyIds.length);
       for(int i = 0; i < groupingKeyIds.length; i++) {
         currentKey.put(i, tuple.asDatum(groupingKeyIds[i]));
       }
@@ -75,7 +90,7 @@ public class SortAggregateExec extends AggregationExec {
               aggFunctions[i].merge(contexts[i], tuple);
             }
           }
-          lastKey = currentKey;
+          lastKey = new VTuple(currentKey.getValues());
         } else {
           // aggregate
           for (int i = 0; i < aggFunctionsNum; i++) {
@@ -85,14 +100,13 @@ public class SortAggregateExec extends AggregationExec {
 
       } else { /** Finalization State */
         // finalize aggregate and return
-        outputTuple = new VTuple(outSchema.size());
         int tupleIdx = 0;
 
         for(; tupleIdx < groupingKeyNum; tupleIdx++) {
-          outputTuple.put(tupleIdx, lastKey.asDatum(tupleIdx));
+          outTuple.put(tupleIdx, lastKey.asDatum(tupleIdx));
         }
         for(int aggFuncIdx = 0; aggFuncIdx < aggFunctionsNum; tupleIdx++, aggFuncIdx++) {
-          outputTuple.put(tupleIdx, aggFunctions[aggFuncIdx].terminate(contexts[aggFuncIdx]));
+          outTuple.put(tupleIdx, aggFunctions[aggFuncIdx].terminate(contexts[aggFuncIdx]));
         }
 
         for(int evalIdx = 0; evalIdx < aggFunctionsNum; evalIdx++) {
@@ -100,8 +114,8 @@ public class SortAggregateExec extends AggregationExec {
           aggFunctions[evalIdx].merge(contexts[evalIdx], tuple);
         }
 
-        lastKey = currentKey;
-        return outputTuple;
+        lastKey.put(currentKey.getValues());
+        return outTuple;
       }
     } // while loop
 
@@ -110,17 +124,17 @@ public class SortAggregateExec extends AggregationExec {
       return null;
     }
     if (!finished) {
-      outputTuple = new VTuple(outSchema.size());
       int tupleIdx = 0;
       for(; tupleIdx < groupingKeyNum; tupleIdx++) {
-        outputTuple.put(tupleIdx, lastKey.asDatum(tupleIdx));
+        outTuple.put(tupleIdx, lastKey.asDatum(tupleIdx));
       }
       for(int aggFuncIdx = 0; aggFuncIdx < aggFunctionsNum; tupleIdx++, aggFuncIdx++) {
-        outputTuple.put(tupleIdx, aggFunctions[aggFuncIdx].terminate(contexts[aggFuncIdx]));
+        outTuple.put(tupleIdx, aggFunctions[aggFuncIdx].terminate(contexts[aggFuncIdx]));
       }
       finished = true;
+      return outTuple;
     }
-    return outputTuple;
+    return null;
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SortBasedColPartitionStoreExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SortBasedColPartitionStoreExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SortBasedColPartitionStoreExec.java
index a40fc1d..3a0dd38 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SortBasedColPartitionStoreExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SortBasedColPartitionStoreExec.java
@@ -22,7 +22,6 @@
 package org.apache.tajo.engine.planner.physical;
 
 import org.apache.tajo.catalog.statistics.StatisticsUtil;
-import org.apache.tajo.datum.Datum;
 import org.apache.tajo.plan.logical.StoreTableNode;
 import org.apache.tajo.storage.Tuple;
 import org.apache.tajo.storage.VTuple;
@@ -85,7 +84,7 @@ public class SortBasedColPartitionStoreExec extends ColPartitionStoreExec {
           StatisticsUtil.aggregateTableStat(aggregatedStats, appender.getStats());
 
           appender = getNextPartitionAppender(getSubdirectory(currentKey));
-          prevKey = new VTuple(currentKey);
+          prevKey.put(currentKey.getValues());
 
           // reset all states for file rotating
           writtenFileNum = 0;

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SortExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SortExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SortExec.java
index 28be9de..b652b0a 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SortExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/SortExec.java
@@ -26,7 +26,6 @@ import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
 import java.util.Comparator;
-import java.util.List;
 
 public abstract class SortExec extends UnaryPhysicalExec {
 
@@ -40,7 +39,7 @@ public abstract class SortExec extends UnaryPhysicalExec {
     this.comparator = new BaseTupleComparator(inSchema, sortSpecs);
   }
 
-  protected TupleSorter getSorter(List<Tuple> tupleSlots) {
+  protected TupleSorter getSorter(TupleList tupleSlots) {
     if (!tupleSlots.isEmpty() && ComparableVector.isVectorizable(sortSpecs)) {
       return new VectorizedSorter(tupleSlots, sortSpecs, comparator.getSortKeyIds());
     }

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/StoreTableExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/StoreTableExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/StoreTableExec.java
index 6031fdb..c317f7f 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/StoreTableExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/StoreTableExec.java
@@ -49,7 +49,6 @@ public class StoreTableExec extends UnaryPhysicalExec {
   private PersistentStoreNode plan;
   private TableMeta meta;
   private Appender appender;
-  private Tuple tuple;
 
   // for file punctuation
   private TableStats sumStats;                  // for aggregating all stats of written files
@@ -125,6 +124,7 @@ public class StoreTableExec extends UnaryPhysicalExec {
    */
   @Override
   public Tuple next() throws IOException {
+    Tuple tuple;
     while(!context.isStopped() && (tuple = child.next()) != null) {
       appender.addTuple(tuple);
 

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/TupleList.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/TupleList.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/TupleList.java
new file mode 100644
index 0000000..71ccae1
--- /dev/null
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/TupleList.java
@@ -0,0 +1,44 @@
+/**
+ * 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.tajo.engine.planner.physical;
+
+import org.apache.tajo.storage.Tuple;
+import org.apache.tajo.storage.VTuple;
+
+import java.util.ArrayList;
+
+/**
+ * In TupleList, input tuples are automatically cloned whenever the add() method is called.
+ * This data structure is usually used in physical operators like hash join or hash aggregation.
+ */
+public class TupleList extends ArrayList<Tuple> {
+
+  public TupleList() {
+    super();
+  }
+
+  public TupleList(int initialCapacity) {
+    super(initialCapacity);
+  }
+
+  @Override
+  public boolean add(Tuple tuple) {
+    return super.add(new VTuple(tuple));
+  }
+}

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/TupleMap.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/TupleMap.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/TupleMap.java
new file mode 100644
index 0000000..6f72522
--- /dev/null
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/TupleMap.java
@@ -0,0 +1,74 @@
+/**
+ * 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.tajo.engine.planner.physical;
+
+import org.apache.tajo.annotation.Nullable;
+
+import java.util.HashMap;
+
+/**
+ * TupleMap is a map which uses KeyTuple with its key.
+ * Please note that every put() call creates a copy of input KeyTuple.
+ * This data structure is usually used in physical operators like hash join or hash aggregation.
+ *
+ * @param <E> value type
+ */
+public class TupleMap<E> extends HashMap<KeyTuple, E> {
+
+  public TupleMap() {
+    super();
+  }
+
+  public TupleMap(int initialCapacity) {
+    super(initialCapacity);
+  }
+
+  public TupleMap(TupleMap tupleMap){
+    super(tupleMap);
+  }
+
+  /**
+   * Add a pair of (key, value).
+   * The key is always copied.
+   *
+   * @param key
+   * @param value
+   * @return
+   */
+  @Override
+  public E put(@Nullable KeyTuple key, E value) {
+    if (key != null) {
+      return super.put(new KeyTuple(key.getValues()), value);
+    } else {
+      return super.put(null, value);
+    }
+  }
+
+  /**
+   * Add a pair of (key, value).
+   * The key is not copied.
+   *
+   * @param key
+   * @param value
+   * @return
+   */
+  public E putWihtoutKeyCopy(@Nullable KeyTuple key, E value) {
+    return super.put(key, value);
+  }
+}

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/TupleSet.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/TupleSet.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/TupleSet.java
new file mode 100644
index 0000000..ff131c2
--- /dev/null
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/TupleSet.java
@@ -0,0 +1,34 @@
+/**
+ * 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.tajo.engine.planner.physical;
+
+import java.util.HashSet;
+
+/**
+ * TupleSet is a set which accepts only KeyTuple.
+ * Input tuples are automatically cloned whenever the add() method is called.
+ * This data structure is usually used in physical operators like hash join or hash aggregation.
+ */
+public class TupleSet extends HashSet<KeyTuple> {
+
+  @Override
+  public boolean add(KeyTuple tuple) {
+    return super.add(new KeyTuple(tuple));
+  }
+}

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/TupleSorter.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/TupleSorter.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/TupleSorter.java
index 57fe816..abf2808 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/TupleSorter.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/TupleSorter.java
@@ -22,18 +22,17 @@ import org.apache.tajo.storage.Tuple;
 import org.apache.tajo.storage.TupleComparator;
 
 import java.util.Collections;
-import java.util.List;
 
 public interface TupleSorter {
 
   Iterable<Tuple> sort();
 
-  public static class DefaultSorter implements TupleSorter {
+  class DefaultSorter implements TupleSorter {
 
-    private final List<Tuple> target;
+    private final TupleList target;
     private final TupleComparator comparator;
 
-    public DefaultSorter(List<Tuple> target, TupleComparator comparator) {
+    public DefaultSorter(TupleList target, TupleComparator comparator) {
       this.target = target;
       this.comparator = comparator;
     }

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/VectorizedSorter.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/VectorizedSorter.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/VectorizedSorter.java
index 18d853f..d750f15 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/VectorizedSorter.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/VectorizedSorter.java
@@ -25,7 +25,6 @@ import org.apache.tajo.exception.UnsupportedException;
 import org.apache.tajo.storage.Tuple;
 
 import java.util.Iterator;
-import java.util.List;
 
 /**
  * Extract raw level values (primitive or String/byte[]) from each of key columns before sorting
@@ -35,7 +34,7 @@ public class VectorizedSorter extends ComparableVector implements IndexedSortabl
 
   private final int[] mappings;         // index indirection
 
-  public VectorizedSorter(List<Tuple> source, SortSpec[] sortKeys, int[] keyIndex) {
+  public VectorizedSorter(TupleList source, SortSpec[] sortKeys, int[] keyIndex) {
     super(source.size(), sortKeys, keyIndex);
     source.toArray(tuples);   // wish it's array list
     mappings = new int[tuples.length];


[3/3] tajo git commit: TAJO-1343: Improve the memory usage of physical executors. (jihoon)

Posted by ji...@apache.org.
TAJO-1343: Improve the memory usage of physical executors. (jihoon)

Closes #634


Project: http://git-wip-us.apache.org/repos/asf/tajo/repo
Commit: http://git-wip-us.apache.org/repos/asf/tajo/commit/4820610f
Tree: http://git-wip-us.apache.org/repos/asf/tajo/tree/4820610f
Diff: http://git-wip-us.apache.org/repos/asf/tajo/diff/4820610f

Branch: refs/heads/master
Commit: 4820610f4a2a384372aaecf5212bd486c79a65b2
Parents: e5b30e5
Author: Jihoon Son <ji...@apache.org>
Authored: Wed Jul 22 18:04:42 2015 +0900
Committer: Jihoon Son <ji...@apache.org>
Committed: Wed Jul 22 18:04:42 2015 +0900

----------------------------------------------------------------------
 CHANGES                                         |   3 +
 .../org/apache/tajo/storage/RowStoreUtil.java   |   1 -
 .../java/org/apache/tajo/conf/TajoConf.java     |   2 -
 .../java/org/apache/tajo/storage/NullTuple.java |   4 +
 .../java/org/apache/tajo/storage/Tuple.java     |   2 +
 .../java/org/apache/tajo/storage/VTuple.java    |   7 +
 .../tajo/engine/planner/KeyProjector.java       |  44 +++++
 .../tajo/engine/planner/PhysicalPlanner.java    |   4 +-
 .../apache/tajo/engine/planner/Projector.java   |  29 +--
 .../planner/physical/AggregationExec.java       |  11 --
 .../engine/planner/physical/BNLJoinExec.java    |  31 ++--
 .../planner/physical/BSTIndexScanExec.java      |  19 +-
 .../planner/physical/CommonHashJoinExec.java    |  70 +++-----
 .../engine/planner/physical/CommonJoinExec.java |  13 +-
 .../planner/physical/ComparableVector.java      |   8 -
 .../DistinctGroupbyFirstAggregationExec.java    | 179 +++++++++----------
 .../DistinctGroupbyHashAggregationExec.java     | 177 +++++++++---------
 .../DistinctGroupbySecondAggregationExec.java   | 108 ++++++-----
 .../DistinctGroupbySortAggregationExec.java     |  27 ++-
 .../DistinctGroupbyThirdAggregationExec.java    |  54 +++---
 .../planner/physical/ExternalSortExec.java      |  34 ++--
 .../planner/physical/HashAggregateExec.java     |  21 +--
 .../planner/physical/HashFullOuterJoinExec.java |  35 ++--
 .../engine/planner/physical/HashJoinExec.java   |  19 +-
 .../planner/physical/HashLeftAntiJoinExec.java  |  11 +-
 .../planner/physical/HashLeftOuterJoinExec.java |  11 +-
 .../planner/physical/HashLeftSemiJoinExec.java  |  11 +-
 .../physical/HashShuffleFileWriteExec.java      |  25 ++-
 .../tajo/engine/planner/physical/KeyTuple.java  |  85 +++++++++
 .../engine/planner/physical/MemSortExec.java    |  11 +-
 .../physical/MergeFullOuterJoinExec.java        |  77 ++++----
 .../engine/planner/physical/MergeJoinExec.java  |  72 ++++----
 .../engine/planner/physical/NLJoinExec.java     |  12 +-
 .../engine/planner/physical/ProjectionExec.java |   6 +-
 .../physical/RangeShuffleFileWriteExec.java     |  42 ++---
 .../physical/RightOuterMergeJoinExec.java       | 102 +++++------
 .../engine/planner/physical/SeqScanExec.java    |   3 +-
 .../planner/physical/SortAggregateExec.java     |  40 +++--
 .../SortBasedColPartitionStoreExec.java         |   3 +-
 .../tajo/engine/planner/physical/SortExec.java  |   3 +-
 .../engine/planner/physical/StoreTableExec.java |   2 +-
 .../tajo/engine/planner/physical/TupleList.java |  44 +++++
 .../tajo/engine/planner/physical/TupleMap.java  |  74 ++++++++
 .../tajo/engine/planner/physical/TupleSet.java  |  34 ++++
 .../engine/planner/physical/TupleSorter.java    |   7 +-
 .../planner/physical/VectorizedSorter.java      |   3 +-
 .../engine/planner/physical/WindowAggExec.java  |  63 ++++---
 .../apache/tajo/engine/query/QueryContext.java  |   7 +-
 .../apache/tajo/engine/utils/CacheHolder.java   |  13 +-
 .../org/apache/tajo/engine/utils/TupleUtil.java |  21 ---
 .../NonForwardQueryResultSystemScanner.java     |   8 +-
 .../org/apache/tajo/TajoTestingCluster.java     |   1 +
 .../tajo/engine/planner/TestLogicalPlanner.java |   4 +-
 .../planner/physical/TestTupleSorter.java       |  11 +-
 .../tajo/engine/query/TestGroupByQuery.java     |  28 +--
 .../TestGroupByQuery/testGroupbyWithJson.json   | 101 +++++++----
 .../TestGroupByQuery/testGroupbyWithLimit3.sql  |   2 +-
 .../testNestedFieldAsGroupbyKey1.sql            |   2 +
 .../TestGroupByQuery/testGroupbyWithJson.result |   4 +-
 .../testGroupbyWithLimit3.result                |   2 +-
 .../testGroupbyWithPythonFunc.result            |   2 +-
 .../testGroupbyWithPythonFunc2.result           |   4 +-
 .../testHavingWithAggFunction.result            |   2 +-
 .../TestGroupByQuery/testPythonUdaf3.result     |   2 +-
 .../testNestedFieldAsGroupbyKey1.result         |   4 +-
 .../testWindowWithAggregation4.result           |   4 +-
 .../testWindowWithAggregation6.result           |   4 +-
 .../org/apache/tajo/jdbc/MetaDataTuple.java     |   5 +
 .../org/apache/tajo/plan/LogicalPlanner.java    |   6 +-
 .../org/apache/tajo/plan/TablePropertyUtil.java |   2 -
 .../org/apache/tajo/storage/FrameTuple.java     |   5 +
 .../java/org/apache/tajo/storage/LazyTuple.java |   6 +
 .../org/apache/tajo/storage/RowStoreUtil.java   |   2 +-
 .../apache/tajo/tuple/offheap/HeapTuple.java    |   4 +
 .../apache/tajo/tuple/offheap/UnSafeTuple.java  |   4 +
 .../apache/tajo/storage/hbase/HBaseScanner.java |   9 +-
 .../java/org/apache/tajo/storage/CSVFile.java   |  64 +++----
 .../java/org/apache/tajo/storage/RawFile.java   |  42 ++---
 .../java/org/apache/tajo/storage/RowFile.java   |   3 +-
 .../apache/tajo/storage/avro/AvroScanner.java   |  26 +--
 .../apache/tajo/storage/index/bst/BSTIndex.java |  20 ++-
 .../org/apache/tajo/storage/rcfile/RCFile.java  |   9 +-
 .../sequencefile/SequenceFileScanner.java       |  50 ++++--
 .../tajo/storage/text/ByteBufLineReader.java    |   2 +-
 .../tajo/storage/text/CSVLineSerializer.java    |   1 +
 .../tajo/storage/text/DelimitedTextFile.java    |  13 +-
 .../apache/tajo/storage/text/TextLineSerDe.java |  14 +-
 .../apache/tajo/storage/TestMergeScanner.java   |   5 +-
 .../org/apache/tajo/storage/TestStorages.java   |   4 +-
 89 files changed, 1217 insertions(+), 948 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/CHANGES
----------------------------------------------------------------------
diff --git a/CHANGES b/CHANGES
index 6001893..e5735f6 100644
--- a/CHANGES
+++ b/CHANGES
@@ -32,6 +32,8 @@ Release 0.11.0 - unreleased
 
   IMPROVEMENT
 
+    TAJO-1343: Improve the memory usage of physical executors. (jihoon)
+
     TAJO-1696: Resource calculator should consider the requested disk resource 
     at the first stage. (jihoon)
 
@@ -2534,3 +2536,4 @@ Release 0.2.0
     TAJO-252: Add DISCLAIMER file. (hyunsik)
 
     TAJO-251: Rename the legacy name *.tql to *.sql. (hyunsik)
+

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-client/src/main/java/org/apache/tajo/storage/RowStoreUtil.java
----------------------------------------------------------------------
diff --git a/tajo-client/src/main/java/org/apache/tajo/storage/RowStoreUtil.java b/tajo-client/src/main/java/org/apache/tajo/storage/RowStoreUtil.java
index 5b4a308..87282a0 100644
--- a/tajo-client/src/main/java/org/apache/tajo/storage/RowStoreUtil.java
+++ b/tajo-client/src/main/java/org/apache/tajo/storage/RowStoreUtil.java
@@ -44,7 +44,6 @@ public class RowStoreUtil {
   }
 
   public static Tuple project(Tuple in, Tuple out, int[] targetIds) {
-    out.clear();
     for (int idx = 0; idx < targetIds.length; idx++) {
       out.put(idx, in.asDatum(targetIds[idx]));
     }

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-common/src/main/java/org/apache/tajo/conf/TajoConf.java
----------------------------------------------------------------------
diff --git a/tajo-common/src/main/java/org/apache/tajo/conf/TajoConf.java b/tajo-common/src/main/java/org/apache/tajo/conf/TajoConf.java
index b876737..910d6bc 100644
--- a/tajo-common/src/main/java/org/apache/tajo/conf/TajoConf.java
+++ b/tajo-common/src/main/java/org/apache/tajo/conf/TajoConf.java
@@ -266,8 +266,6 @@ public class TajoConf extends Configuration {
     EXECUTOR_EXTERNAL_SORT_THREAD_NUM("tajo.executor.external-sort.thread-num", 1),
     EXECUTOR_EXTERNAL_SORT_FANOUT("tajo.executor.external-sort.fanout-num", 8),
 
-    EXECUTOR_INNER_JOIN_INMEMORY_HASH_TABLE_SIZE("tajo.executor.join.inner.in-memory-table-num", (long)1000000),
-
     // Metrics ----------------------------------------------------------------
     METRICS_PROPERTY_FILENAME("tajo.metrics.property.file", "tajo-metrics.properties"),
 

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-common/src/main/java/org/apache/tajo/storage/NullTuple.java
----------------------------------------------------------------------
diff --git a/tajo-common/src/main/java/org/apache/tajo/storage/NullTuple.java b/tajo-common/src/main/java/org/apache/tajo/storage/NullTuple.java
index a17ef01..967efce 100644
--- a/tajo-common/src/main/java/org/apache/tajo/storage/NullTuple.java
+++ b/tajo-common/src/main/java/org/apache/tajo/storage/NullTuple.java
@@ -87,6 +87,10 @@ public class NullTuple implements Tuple, Cloneable {
   }
 
   @Override
+  public void clearOffset() {
+  }
+
+  @Override
   public void put(int fieldId, Tuple tuple) {
     throw new UnsupportedOperationException();
   }

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-common/src/main/java/org/apache/tajo/storage/Tuple.java
----------------------------------------------------------------------
diff --git a/tajo-common/src/main/java/org/apache/tajo/storage/Tuple.java b/tajo-common/src/main/java/org/apache/tajo/storage/Tuple.java
index 7eb56bd..f4a61e6 100644
--- a/tajo-common/src/main/java/org/apache/tajo/storage/Tuple.java
+++ b/tajo-common/src/main/java/org/apache/tajo/storage/Tuple.java
@@ -46,6 +46,8 @@ public interface Tuple extends Cloneable {
 
   int size(int fieldId);
 
+  void clearOffset();
+
   void setOffset(long offset);
 
   long getOffset();

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-common/src/main/java/org/apache/tajo/storage/VTuple.java
----------------------------------------------------------------------
diff --git a/tajo-common/src/main/java/org/apache/tajo/storage/VTuple.java b/tajo-common/src/main/java/org/apache/tajo/storage/VTuple.java
index 2c81e54..d7b648d 100644
--- a/tajo-common/src/main/java/org/apache/tajo/storage/VTuple.java
+++ b/tajo-common/src/main/java/org/apache/tajo/storage/VTuple.java
@@ -73,6 +73,7 @@ public class VTuple implements Tuple, Cloneable {
 
   @Override
   public void clear() {
+    clearOffset();
     for (int i=0; i < values.length; i++) {
       values[i] = null;
     }
@@ -100,7 +101,9 @@ public class VTuple implements Tuple, Cloneable {
     return values[fieldId].size();
   }
 
+  @Override
   public void put(Datum [] values) {
+    clearOffset();
     System.arraycopy(values, 0, this.values, 0, values.length);
   }
 
@@ -111,6 +114,10 @@ public class VTuple implements Tuple, Cloneable {
     return this.values[fieldId];
   }
 
+  public void clearOffset() {
+    this.offset = -1;
+  }
+
   public void setOffset(long offset) {
     this.offset = offset;
   }

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/KeyProjector.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/KeyProjector.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/KeyProjector.java
new file mode 100644
index 0000000..f6220a8
--- /dev/null
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/KeyProjector.java
@@ -0,0 +1,44 @@
+/**
+ * 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.tajo.engine.planner;
+
+import org.apache.tajo.catalog.Column;
+import org.apache.tajo.catalog.Schema;
+import org.apache.tajo.engine.planner.physical.KeyTuple;
+import org.apache.tajo.storage.RowStoreUtil;
+import org.apache.tajo.storage.Tuple;
+
+public class KeyProjector {
+
+  private final KeyTuple keyTuple;
+  private final int projectIds[];
+
+  public KeyProjector(Schema inSchema, Column[] keyColumns) {
+    keyTuple = new KeyTuple(keyColumns.length);
+    projectIds = new int[keyColumns.length];
+    for (int i = 0; i < keyColumns.length; i++) {
+      projectIds[i] = inSchema.getColumnId(keyColumns[i].getQualifiedName());
+    }
+  }
+
+  public KeyTuple project(Tuple tuple) {
+    RowStoreUtil.project(tuple, keyTuple, projectIds);
+    return keyTuple;
+  }
+}

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/PhysicalPlanner.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/PhysicalPlanner.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/PhysicalPlanner.java
index d4c57db..0983dc6 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/PhysicalPlanner.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/PhysicalPlanner.java
@@ -30,7 +30,7 @@ import org.apache.tajo.exception.InternalException;
  * This class generates a physical execution plan.
  */
 public interface PhysicalPlanner {
-  public PhysicalExec createPlan(TaskAttemptContext context,
-                                 LogicalNode logicalPlan)
+  PhysicalExec createPlan(TaskAttemptContext context,
+                          LogicalNode logicalPlan)
       throws InternalException;
 }

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/Projector.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/Projector.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/Projector.java
index a73478f..ba8ec32 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/Projector.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/Projector.java
@@ -20,42 +20,44 @@ package org.apache.tajo.engine.planner;
 
 import org.apache.tajo.SessionVars;
 import org.apache.tajo.catalog.Schema;
-import org.apache.tajo.plan.util.PlannerUtil;
 import org.apache.tajo.plan.Target;
 import org.apache.tajo.plan.expr.EvalNode;
+import org.apache.tajo.plan.util.PlannerUtil;
 import org.apache.tajo.storage.Tuple;
+import org.apache.tajo.storage.VTuple;
 import org.apache.tajo.worker.TaskAttemptContext;
 
 public class Projector {
   private final TaskAttemptContext context;
   private final Schema inSchema;
-  private final Target[] targets;
 
   // for projection
-  private final int targetNum;
   private final EvalNode[] evals;
 
+  private final Tuple outTuple;
+
   public Projector(TaskAttemptContext context, Schema inSchema, Schema outSchema, Target [] targets) {
     this.context = context;
     this.inSchema = inSchema;
+    Target[] realTargets;
     if (targets == null) {
-      this.targets = PlannerUtil.schemaToTargets(outSchema);
+      realTargets = PlannerUtil.schemaToTargets(outSchema);
     } else {
-      this.targets = targets;
+      realTargets = targets;
     }
 
-    this.targetNum = this.targets.length;
-    evals = new EvalNode[targetNum];
+    outTuple = new VTuple(realTargets.length);
+    evals = new EvalNode[realTargets.length];
 
     if (context.getQueryContext().getBool(SessionVars.CODEGEN)) {
       EvalNode eval;
-      for (int i = 0; i < targetNum; i++) {
-        eval = this.targets[i].getEvalTree();
+      for (int i = 0; i < realTargets.length; i++) {
+        eval = realTargets[i].getEvalTree();
         evals[i] = context.getPrecompiledEval(inSchema, eval);
       }
     } else {
-      for (int i = 0; i < targetNum; i++) {
-        evals[i] = this.targets[i].getEvalTree();
+      for (int i = 0; i < realTargets.length; i++) {
+        evals[i] = realTargets[i].getEvalTree();
       }
     }
     init();
@@ -67,9 +69,10 @@ public class Projector {
     }
   }
 
-  public void eval(Tuple in, Tuple out) {
+  public Tuple eval(Tuple in) {
     for (int i = 0; i < evals.length; i++) {
-      out.put(i, evals[i].eval(in));
+      outTuple.put(i, evals[i].eval(in));
     }
+    return outTuple;
   }
 }

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/AggregationExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/AggregationExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/AggregationExec.java
index 4b53b39..fdb8fdd 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/AggregationExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/AggregationExec.java
@@ -29,7 +29,6 @@ import java.io.IOException;
 public abstract class AggregationExec extends UnaryPhysicalExec {
 
   protected final int groupingKeyNum;
-  protected final int groupingKeyIds[];
   protected final int aggFunctionsNum;
   protected final AggregationFunctionCallEval aggFunctions[];
 
@@ -39,16 +38,6 @@ public abstract class AggregationExec extends UnaryPhysicalExec {
 
     final Column [] keyColumns = plan.getGroupingColumns();
     groupingKeyNum = keyColumns.length;
-    groupingKeyIds = new int[groupingKeyNum];
-    Column col;
-    for (int idx = 0; idx < plan.getGroupingColumns().length; idx++) {
-      col = keyColumns[idx];
-      if (col.hasQualifier()) {
-        groupingKeyIds[idx] = inSchema.getColumnId(col.getQualifiedName());
-      } else {
-        groupingKeyIds[idx] = inSchema.getColumnIdByName(col.getSimpleName());
-      }
-    }
 
     if (plan.hasAggFunctions()) {
       aggFunctions = plan.getAggFunctions();

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/BNLJoinExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/BNLJoinExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/BNLJoinExec.java
index 6e1a553..d28b7f6 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/BNLJoinExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/BNLJoinExec.java
@@ -18,22 +18,18 @@
 
 package org.apache.tajo.engine.planner.physical;
 
-import org.apache.tajo.plan.util.PlannerUtil;
 import org.apache.tajo.plan.logical.JoinNode;
-import org.apache.tajo.storage.FrameTuple;
+import org.apache.tajo.plan.util.PlannerUtil;
 import org.apache.tajo.storage.Tuple;
-import org.apache.tajo.storage.VTuple;
 import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
-import java.util.ArrayList;
 import java.util.Iterator;
-import java.util.List;
 
 public class BNLJoinExec extends CommonJoinExec {
 
-  private List<Tuple> leftTupleSlots;
-  private List<Tuple> rightTupleSlots;
+  private TupleList leftTupleSlots;
+  private TupleList rightTupleSlots;
   private Iterator<Tuple> leftIterator;
   private Iterator<Tuple> rightIterator;
 
@@ -41,9 +37,7 @@ public class BNLJoinExec extends CommonJoinExec {
   private boolean rightEnd;
 
   // temporal tuples and states for nested loop join
-  private FrameTuple frameTuple;
   private Tuple leftTuple = null;
-  private Tuple outputTuple = null;
   private Tuple rightNext = null;
 
   private final static int TUPLE_SLOT_SIZE = 10000;
@@ -51,8 +45,8 @@ public class BNLJoinExec extends CommonJoinExec {
   public BNLJoinExec(final TaskAttemptContext context, final JoinNode plan,
                      final PhysicalExec leftExec, PhysicalExec rightExec) {
     super(context, plan, leftExec, rightExec);
-    this.leftTupleSlots = new ArrayList<Tuple>(TUPLE_SLOT_SIZE);
-    this.rightTupleSlots = new ArrayList<Tuple>(TUPLE_SLOT_SIZE);
+    this.leftTupleSlots = new TupleList(TUPLE_SLOT_SIZE);
+    this.rightTupleSlots = new TupleList(TUPLE_SLOT_SIZE);
     this.leftIterator = leftTupleSlots.iterator();
     this.rightIterator = rightTupleSlots.iterator();
     this.rightEnd = false;
@@ -62,10 +56,6 @@ public class BNLJoinExec extends CommonJoinExec {
     if (!plan.hasTargets()) {
       plan.setTargets(PlannerUtil.schemaToTargets(outSchema));
     }
-
-    // for join
-    frameTuple = new FrameTuple();
-    outputTuple = new VTuple(outSchema.size());
   }
 
   public Tuple next() throws IOException {
@@ -108,7 +98,7 @@ public class BNLJoinExec extends CommonJoinExec {
           if (rightEnd) {
             rightChild.rescan();
             rightEnd = false;
-            
+
             if (leftEnd) {
               return null;
             }
@@ -126,12 +116,12 @@ public class BNLJoinExec extends CommonJoinExec {
             }
             leftIterator = leftTupleSlots.iterator();
             leftTuple = leftIterator.next();
-            
+
           } else {
             leftIterator = leftTupleSlots.iterator();
             leftTuple = leftIterator.next();
           }
-          
+
           rightTupleSlots.clear();
           if (rightNext != null) {
             rightTupleSlots.add(rightNext);
@@ -153,7 +143,7 @@ public class BNLJoinExec extends CommonJoinExec {
               rightTupleSlots.add(t);
             }
           }
-          
+
           if ((rightNext = rightChild.next()) == null) {
             rightEnd = true;
           }
@@ -163,8 +153,7 @@ public class BNLJoinExec extends CommonJoinExec {
 
       frameTuple.set(leftTuple, rightIterator.next());
       if (!hasJoinQual || joinQual.eval(frameTuple).isTrue()) {
-        projector.eval(frameTuple, outputTuple);
-        return outputTuple;
+        return projector.eval(frameTuple);
       }
     }
     return null;

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/BSTIndexScanExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/BSTIndexScanExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/BSTIndexScanExec.java
index 54abca8..28622d7 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/BSTIndexScanExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/BSTIndexScanExec.java
@@ -41,20 +41,20 @@ public class BSTIndexScanExec extends PhysicalExec {
   private BSTIndex.BSTIndexReader reader;
   
   private Projector projector;
-  
-  private Datum[] datum = null;
-  
+
   private boolean initialize = true;
 
   private float progress;
 
+  private Tuple indexLookupKey;
+
   public BSTIndexScanExec(TaskAttemptContext context, ScanNode scanNode ,
        FileFragment fragment, Path fileName , Schema keySchema,
        TupleComparator comparator , Datum[] datum) throws IOException {
     super(context, scanNode.getInSchema(), scanNode.getOutSchema());
     this.scanNode = scanNode;
     this.qual = scanNode.getQual();
-    this.datum = datum;
+    indexLookupKey = new VTuple(datum);
 
     this.fileScanner = OldStorageManager.getSeekableScanner(context.getConf(),
         scanNode.getTableDesc().getMeta(), scanNode.getInSchema(), fragment, outSchema);
@@ -80,8 +80,7 @@ public class BSTIndexScanExec extends PhysicalExec {
   public Tuple next() throws IOException {
     if(initialize) {
       //TODO : more complicated condition
-      Tuple key = new VTuple(datum);
-      long offset = reader.find(key);
+      long offset = reader.find(indexLookupKey);
       if (offset == -1) {
         reader.close();
         fileScanner.close();
@@ -104,19 +103,16 @@ public class BSTIndexScanExec extends PhysicalExec {
       }
     }
     Tuple tuple;
-    Tuple outTuple = new VTuple(this.outSchema.size());
     if (!scanNode.hasQual()) {
       if ((tuple = fileScanner.next()) != null) {
-        projector.eval(tuple, outTuple);
-        return outTuple;
+        return projector.eval(tuple);
       } else {
         return null;
       }
     } else {
        while(reader.isCurInMemory() && (tuple = fileScanner.next()) != null) {
          if (qual.eval(tuple).isTrue()) {
-           projector.eval(tuple, outTuple);
-           return outTuple;
+           return projector.eval(tuple);
          } else {
            long offset = reader.next();
            if (offset == -1) return null;
@@ -140,6 +136,7 @@ public class BSTIndexScanExec extends PhysicalExec {
     scanNode = null;
     qual = null;
     projector = null;
+    indexLookupKey = null;
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/CommonHashJoinExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/CommonHashJoinExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/CommonHashJoinExec.java
index a018fe1..0d64e65 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/CommonHashJoinExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/CommonHashJoinExec.java
@@ -20,21 +20,18 @@ package org.apache.tajo.engine.planner.physical;
 
 import org.apache.tajo.catalog.Column;
 import org.apache.tajo.catalog.statistics.TableStats;
+import org.apache.tajo.engine.planner.KeyProjector;
 import org.apache.tajo.engine.utils.CacheHolder;
 import org.apache.tajo.engine.utils.TableCacheKey;
 import org.apache.tajo.plan.logical.JoinNode;
 import org.apache.tajo.plan.util.PlannerUtil;
 import org.apache.tajo.storage.Tuple;
-import org.apache.tajo.storage.VTuple;
 import org.apache.tajo.worker.ExecutionBlockSharedResource;
 import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
-import java.util.Map;
 
 /**
  * common exec for all hash join execs
@@ -47,19 +44,18 @@ public abstract class CommonHashJoinExec<T> extends CommonJoinExec {
 
   // temporal tuples and states for nested loop join
   protected boolean first = true;
-  protected Map<Tuple, T> tupleSlots;
+  protected TupleMap<T> tupleSlots;
 
   protected Iterator<Tuple> iterator;
 
-  protected final Tuple keyTuple;
-
   protected final int rightNumCols;
   protected final int leftNumCols;
 
-  protected final int[] leftKeyList;
-  protected final int[] rightKeyList;
+  protected final Column[] leftKeyList;
+  protected final Column[] rightKeyList;
 
   protected boolean finished;
+  protected final KeyProjector leftKeyExtractor;
 
   public CommonHashJoinExec(TaskAttemptContext context, JoinNode plan, PhysicalExec outer, PhysicalExec inner) {
     super(context, plan, outer, inner);
@@ -68,21 +64,18 @@ public abstract class CommonHashJoinExec<T> extends CommonJoinExec {
     this.joinKeyPairs = PlannerUtil.getJoinKeyPairs(joinQual, outer.getSchema(),
         inner.getSchema(), false);
 
-    leftKeyList = new int[joinKeyPairs.size()];
-    rightKeyList = new int[joinKeyPairs.size()];
-
-    for (int i = 0; i < joinKeyPairs.size(); i++) {
-      leftKeyList[i] = outer.getSchema().getColumnId(joinKeyPairs.get(i)[0].getQualifiedName());
-    }
+    leftKeyList = new Column[joinKeyPairs.size()];
+    rightKeyList = new Column[joinKeyPairs.size()];
 
     for (int i = 0; i < joinKeyPairs.size(); i++) {
-      rightKeyList[i] = inner.getSchema().getColumnId(joinKeyPairs.get(i)[1].getQualifiedName());
+      leftKeyList[i] = outer.getSchema().getColumn(joinKeyPairs.get(i)[0].getQualifiedName());
+      rightKeyList[i] = inner.getSchema().getColumn(joinKeyPairs.get(i)[1].getQualifiedName());
     }
 
     leftNumCols = outer.getSchema().size();
     rightNumCols = inner.getSchema().size();
 
-    keyTuple = new VTuple(leftKeyList.length);
+    leftKeyExtractor = new KeyProjector(leftSchema, leftKeyList);
   }
 
   protected void loadRightToHashTable() throws IOException {
@@ -102,12 +95,12 @@ public abstract class CommonHashJoinExec<T> extends CommonJoinExec {
   protected void loadRightFromCache(TableCacheKey key) throws IOException {
     ExecutionBlockSharedResource sharedResource = context.getSharedResource();
 
-    CacheHolder<Map<Tuple, List<Tuple>>> holder;
+    CacheHolder<TupleMap<TupleList>> holder;
     synchronized (sharedResource.getLock()) {
       if (sharedResource.hasBroadcastCache(key)) {
         holder = sharedResource.getBroadcastCache(key);
       } else {
-        Map<Tuple, List<Tuple>> built = buildRightToHashTable();
+        TupleMap<TupleList> built = buildRightToHashTable();
         holder = new CacheHolder.BroadcastCacheHolder(built, rightChild.getInputStats(), null);
         sharedResource.addBroadcastCache(key, holder);
       }
@@ -115,50 +108,27 @@ public abstract class CommonHashJoinExec<T> extends CommonJoinExec {
     this.tupleSlots = convert(holder.getData(), true);
   }
 
-  protected Map<Tuple, List<Tuple>> buildRightToHashTable() throws IOException {
+  protected TupleMap<TupleList> buildRightToHashTable() throws IOException {
     Tuple tuple;
-    Map<Tuple, List<Tuple>> map = new HashMap<Tuple, List<Tuple>>(100000);
+    TupleMap<TupleList> map = new TupleMap<TupleList>(100000);
+    KeyProjector keyProjector = new KeyProjector(rightSchema, rightKeyList);
 
     while (!context.isStopped() && (tuple = rightChild.next()) != null) {
-      Tuple keyTuple = new VTuple(joinKeyPairs.size());
-      for (int i = 0; i < rightKeyList.length; i++) {
-        keyTuple.put(i, tuple.asDatum(rightKeyList[i]));
-      }
-
-      /*
-       * TODO
-       * Currently, some physical executors can return new instances of tuple, but others not.
-       * This sometimes causes wrong results due to the singleton Tuple instance.
-       * The below line is a temporal solution to fix this problem.
-       * This will be improved at https://issues.apache.org/jira/browse/TAJO-1343.
-       */
-      try {
-        tuple = tuple.clone();
-      } catch (CloneNotSupportedException e) {
-        throw new IOException(e);
-      }
-
-      List<Tuple> newValue = map.get(keyTuple);
+      KeyTuple keyTuple = keyProjector.project(tuple);
+      TupleList newValue = map.get(keyTuple);
       if (newValue == null) {
-        map.put(keyTuple, newValue = new ArrayList<Tuple>());
+        map.put(keyTuple, newValue = new TupleList());
       }
       // if source is scan or groupby, it needs not to be cloned
-      newValue.add(new VTuple(tuple));
+      newValue.add(tuple);
     }
     return map;
   }
 
   // todo: convert loaded data to cache condition
-  protected abstract Map<Tuple, T> convert(Map<Tuple, List<Tuple>> hashed, boolean fromCache)
+  protected abstract TupleMap<T> convert(TupleMap<TupleList> hashed, boolean fromCache)
       throws IOException;
 
-  protected Tuple toKey(final Tuple outerTuple) {
-    for (int i = 0; i < leftKeyList.length; i++) {
-      keyTuple.put(i, outerTuple.asDatum(leftKeyList[i]));
-    }
-    return keyTuple;
-  }
-
   @Override
   public void rescan() throws IOException {
     super.rescan();

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/CommonJoinExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/CommonJoinExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/CommonJoinExec.java
index ec29085..4f819ad 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/CommonJoinExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/CommonJoinExec.java
@@ -33,7 +33,6 @@ import org.apache.tajo.plan.logical.JoinNode;
 import org.apache.tajo.storage.FrameTuple;
 import org.apache.tajo.storage.NullTuple;
 import org.apache.tajo.storage.Tuple;
-import org.apache.tajo.storage.VTuple;
 import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
@@ -59,7 +58,6 @@ public abstract class CommonJoinExec extends BinaryPhysicalExec {
   protected final Schema rightSchema;
 
   protected final FrameTuple frameTuple;
-  protected final Tuple outTuple;
 
   // projection
   protected Projector projector;
@@ -83,7 +81,6 @@ public abstract class CommonJoinExec extends BinaryPhysicalExec {
 
     // for join
     this.frameTuple = new FrameTuple();
-    this.outTuple = new VTuple(outSchema.size());
   }
 
   /**
@@ -183,13 +180,13 @@ public abstract class CommonJoinExec extends BinaryPhysicalExec {
   }
 
   /**
-   * Return an tuple iterator, containing a single NullTuple
+   * Create a list that contains a single null tuple.
    *
-   * @param width the width of tuple
-   * @return an tuple iterator, containing a single NullTuple
+   * @param width the width of null tuple which will be created.
+   * @return created list of a null tuple
    */
-  protected Iterator<Tuple> nullIterator(int width) {
-    return Arrays.asList(NullTuple.create(width)).iterator();
+  protected List<Tuple> nullTupleList(int width) {
+    return Arrays.asList(NullTuple.create(width));
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/ComparableVector.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/ComparableVector.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/ComparableVector.java
index 2d836f4..a298564 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/ComparableVector.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/ComparableVector.java
@@ -302,14 +302,6 @@ public class ComparableVector {
       return new ComparableTuple(keyTypes, keyIndex);
     }
 
-    public VTuple toVTuple() {
-      VTuple vtuple = new VTuple(keyIndex.length);
-      for (int i = 0; i < keyIndex.length; i++) {
-        vtuple.put(i, toDatum(i));
-      }
-      return vtuple;
-    }
-
     public Datum toDatum(int i) {
       if (keys[i] == null) {
         return NullDatum.get();

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbyFirstAggregationExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbyFirstAggregationExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbyFirstAggregationExec.java
index 7784817..7ac3e0b 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbyFirstAggregationExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbyFirstAggregationExec.java
@@ -23,13 +23,15 @@ import org.apache.commons.logging.LogFactory;
 import org.apache.tajo.catalog.Column;
 import org.apache.tajo.catalog.statistics.TableStats;
 import org.apache.tajo.datum.Int2Datum;
-import org.apache.tajo.datum.NullDatum;
+import org.apache.tajo.engine.planner.KeyProjector;
 import org.apache.tajo.plan.expr.AggregationFunctionCallEval;
 import org.apache.tajo.plan.function.FunctionContext;
 import org.apache.tajo.plan.logical.DistinctGroupbyNode;
 import org.apache.tajo.plan.logical.GroupbyNode;
+import org.apache.tajo.storage.NullTuple;
 import org.apache.tajo.storage.Tuple;
 import org.apache.tajo.storage.VTuple;
+import org.apache.tajo.util.TUtil;
 import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
@@ -94,9 +96,11 @@ public class DistinctGroupbyFirstAggregationExec extends UnaryPhysicalExec {
   private long totalNumRows;
   private int fetchedRows;
 
-  private int[] groupingKeyIndexes;
   private NonDistinctHashAggregator nonDistinctHashAggregator;
-  private DistinctHashAggregator[] distinctAggregators;
+  private Map<Integer, DistinctHashAggregator> nodeSeqToDistinctAggregators = TUtil.newHashMap();
+
+  private KeyProjector nonDistinctGroupingKeyProjector;
+  private Map<Integer, KeyProjector> distinctGroupbyKeyProjectors = TUtil.newHashMap();
 
   private int resultTupleLength;
 
@@ -111,37 +115,23 @@ public class DistinctGroupbyFirstAggregationExec extends UnaryPhysicalExec {
     super.init();
 
     // finding grouping column index
-    Column[] groupingColumns = plan.getGroupingColumns();
-    groupingKeyIndexes = new int[groupingColumns.length];
-
-    int index = 0;
-    for (Column col: groupingColumns) {
-      int keyIndex;
-      if (col.hasQualifier()) {
-        keyIndex = inSchema.getColumnId(col.getQualifiedName());
-      } else {
-        keyIndex = inSchema.getColumnIdByName(col.getSimpleName());
-      }
-      groupingKeyIndexes[index++] = keyIndex;
-    }
-    resultTupleLength = groupingKeyIndexes.length + 1;  //1 is Sequence Datum which indicates sequence of DistinctNode.
+    Column[] groupingKeyColumns = plan.getGroupingColumns();
+    nonDistinctGroupingKeyProjector = new KeyProjector(inSchema, plan.getGroupingColumns());
+    resultTupleLength = groupingKeyColumns.length + 1;  //1 is Sequence Datum which indicates sequence of DistinctNode.
 
     List<GroupbyNode> groupbyNodes = plan.getSubPlans();
 
-    List<DistinctHashAggregator> distinctAggrList = new ArrayList<DistinctHashAggregator>();
     int distinctSeq = 0;
     for (GroupbyNode eachGroupby: groupbyNodes) {
       if (eachGroupby.isDistinct()) {
-        DistinctHashAggregator aggregator = new DistinctHashAggregator(eachGroupby);
-        aggregator.setNodeSequence(distinctSeq++);
-        distinctAggrList.add(aggregator);
+        DistinctHashAggregator aggregator = new DistinctHashAggregator(eachGroupby, distinctSeq);
+        nodeSeqToDistinctAggregators.put(distinctSeq++, aggregator);
         resultTupleLength += aggregator.getTupleLength();
       } else {
         nonDistinctHashAggregator = new NonDistinctHashAggregator(eachGroupby);
         resultTupleLength += nonDistinctHashAggregator.getTupleLength();
       }
     }
-    distinctAggregators = distinctAggrList.toArray(new DistinctHashAggregator[]{});
   }
 
   private int currentAggregatorIndex = 0;
@@ -154,13 +144,13 @@ public class DistinctGroupbyFirstAggregationExec extends UnaryPhysicalExec {
 
     int prevIndex = currentAggregatorIndex;
     while (!context.isStopped()) {
-      DistinctHashAggregator aggregator = distinctAggregators[currentAggregatorIndex];
+      DistinctHashAggregator aggregator = nodeSeqToDistinctAggregators.get(currentAggregatorIndex);
       Tuple result = aggregator.next();
       if (result != null) {
         return result;
       }
       currentAggregatorIndex++;
-      currentAggregatorIndex = currentAggregatorIndex % distinctAggregators.length;
+      currentAggregatorIndex = currentAggregatorIndex % nodeSeqToDistinctAggregators.size();
       if (currentAggregatorIndex == prevIndex) {
         finished = true;
         return null;
@@ -171,29 +161,36 @@ public class DistinctGroupbyFirstAggregationExec extends UnaryPhysicalExec {
   }
 
   private void prepareInputData() throws IOException {
-    Tuple tuple = null;
+    Tuple tuple;
+
     while(!context.isStopped() && (tuple = child.next()) != null) {
-      Tuple groupingKey = new VTuple(groupingKeyIndexes.length);
-      for (int i = 0; i < groupingKeyIndexes.length; i++) {
-        groupingKey.put(i, tuple.asDatum(groupingKeyIndexes[i]));
-      }
-      for (int i = 0; i < distinctAggregators.length; i++) {
-        distinctAggregators[i].compute(groupingKey, tuple);
+
+      KeyTuple groupingKey = nonDistinctGroupingKeyProjector.project(tuple);
+      for (int i = 0; i < nodeSeqToDistinctAggregators.size(); i++) {
+        nodeSeqToDistinctAggregators.get(i).compute(groupingKey, tuple);
       }
       if (nonDistinctHashAggregator != null) {
         nonDistinctHashAggregator.compute(groupingKey, tuple);
       }
     }
-    for (int i = 0; i < distinctAggregators.length; i++) {
-      distinctAggregators[i].rescan();
+    for (int i = 0; i < nodeSeqToDistinctAggregators.size(); i++) {
+      nodeSeqToDistinctAggregators.get(i).rescan();
     }
 
-    totalNumRows = distinctAggregators[0].distinctAggrDatas.size();
+    totalNumRows = nodeSeqToDistinctAggregators.get(0).distinctAggrDatas.size();
     preparedData = true;
   }
 
   @Override
   public void close() throws IOException {
+    if (nonDistinctHashAggregator != null) {
+      nonDistinctHashAggregator.close();
+      nonDistinctHashAggregator = null;
+    }
+    for (DistinctHashAggregator aggregator : nodeSeqToDistinctAggregators.values()) {
+      aggregator.close();
+    }
+    nodeSeqToDistinctAggregators.clear();
     child.close();
   }
 
@@ -223,8 +220,8 @@ public class DistinctGroupbyFirstAggregationExec extends UnaryPhysicalExec {
   public void rescan() {
     finished = false;
     currentAggregatorIndex = 0;
-    for (int i = 0; i < distinctAggregators.length; i++) {
-      distinctAggregators[i].rescan();
+    for (int i = 0; i < nodeSeqToDistinctAggregators.size(); i++) {
+      nodeSeqToDistinctAggregators.get(i).rescan();
     }
   }
 
@@ -233,13 +230,14 @@ public class DistinctGroupbyFirstAggregationExec extends UnaryPhysicalExec {
     private final AggregationFunctionCallEval aggFunctions[];
 
     // GroupingKey -> FunctionContext[]
-    private Map<Tuple, FunctionContext[]> nonDistinctAggrDatas;
+    private TupleMap<FunctionContext[]> nonDistinctAggrDatas;
     private int tupleLength;
 
-    private Tuple dummyTuple;
+    private final Tuple dummyTuple;
+    private final Tuple outTuple;
     private NonDistinctHashAggregator(GroupbyNode groupbyNode) throws IOException {
 
-      nonDistinctAggrDatas = new HashMap<Tuple, FunctionContext[]>();
+      nonDistinctAggrDatas = new TupleMap<FunctionContext[]>();
 
       if (groupbyNode.hasAggFunctions()) {
         aggFunctions = groupbyNode.getAggFunctions();
@@ -254,14 +252,12 @@ public class DistinctGroupbyFirstAggregationExec extends UnaryPhysicalExec {
         eachFunction.setFirstPhase();
       }
 
-      dummyTuple = new VTuple(aggFunctionsNum);
-      for (int i = 0; i < aggFunctionsNum; i++) {
-        dummyTuple.put(i, NullDatum.get());
-      }
+      outTuple = new VTuple(aggFunctionsNum);
+      dummyTuple = NullTuple.create(aggFunctionsNum);
       tupleLength = aggFunctionsNum;
     }
 
-    public void compute(Tuple groupingKeyTuple, Tuple tuple) {
+    public void compute(KeyTuple groupingKeyTuple, Tuple tuple) {
       FunctionContext[] contexts = nonDistinctAggrDatas.get(groupingKeyTuple);
       if (contexts != null) {
         for (int i = 0; i < aggFunctions.length; i++) {
@@ -282,13 +278,12 @@ public class DistinctGroupbyFirstAggregationExec extends UnaryPhysicalExec {
       if (contexts == null) {
         return null;
       }
-      Tuple tuple = new VTuple(aggFunctionsNum);
 
       for (int i = 0; i < aggFunctionsNum; i++) {
-        tuple.put(i, aggFunctions[i].terminate(contexts[i]));
+        outTuple.put(i, aggFunctions[i].terminate(contexts[i]));
       }
 
-      return tuple;
+      return outTuple;
     }
 
     public int getTupleLength() {
@@ -298,57 +293,51 @@ public class DistinctGroupbyFirstAggregationExec extends UnaryPhysicalExec {
     public Tuple getDummyTuple() {
       return dummyTuple;
     }
+
+    public void close() {
+      nonDistinctAggrDatas.clear();
+      nonDistinctAggrDatas = null;
+    }
   }
 
   class DistinctHashAggregator {
 
     // GroupingKey -> DistinctKey
-    private Map<Tuple, Set<Tuple>> distinctAggrDatas;
-    private Iterator<Entry<Tuple, Set<Tuple>>> iterator = null;
+    private TupleMap<TupleSet> distinctAggrDatas;
+    private Iterator<Entry<KeyTuple, TupleSet>> iterator = null;
 
     private int nodeSequence;
     private Int2Datum nodeSequenceDatum;
 
-    private int[] distinctKeyIndexes;
-
     private int tupleLength;
-    private Tuple dummyTuple;
+    private final Tuple dummyTuple;
+    private Tuple outTuple;
     private boolean aggregatorFinished = false;
 
-    public DistinctHashAggregator(GroupbyNode groupbyNode) throws IOException {
+    public DistinctHashAggregator(GroupbyNode groupbyNode, int nodeSequence) throws IOException {
 
-      Set<Integer> groupingKeyIndexSet = new HashSet<Integer>();
-      for (Integer eachIndex: groupingKeyIndexes) {
-        groupingKeyIndexSet.add(eachIndex);
-      }
+      Set<Column> groupingKeySet = TUtil.newHashSet(plan.getGroupingColumns());
 
-      List<Integer> distinctGroupingKeyIndexSet = new ArrayList<Integer>();
+      List<Column> distinctGroupingKeyIndexSet = new ArrayList<Column>();
       Column[] groupingColumns = groupbyNode.getGroupingColumns();
       for (int idx = 0; idx < groupingColumns.length; idx++) {
         Column col = groupingColumns[idx];
-        int keyIndex;
-        if (col.hasQualifier()) {
-          keyIndex = inSchema.getColumnId(col.getQualifiedName());
-        } else {
-          keyIndex = inSchema.getColumnIdByName(col.getSimpleName());
-        }
-        if (!groupingKeyIndexSet.contains(keyIndex)) {
-          distinctGroupingKeyIndexSet.add(keyIndex);
+        if (!groupingKeySet.contains(col)) {
+          distinctGroupingKeyIndexSet.add(col);
         }
       }
-      int index = 0;
-      this.distinctKeyIndexes = new int[distinctGroupingKeyIndexSet.size()];
-      this.dummyTuple = new VTuple(distinctGroupingKeyIndexSet.size());
-      for (Integer eachId : distinctGroupingKeyIndexSet) {
-        this.dummyTuple.put(index, NullDatum.get());
-        this.distinctKeyIndexes[index++] = eachId;
-      }
+      Column[] distinctKeyColumns = new Column[distinctGroupingKeyIndexSet.size()];
+      distinctKeyColumns = distinctGroupingKeyIndexSet.toArray(distinctKeyColumns);
+      this.dummyTuple = NullTuple.create(distinctGroupingKeyIndexSet.size());
+
+      this.distinctAggrDatas = new TupleMap<TupleSet>();
+      distinctGroupbyKeyProjectors.put(nodeSequence, new KeyProjector(inSchema, distinctKeyColumns));
+      this.tupleLength = distinctKeyColumns.length;
 
-      this.distinctAggrDatas = new HashMap<Tuple, Set<Tuple>>();
-      this.tupleLength = distinctKeyIndexes.length;
+      setNodeSequence(nodeSequence);
     }
 
-    public void setNodeSequence(int nodeSequence) {
+    private void setNodeSequence(int nodeSequence) {
       this.nodeSequence = nodeSequence;
       this.nodeSequenceDatum = new Int2Datum((short)nodeSequence);
     }
@@ -357,15 +346,12 @@ public class DistinctGroupbyFirstAggregationExec extends UnaryPhysicalExec {
       return tupleLength;
     }
 
-    public void compute(Tuple groupingKey, Tuple tuple) throws IOException {
-      Tuple distinctKeyTuple = new VTuple(distinctKeyIndexes.length);
-      for (int i = 0; i < distinctKeyIndexes.length; i++) {
-        distinctKeyTuple.put(i, tuple.asDatum(distinctKeyIndexes[i]));
-      }
+    public void compute(KeyTuple groupingKey, Tuple tuple) throws IOException {
+      KeyTuple distinctKeyTuple = distinctGroupbyKeyProjectors.get(nodeSequence).project(tuple);
 
-      Set<Tuple> distinctEntry = distinctAggrDatas.get(groupingKey);
+      TupleSet distinctEntry = distinctAggrDatas.get(groupingKey);
       if (distinctEntry == null) {
-        distinctEntry = new HashSet<Tuple>();
+        distinctEntry = new TupleSet();
         distinctAggrDatas.put(groupingKey, distinctEntry);
       }
       distinctEntry.add(distinctKeyTuple);
@@ -379,14 +365,17 @@ public class DistinctGroupbyFirstAggregationExec extends UnaryPhysicalExec {
     }
 
     public void close() throws IOException {
+      for (TupleSet set : distinctAggrDatas.values()) {
+        set.clear();
+      }
       distinctAggrDatas.clear();
       distinctAggrDatas = null;
       currentGroupingTuples = null;
       iterator = null;
     }
 
-    Entry<Tuple, Set<Tuple>> currentGroupingTuples;
-    Iterator<Tuple> distinctKeyIterator;
+    Entry<KeyTuple, TupleSet> currentGroupingTuples;
+    Iterator<KeyTuple> distinctKeyIterator;
     boolean groupingKeyChanged = false;
 
     public Tuple next() {
@@ -415,30 +404,32 @@ public class DistinctGroupbyFirstAggregationExec extends UnaryPhysicalExec {
       }
       // node sequence, groupingKeys, 1'st distinctKeys, 2'st distinctKeys, ...
       // If n'st == this.nodeSequence set with real data, otherwise set with NullDatum
-      VTuple tuple = new VTuple(resultTupleLength);
       int tupleIndex = 0;
-      tuple.put(tupleIndex++, nodeSequenceDatum);
+      if (outTuple == null) {
+        outTuple = new VTuple(resultTupleLength);
+      }
+      outTuple.put(tupleIndex++, nodeSequenceDatum);
 
       // merge grouping key
       Tuple groupingKeyTuple = currentGroupingTuples.getKey();
       int groupingKeyLength = groupingKeyTuple.size();
       for (int i = 0; i < groupingKeyLength; i++, tupleIndex++) {
-        tuple.put(tupleIndex, groupingKeyTuple.asDatum(i));
+        outTuple.put(tupleIndex, groupingKeyTuple.asDatum(i));
       }
 
       // merge distinctKey
-      for (int i = 0; i < distinctAggregators.length; i++) {
+      for (int i = 0; i < nodeSeqToDistinctAggregators.size(); i++) {
         if (i == nodeSequence) {
           Tuple distinctKeyTuple = distinctKeyIterator.next();
           int distinctKeyLength = distinctKeyTuple.size();
           for (int j = 0; j < distinctKeyLength; j++, tupleIndex++) {
-            tuple.put(tupleIndex, distinctKeyTuple.asDatum(j));
+            outTuple.put(tupleIndex, distinctKeyTuple.asDatum(j));
           }
         } else {
-          Tuple dummyTuple = distinctAggregators[i].getDummyTuple();
+          Tuple dummyTuple = nodeSeqToDistinctAggregators.get(i).getDummyTuple();
           int dummyTupleSize = dummyTuple.size();
           for (int j = 0; j < dummyTupleSize; j++, tupleIndex++) {
-            tuple.put(tupleIndex, dummyTuple.asDatum(j));
+            outTuple.put(tupleIndex, dummyTuple.asDatum(j));
           }
         }
       }
@@ -457,10 +448,10 @@ public class DistinctGroupbyFirstAggregationExec extends UnaryPhysicalExec {
         }
         int tupleSize = nonDistinctTuple.size();
         for (int j = 0; j < tupleSize; j++, tupleIndex++) {
-          tuple.put(tupleIndex, nonDistinctTuple.asDatum(j));
+          outTuple.put(tupleIndex, nonDistinctTuple.asDatum(j));
         }
       }
-      return tuple;
+      return outTuple;
     }
 
     public Tuple getDummyTuple() {

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbyHashAggregationExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbyHashAggregationExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbyHashAggregationExec.java
index c8a6588..2d1fa4b 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbyHashAggregationExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbyHashAggregationExec.java
@@ -21,27 +21,34 @@ package org.apache.tajo.engine.planner.physical;
 import org.apache.tajo.catalog.Column;
 import org.apache.tajo.catalog.Schema;
 import org.apache.tajo.catalog.statistics.TableStats;
-import org.apache.tajo.datum.DatumFactory;
 import org.apache.tajo.datum.NullDatum;
+import org.apache.tajo.engine.planner.KeyProjector;
 import org.apache.tajo.plan.expr.AggregationFunctionCallEval;
 import org.apache.tajo.plan.expr.EvalNode;
 import org.apache.tajo.plan.function.FunctionContext;
 import org.apache.tajo.plan.logical.DistinctGroupbyNode;
 import org.apache.tajo.plan.logical.GroupbyNode;
+import org.apache.tajo.storage.NullTuple;
 import org.apache.tajo.storage.Tuple;
 import org.apache.tajo.storage.VTuple;
+import org.apache.tajo.util.TUtil;
 import org.apache.tajo.worker.TaskAttemptContext;
 
 import java.io.IOException;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
 import java.util.Map.Entry;
 
 public class DistinctGroupbyHashAggregationExec extends UnaryPhysicalExec {
+
   private boolean finished = false;
 
-  private DistinctGroupbyNode plan;
+  private final DistinctGroupbyNode plan;
   private HashAggregator[] hashAggregators;
-  private int distinctGroupingKeyIds[];
+
+  private List<Column> distinctGroupingKeyColumnSet;
   private boolean first = true;
   private int groupbyNodeNum;
   private int outputColumnNum;
@@ -50,6 +57,10 @@ public class DistinctGroupbyHashAggregationExec extends UnaryPhysicalExec {
 
   private int[] resultColumnIdIndexes;
 
+  private Tuple outTuple;
+
+  private KeyProjector outerKeyProjector;
+
   public DistinctGroupbyHashAggregationExec(TaskAttemptContext context, DistinctGroupbyNode plan, PhysicalExec subOp)
       throws IOException {
     super(context, plan.getInSchema(), plan.getOutSchema(), subOp);
@@ -60,23 +71,16 @@ public class DistinctGroupbyHashAggregationExec extends UnaryPhysicalExec {
   public void init() throws IOException {
     super.init();
 
-    List<Integer> distinctGroupingKeyIdList = new ArrayList<Integer>();
-    for (Column col: plan.getGroupingColumns()) {
-      int keyIndex;
-      if (col.hasQualifier()) {
-        keyIndex = inSchema.getColumnId(col.getQualifiedName());
-      } else {
-        keyIndex = inSchema.getColumnIdByName(col.getSimpleName());
-      }
-      if (!distinctGroupingKeyIdList.contains(keyIndex)) {
-        distinctGroupingKeyIdList.add(keyIndex);
+    distinctGroupingKeyColumnSet = TUtil.newList();
+    for (Column col : plan.getGroupingColumns()) {
+      if (!distinctGroupingKeyColumnSet.contains(col)) {
+        distinctGroupingKeyColumnSet.add(col);
       }
     }
-    int idx = 0;
-    distinctGroupingKeyIds = new int[distinctGroupingKeyIdList.size()];
-    for (Integer intVal: distinctGroupingKeyIdList) {
-      distinctGroupingKeyIds[idx++] = intVal;
-    }
+    Column[] distinctGroupingKeyColumns = new Column[distinctGroupingKeyColumnSet.size()];
+    distinctGroupingKeyColumns = distinctGroupingKeyColumnSet.toArray(distinctGroupingKeyColumns);
+
+    outerKeyProjector = new KeyProjector(inSchema, distinctGroupingKeyColumns);
 
     List<GroupbyNode> groupbyNodes = plan.getSubPlans();
     groupbyNodeNum = groupbyNodes.size();
@@ -88,6 +92,7 @@ public class DistinctGroupbyHashAggregationExec extends UnaryPhysicalExec {
     }
 
     outputColumnNum = plan.getOutSchema().size();
+    outTuple = new VTuple(outputColumnNum);
 
     int allGroupbyOutColNum = 0;
     for (GroupbyNode eachGroupby: plan.getSubPlans()) {
@@ -105,7 +110,7 @@ public class DistinctGroupbyHashAggregationExec extends UnaryPhysicalExec {
     }
   }
 
-  List<Tuple> currentAggregatedTuples = null;
+  TupleList currentAggregatedTuples = null;
   int currentAggregatedTupleIndex = 0;
   int currentAggregatedTupleSize = 0;
 
@@ -143,20 +148,21 @@ public class DistinctGroupbyHashAggregationExec extends UnaryPhysicalExec {
     // Groupby_Key2 | Distinct1_Column_V3 |                     |                          |
     //--------------------------------------------------------------------------------------
 
-    List<List<Tuple>> tupleSlots = new ArrayList<List<Tuple>>();
+    List<TupleList> tupleSlots = new ArrayList<TupleList>();
 
     // aggregation with single grouping key
     for (int i = 0; i < hashAggregators.length; i++) {
-      if (!hashAggregators[i].iterator.hasNext()) {
+      HashAggregator hashAggregator = hashAggregators[i];
+      if (!hashAggregator.iterator.hasNext()) {
         nullCount++;
-        tupleSlots.add(new ArrayList<Tuple>());
+        tupleSlots.add(new TupleList());
         continue;
       }
-      Entry<Tuple, Map<Tuple, FunctionContext[]>> entry = hashAggregators[i].iterator.next();
+      Entry<KeyTuple, TupleMap<FunctionContext[]>> entry = hashAggregator.iterator.next();
       if (distinctGroupingKey == null) {
         distinctGroupingKey = entry.getKey();
       }
-      List<Tuple> aggregatedTuples = hashAggregators[i].aggregate(entry.getValue());
+      TupleList aggregatedTuples = hashAggregator.aggregate(entry.getValue());
       tupleSlots.add(aggregatedTuples);
     }
 
@@ -167,11 +173,7 @@ public class DistinctGroupbyHashAggregationExec extends UnaryPhysicalExec {
       // If DistinctGroupbyHashAggregationExec does not have any rows,
       // it should return NullDatum.
       if (totalNumRows == 0 && groupbyNodeNum == 0) {
-        Tuple tuple = new VTuple(outputColumnNum);
-        for (int i = 0; i < tuple.size(); i++) {
-          tuple.put(i, DatumFactory.createNullDatum());
-        }
-        return tuple;
+        return NullTuple.create(outputColumnNum);
       } else {
         return null;
       }
@@ -206,20 +208,23 @@ public class DistinctGroupbyHashAggregationExec extends UnaryPhysicalExec {
     */
 
     // currentAggregatedTuples has tuples which has same group key.
-    currentAggregatedTuples = new ArrayList<Tuple>();
+    if (currentAggregatedTuples == null) {
+      currentAggregatedTuples = new TupleList();
+    } else {
+      currentAggregatedTuples.clear();
+    }
     int listIndex = 0;
     while (true) {
-      // Each item in tuples is VTuple. So the tuples variable is two dimensions(tuple[aggregator][datum]).
       Tuple[] tuples = new Tuple[hashAggregators.length];
+      // Each item in tuples is VTuple. So the tuples variable is two dimensions(tuple[aggregator][datum]).
       for (int i = 0; i < hashAggregators.length; i++) {
-        List<Tuple> aggregatedTuples = tupleSlots.get(i);
+        TupleList aggregatedTuples = tupleSlots.get(i);
         if (aggregatedTuples.size() > listIndex) {
           tuples[i] = tupleSlots.get(i).get(listIndex);
         }
       }
 
       //merge
-      Tuple mergedTuple = new VTuple(outputColumnNum);
       int resultColumnIdx = 0;
 
       boolean allNull = true;
@@ -236,12 +241,12 @@ public class DistinctGroupbyHashAggregationExec extends UnaryPhysicalExec {
               // set group key tuple
               // Because each hashAggregator has different number of tuples,
               // sometimes getting group key from each hashAggregator will be null value.
-              mergedTuple.put(mergeTupleIndex, distinctGroupingKey.asDatum(mergeTupleIndex));
+              outTuple.put(mergeTupleIndex, distinctGroupingKey.asDatum(mergeTupleIndex));
             } else {
               if (tuples[i] != null) {
-                mergedTuple.put(mergeTupleIndex, tuples[i].asDatum(j));
+                outTuple.put(mergeTupleIndex, tuples[i].asDatum(j));
               } else {
-                mergedTuple.put(mergeTupleIndex, NullDatum.get());
+                outTuple.put(mergeTupleIndex, NullDatum.get());
               }
             }
           }
@@ -253,10 +258,15 @@ public class DistinctGroupbyHashAggregationExec extends UnaryPhysicalExec {
         break;
       }
 
-      currentAggregatedTuples.add(mergedTuple);
+      currentAggregatedTuples.add(outTuple);
       listIndex++;
     }
 
+    for (TupleList eachList : tupleSlots) {
+      eachList.clear();
+    }
+    tupleSlots.clear();
+
     currentAggregatedTupleIndex = 0;
     currentAggregatedTupleSize = currentAggregatedTuples.size();
 
@@ -267,13 +277,11 @@ public class DistinctGroupbyHashAggregationExec extends UnaryPhysicalExec {
     }
 
     fetchedRows++;
-    Tuple tuple = currentAggregatedTuples.get(currentAggregatedTupleIndex++);
-
-    return tuple;
+    return currentAggregatedTuples.get(currentAggregatedTupleIndex++);
   }
 
   private void loadChildHashTable() throws IOException {
-    Tuple tuple = null;
+    Tuple tuple;
     while(!context.isStopped() && (tuple = child.next()) != null) {
       for (int i = 0; i < hashAggregators.length; i++) {
         hashAggregators[i].compute(tuple);
@@ -296,6 +304,13 @@ public class DistinctGroupbyHashAggregationExec extends UnaryPhysicalExec {
     if (child != null) {
       child.close();
     }
+    if (currentAggregatedTuples != null) {
+      currentAggregatedTuples.clear();
+      currentAggregatedTuples = null;
+    }
+    if (distinctGroupingKeyColumnSet != null) {
+      distinctGroupingKeyColumnSet.clear();
+    }
   }
 
   public void rescan() throws IOException {
@@ -303,6 +318,9 @@ public class DistinctGroupbyHashAggregationExec extends UnaryPhysicalExec {
     for (int i = 0; i < hashAggregators.length; i++) {
       hashAggregators[i].initFetch();
     }
+    if (currentAggregatedTuples != null) {
+      currentAggregatedTuples.clear();
+    }
   }
 
   public float getProgress() {
@@ -327,44 +345,33 @@ public class DistinctGroupbyHashAggregationExec extends UnaryPhysicalExec {
 
   class HashAggregator {
     // Outer's GroupBy Key -> Each GroupByNode's Key -> FunctionContext
-    private Map<Tuple, Map<Tuple, FunctionContext[]>> hashTable;
-    private Iterator<Entry<Tuple, Map<Tuple, FunctionContext[]>>> iterator = null;
+    private TupleMap<TupleMap<FunctionContext[]>> hashTable;
+    private Iterator<Entry<KeyTuple, TupleMap<FunctionContext[]>>> iterator = null;
+
+    private final KeyProjector innerKeyProjector;
 
-    private int groupingKeyIds[];
     private final int aggFunctionsNum;
     private final AggregationFunctionCallEval aggFunctions[];
 
-    int tupleSize;
+    private final Tuple aggregatedTuple;
+
+    private final int tupleSize;
 
     public HashAggregator(GroupbyNode groupbyNode, Schema schema) throws IOException {
 
-      hashTable = new HashMap<Tuple, Map<Tuple, FunctionContext[]>>(10000);
+      hashTable = new TupleMap<TupleMap<FunctionContext[]>>(10000);
 
-      List<Integer> distinctGroupingKeyIdSet = new ArrayList<Integer>();
-      for (int i = 0; i < distinctGroupingKeyIds.length; i++) {
-        distinctGroupingKeyIdSet.add(distinctGroupingKeyIds[i]);
-      }
+      List<Column> groupingKeyColumnList = new ArrayList<Column>(distinctGroupingKeyColumnSet);
 
-      List<Integer> groupingKeyIdList = new ArrayList<Integer>(distinctGroupingKeyIdSet);
       Column[] keyColumns = groupbyNode.getGroupingColumns();
       Column col;
       for (int idx = 0; idx < keyColumns.length; idx++) {
         col = keyColumns[idx];
-        int keyIndex;
-        if (col.hasQualifier()) {
-          keyIndex = inSchema.getColumnId(col.getQualifiedName());
-        } else {
-          keyIndex = inSchema.getColumnIdByName(col.getSimpleName());
+        if (!distinctGroupingKeyColumnSet.contains(col)) {
+          groupingKeyColumnList.add(col);
         }
-        if (!distinctGroupingKeyIdSet.contains(keyIndex)) {
-          groupingKeyIdList.add(keyIndex);
-        }
-      }
-      int index = 0;
-      groupingKeyIds = new int[groupingKeyIdList.size()];
-      for (Integer eachId : groupingKeyIdList) {
-        groupingKeyIds[index++] = eachId;
       }
+      Column[] groupingKeyColumns = groupingKeyColumnList.toArray(new Column[groupingKeyColumnList.size()]);
 
       if (groupbyNode.hasAggFunctions()) {
         aggFunctions = groupbyNode.getAggFunctions();
@@ -378,7 +385,9 @@ public class DistinctGroupbyHashAggregationExec extends UnaryPhysicalExec {
         aggFunction.bind(context.getEvalContext(), schema);
       }
 
-      tupleSize = groupingKeyIds.length + aggFunctionsNum;
+      tupleSize = groupingKeyColumns.length + aggFunctionsNum;
+      aggregatedTuple = new VTuple(groupingKeyColumns.length + aggFunctionsNum);
+      innerKeyProjector = new KeyProjector(inSchema, groupingKeyColumns);
     }
 
     public int getTupleSize() {
@@ -386,22 +395,16 @@ public class DistinctGroupbyHashAggregationExec extends UnaryPhysicalExec {
     }
 
     public void compute(Tuple tuple) throws IOException {
-      Tuple outerKeyTuple = new VTuple(distinctGroupingKeyIds.length);
-      for (int i = 0; i < distinctGroupingKeyIds.length; i++) {
-        outerKeyTuple.put(i, tuple.asDatum(distinctGroupingKeyIds[i]));
-      }
+      KeyTuple outerKeyTuple = outerKeyProjector.project(tuple);
+      TupleMap<FunctionContext[]> distinctEntry = hashTable.get(outerKeyTuple);
 
-      Tuple keyTuple = new VTuple(groupingKeyIds.length);
-      for (int i = 0; i < groupingKeyIds.length; i++) {
-        keyTuple.put(i, tuple.asDatum(groupingKeyIds[i]));
-      }
-
-      Map<Tuple, FunctionContext[]> distinctEntry = hashTable.get(outerKeyTuple);
       if (distinctEntry == null) {
-        distinctEntry = new HashMap<Tuple, FunctionContext[]>();
+        distinctEntry = new TupleMap<FunctionContext[]>();
         hashTable.put(outerKeyTuple, distinctEntry);
       }
-      FunctionContext[] contexts = distinctEntry.get(keyTuple);
+
+      KeyTuple innerKeyTuple = innerKeyProjector.project(tuple);
+      FunctionContext[] contexts = distinctEntry.get(innerKeyTuple);
       if (contexts != null) {
         for (int i = 0; i < aggFunctions.length; i++) {
           aggFunctions[i].merge(contexts[i], tuple);
@@ -412,7 +415,7 @@ public class DistinctGroupbyHashAggregationExec extends UnaryPhysicalExec {
           contexts[i] = aggFunctions[i].newContext();
           aggFunctions[i].merge(contexts[i], tuple);
         }
-        distinctEntry.put(keyTuple, contexts);
+        distinctEntry.put(innerKeyTuple, contexts);
       }
     }
 
@@ -420,27 +423,29 @@ public class DistinctGroupbyHashAggregationExec extends UnaryPhysicalExec {
       iterator = hashTable.entrySet().iterator();
     }
 
-    public List<Tuple> aggregate(Map<Tuple, FunctionContext[]> groupTuples) {
-      List<Tuple> aggregatedTuples = new ArrayList<Tuple>();
+    public TupleList aggregate(Map<KeyTuple, FunctionContext[]> groupTuples) {
+      TupleList aggregatedTuples = new TupleList();
 
-      for (Entry<Tuple, FunctionContext[]> entry : groupTuples.entrySet()) {
-        Tuple tuple = new VTuple(groupingKeyIds.length + aggFunctionsNum);
+      for (Entry<KeyTuple, FunctionContext[]> entry : groupTuples.entrySet()) {
         Tuple groupbyKey = entry.getKey();
         int index = 0;
         for (; index < groupbyKey.size(); index++) {
-          tuple.put(index, groupbyKey.asDatum(index));
+          aggregatedTuple.put(index, groupbyKey.asDatum(index));
         }
 
         FunctionContext[] contexts = entry.getValue();
         for (int i = 0; i < aggFunctionsNum; i++, index++) {
-          tuple.put(index, aggFunctions[i].terminate(contexts[i]));
+          aggregatedTuple.put(index, aggFunctions[i].terminate(contexts[i]));
         }
-        aggregatedTuples.add(tuple);
+        aggregatedTuples.add(aggregatedTuple);
       }
       return aggregatedTuples;
     }
 
     public void close() throws IOException {
+      for (TupleMap<FunctionContext[]> map : hashTable.values()) {
+        map.clear();
+      }
       hashTable.clear();
       hashTable = null;
       iterator = null;

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbySecondAggregationExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbySecondAggregationExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbySecondAggregationExec.java
index 5a262a6..b3edab6 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbySecondAggregationExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbySecondAggregationExec.java
@@ -1,4 +1,4 @@
-  /**
+/**
  * 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
@@ -18,22 +18,20 @@
 
 package org.apache.tajo.engine.planner.physical;
 
-  import org.apache.commons.logging.Log;
-  import org.apache.commons.logging.LogFactory;
-  import org.apache.tajo.catalog.Column;
-  import org.apache.tajo.plan.expr.AggregationFunctionCallEval;
-  import org.apache.tajo.plan.function.FunctionContext;
-  import org.apache.tajo.plan.logical.DistinctGroupbyNode;
-  import org.apache.tajo.plan.logical.GroupbyNode;
-  import org.apache.tajo.storage.Tuple;
-  import org.apache.tajo.storage.VTuple;
-  import org.apache.tajo.worker.TaskAttemptContext;
-
-  import java.io.IOException;
-  import java.util.ArrayList;
-  import java.util.HashSet;
-  import java.util.List;
-  import java.util.Set;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.tajo.catalog.Column;
+import org.apache.tajo.datum.Datum;
+import org.apache.tajo.plan.expr.AggregationFunctionCallEval;
+import org.apache.tajo.plan.function.FunctionContext;
+import org.apache.tajo.plan.logical.DistinctGroupbyNode;
+import org.apache.tajo.plan.logical.GroupbyNode;
+import org.apache.tajo.storage.Tuple;
+import org.apache.tajo.storage.VTuple;
+import org.apache.tajo.worker.TaskAttemptContext;
+
+import java.io.IOException;
+import java.util.*;
 
 /**
  * This class adjusts shuffle columns between DistinctGroupbyFirstAggregationExec and
@@ -86,10 +84,21 @@ public class DistinctGroupbySecondAggregationExec extends UnaryPhysicalExec {
   private AggregationFunctionCallEval[] nonDistinctAggrFunctions;
   private int nonDistinctAggrTupleStartIndex = -1;
 
+  // Key tuples may have various lengths. The below two maps are used to cache key tuple instances.
+  // Each map is a mapping of key length to key tuple.
+  private Map<Integer, Tuple> keyTupleMap = new HashMap<Integer, Tuple>();
+  private Map<Integer, Tuple> prevKeyTupleMap = new HashMap<Integer, Tuple>();
+
+  private Tuple prevKeyTuple = null;
+  private Tuple prevTuple = null;
+  private final Tuple outTuple;
+  private int prevSeq = -1;
+
   public DistinctGroupbySecondAggregationExec(TaskAttemptContext context, DistinctGroupbyNode plan, SortExec sortExec)
       throws IOException {
     super(context, plan.getInSchema(), plan.getOutSchema(), sortExec);
     this.plan = plan;
+    outTuple = new VTuple(outSchema.size());
   }
 
   @Override
@@ -158,20 +167,15 @@ public class DistinctGroupbySecondAggregationExec extends UnaryPhysicalExec {
     }
   }
 
-  Tuple prevKeyTuple = null;
-  Tuple prevTuple = null;
-  int prevSeq = -1;
-
   @Override
   public Tuple next() throws IOException {
     if (finished) {
       return null;
     }
 
-    Tuple result = null;
     while (!context.isStopped()) {
-      Tuple childTuple = child.next();
-      if (childTuple == null) {
+      Tuple tuple = child.next();
+      if (tuple == null) {
         finished = true;
 
         if (prevTuple == null) {
@@ -181,15 +185,8 @@ public class DistinctGroupbySecondAggregationExec extends UnaryPhysicalExec {
         if (prevSeq == 0 && nonDistinctAggrFunctions != null) {
           terminatedNonDistinctAggr(prevTuple);
         }
-        result = prevTuple;
-        break;
-      }
-
-      Tuple tuple = null;
-      try {
-        tuple = childTuple.clone();
-      } catch (CloneNotSupportedException e) {
-        throw new IOException(e.getMessage(), e);
+        outTuple.put(prevTuple.getValues());
+        return outTuple;
       }
 
       int distinctSeq = tuple.getInt2(0);
@@ -201,8 +198,8 @@ public class DistinctGroupbySecondAggregationExec extends UnaryPhysicalExec {
           initNonDistinctAggrContext();
           mergeNonDistinctAggr(tuple);
         }
-        prevKeyTuple = keyTuple;
-        prevTuple = tuple;
+        prevKeyTuple = getKeyTuple(prevKeyTupleMap, keyTuple.getValues());
+        prevTuple = new VTuple(tuple.getValues());
         prevSeq = distinctSeq;
         continue;
       }
@@ -212,20 +209,20 @@ public class DistinctGroupbySecondAggregationExec extends UnaryPhysicalExec {
         if (prevSeq == 0 && nonDistinctAggrFunctions != null) {
           terminatedNonDistinctAggr(prevTuple);
         }
-        result = prevTuple;
+        outTuple.put(prevTuple.getValues());
 
-        prevKeyTuple = keyTuple;
-        prevTuple = tuple;
+        prevKeyTuple = getKeyTuple(prevKeyTupleMap, keyTuple.getValues());
+        prevTuple.put(tuple.getValues());
         prevSeq = distinctSeq;
 
         if (distinctSeq == 0 && nonDistinctAggrFunctions != null) {
           initNonDistinctAggrContext();
           mergeNonDistinctAggr(tuple);
         }
-        break;
+        return outTuple;
       } else {
-        prevKeyTuple = keyTuple;
-        prevTuple = tuple;
+        prevKeyTuple = getKeyTuple(prevKeyTupleMap, keyTuple.getValues());
+        prevTuple.put(tuple.getValues());
         prevSeq = distinctSeq;
         if (distinctSeq == 0 && nonDistinctAggrFunctions != null) {
           mergeNonDistinctAggr(tuple);
@@ -233,7 +230,7 @@ public class DistinctGroupbySecondAggregationExec extends UnaryPhysicalExec {
       }
     }
 
-    return result;
+    return null;
   }
 
   private void initNonDistinctAggrContext() {
@@ -265,8 +262,8 @@ public class DistinctGroupbySecondAggregationExec extends UnaryPhysicalExec {
 
   private Tuple getKeyTuple(int distinctSeq, Tuple tuple) {
     int[] columnIndexes = distinctKeyIndexes[distinctSeq];
-
-    Tuple keyTuple = new VTuple(numGroupingColumns + columnIndexes.length + 1);
+    int keyLength = numGroupingColumns + columnIndexes.length + 1;
+    Tuple keyTuple = getKeyTuple(keyTupleMap, keyLength);
     keyTuple.put(0, tuple.asDatum(0));
     for (int i = 0; i < numGroupingColumns; i++) {
       keyTuple.put(i + 1, tuple.asDatum(i + 1));
@@ -278,16 +275,39 @@ public class DistinctGroupbySecondAggregationExec extends UnaryPhysicalExec {
     return keyTuple;
   }
 
+  private static Tuple getKeyTuple(Map<Integer, Tuple> keyTupleMap, Datum[] values) {
+    Tuple keyTuple = getKeyTuple(keyTupleMap, values.length);
+    keyTuple.put(values);
+    return keyTuple;
+  }
+
+  private static Tuple getKeyTuple(Map<Integer, Tuple> keyTupleMap, int keyLength) {
+    Tuple keyTuple;
+    if (keyTupleMap.containsKey(keyLength)) {
+      keyTuple = keyTupleMap.get(keyLength);
+    } else {
+      keyTuple = new VTuple(keyLength);
+      keyTupleMap.put(keyLength, keyTuple);
+    }
+    return keyTuple;
+  }
+
   @Override
   public void rescan() throws IOException {
     super.rescan();
     prevKeyTuple = null;
     prevTuple = null;
     finished = false;
+    keyTupleMap.clear();
+    prevKeyTupleMap.clear();
   }
 
   @Override
   public void close() throws IOException {
     super.close();
+    keyTupleMap.clear();
+    prevKeyTupleMap.clear();
+    prevKeyTuple = null;
+    prevTuple = null;
   }
 }

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbySortAggregationExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbySortAggregationExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbySortAggregationExec.java
index c91dcca..58cfca4 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbySortAggregationExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbySortAggregationExec.java
@@ -22,7 +22,6 @@ import org.apache.tajo.catalog.statistics.TableStats;
 import org.apache.tajo.common.TajoDataTypes;
 import org.apache.tajo.datum.DatumFactory;
 import org.apache.tajo.datum.NullDatum;
-import org.apache.tajo.plan.expr.AggregationFunctionCallEval;
 import org.apache.tajo.plan.logical.DistinctGroupbyNode;
 import org.apache.tajo.plan.logical.GroupbyNode;
 import org.apache.tajo.storage.Tuple;
@@ -42,6 +41,8 @@ public class DistinctGroupbySortAggregationExec extends PhysicalExec {
 
   private int[] resultColumnIdIndexes;
 
+  private final Tuple outTuple;
+
   public DistinctGroupbySortAggregationExec(final TaskAttemptContext context, DistinctGroupbyNode plan,
                                             SortAggregateExec[] aggregateExecs) throws IOException {
     super(context, plan.getInSchema(), plan.getOutSchema());
@@ -50,6 +51,7 @@ public class DistinctGroupbySortAggregationExec extends PhysicalExec {
 
     currentTuples = new Tuple[groupbyNodeNum];
     outColumnNum = outSchema.size();
+    outTuple = new VTuple(outColumnNum);
 
     int allGroupbyOutColNum = 0;
     for (GroupbyNode eachGroupby: plan.getSubPlans()) {
@@ -110,23 +112,20 @@ public class DistinctGroupbySortAggregationExec extends PhysicalExec {
       return null;
     }
 
-    Tuple mergedTuple = new VTuple(outColumnNum);
-
     int mergeTupleIndex = 0;
     for (int i = 0; i < currentTuples.length; i++) {
       int tupleSize = currentTuples[i].size();
       for (int j = 0; j < tupleSize; j++) {
         if (resultColumnIdIndexes[mergeTupleIndex] >= 0) {
-          mergedTuple.put(resultColumnIdIndexes[mergeTupleIndex], currentTuples[i].asDatum(j));
+          outTuple.put(resultColumnIdIndexes[mergeTupleIndex], currentTuples[i].asDatum(j));
         }
         mergeTupleIndex++;
       }
     }
-    return mergedTuple;
+    return outTuple;
   }
 
   private Tuple getEmptyTuple() {
-    Tuple tuple = new VTuple(outSchema.size());
     NullDatum nullDatum = DatumFactory.createNullDatum();
 
     int tupleIndex = 0;
@@ -134,23 +133,23 @@ public class DistinctGroupbySortAggregationExec extends PhysicalExec {
       for (int i = 0; i < aggExec.aggFunctionsNum; i++, tupleIndex++) {
         String funcName = aggExec.aggFunctions[i].getName();
         if ("min".equals(funcName) || "max".equals(funcName) || "avg".equals(funcName) || "sum".equals(funcName)) {
-          tuple.put(resultColumnIdIndexes[tupleIndex], DatumFactory.createNullDatum());
+          outTuple.put(resultColumnIdIndexes[tupleIndex], DatumFactory.createNullDatum());
         }
         else
         {
           TajoDataTypes.Type type = outSchema.getColumn(resultColumnIdIndexes[tupleIndex]).getDataType().getType();
           if (type == TajoDataTypes.Type.INT8) {
-            tuple.put(resultColumnIdIndexes[tupleIndex], DatumFactory.createInt8(nullDatum.asInt8()));
+            outTuple.put(resultColumnIdIndexes[tupleIndex], DatumFactory.createInt8(nullDatum.asInt8()));
           } else if (type == TajoDataTypes.Type.INT4) {
-            tuple.put(resultColumnIdIndexes[tupleIndex], DatumFactory.createInt4(nullDatum.asInt4()));
+            outTuple.put(resultColumnIdIndexes[tupleIndex], DatumFactory.createInt4(nullDatum.asInt4()));
           } else if (type == TajoDataTypes.Type.INT2) {
-            tuple.put(resultColumnIdIndexes[tupleIndex], DatumFactory.createInt2(nullDatum.asInt2()));
+            outTuple.put(resultColumnIdIndexes[tupleIndex], DatumFactory.createInt2(nullDatum.asInt2()));
           } else if (type == TajoDataTypes.Type.FLOAT4) {
-            tuple.put(resultColumnIdIndexes[tupleIndex], DatumFactory.createFloat4(nullDatum.asFloat4()));
+            outTuple.put(resultColumnIdIndexes[tupleIndex], DatumFactory.createFloat4(nullDatum.asFloat4()));
           } else if (type == TajoDataTypes.Type.FLOAT8) {
-            tuple.put(resultColumnIdIndexes[tupleIndex], DatumFactory.createFloat8(nullDatum.asFloat8()));
+            outTuple.put(resultColumnIdIndexes[tupleIndex], DatumFactory.createFloat8(nullDatum.asFloat8()));
           } else {
-            tuple.put(resultColumnIdIndexes[tupleIndex], DatumFactory.createNullDatum());
+            outTuple.put(resultColumnIdIndexes[tupleIndex], DatumFactory.createNullDatum());
           }
         }
       }
@@ -159,7 +158,7 @@ public class DistinctGroupbySortAggregationExec extends PhysicalExec {
     finished = true;
     first = false;
 
-    return tuple;
+    return outTuple;
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/tajo/blob/4820610f/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbyThirdAggregationExec.java
----------------------------------------------------------------------
diff --git a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbyThirdAggregationExec.java b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbyThirdAggregationExec.java
index 5791230..9e9e9b4 100644
--- a/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbyThirdAggregationExec.java
+++ b/tajo-core/src/main/java/org/apache/tajo/engine/planner/physical/DistinctGroupbyThirdAggregationExec.java
@@ -51,6 +51,11 @@ public class DistinctGroupbyThirdAggregationExec extends UnaryPhysicalExec {
 
   private int[] resultTupleIndexes;
 
+  private Tuple outTuple;
+  private Tuple keyTuple;
+  private Tuple prevKeyTuple = null;
+  private Tuple prevTuple = null;
+
   public DistinctGroupbyThirdAggregationExec(TaskAttemptContext context, DistinctGroupbyNode plan, SortExec sortExec)
       throws IOException {
     super(context, plan.getInSchema(), plan.getOutSchema(), sortExec);
@@ -63,6 +68,7 @@ public class DistinctGroupbyThirdAggregationExec extends UnaryPhysicalExec {
 
     numGroupingColumns = plan.getGroupingColumns().length;
     resultTupleLength = numGroupingColumns;
+    keyTuple = new VTuple(numGroupingColumns);
 
     List<GroupbyNode> groupbyNodes = plan.getSubPlans();
 
@@ -86,6 +92,7 @@ public class DistinctGroupbyThirdAggregationExec extends UnaryPhysicalExec {
       resultTupleLength += eachGroupby.getAggFunctions().length;
     }
     aggregators = aggregatorList.toArray(new DistinctFinalAggregator[]{});
+    outTuple = new VTuple(resultTupleLength);
 
     // make output schema mapping index
     resultTupleIndexes = new int[outSchema.size()];
@@ -128,21 +135,16 @@ public class DistinctGroupbyThirdAggregationExec extends UnaryPhysicalExec {
     }
   }
 
-  Tuple prevKeyTuple = null;
-  Tuple prevTuple = null;
-
   @Override
   public Tuple next() throws IOException {
     if (finished) {
       return null;
     }
 
-    Tuple resultTuple = new VTuple(resultTupleLength);
-
     while (!context.isStopped()) {
-      Tuple childTuple = child.next();
+      Tuple tuple = child.next();
       // Last tuple
-      if (childTuple == null) {
+      if (tuple == null) {
         finished = true;
 
         if (prevTuple == null) {
@@ -156,19 +158,13 @@ public class DistinctGroupbyThirdAggregationExec extends UnaryPhysicalExec {
         }
 
         for (int i = 0; i < numGroupingColumns; i++) {
-          resultTuple.put(resultTupleIndexes[i], prevTuple.asDatum(i + 1));
+          outTuple.put(resultTupleIndexes[i], prevTuple.asDatum(i + 1));
         }
         for (DistinctFinalAggregator eachAggr: aggregators) {
-          eachAggr.terminate(resultTuple);
+          eachAggr.terminate(outTuple);
         }
-        break;
-      }
 
-      Tuple tuple = null;
-      try {
-        tuple = childTuple.clone();
-      } catch (CloneNotSupportedException e) {
-        throw new IOException(e.getMessage(), e);
+        return outTuple;
       }
 
       int distinctSeq = tuple.getInt2(0);
@@ -176,8 +172,8 @@ public class DistinctGroupbyThirdAggregationExec extends UnaryPhysicalExec {
 
       // First tuple
       if (prevKeyTuple == null) {
-        prevKeyTuple = keyTuple;
-        prevTuple = tuple;
+        prevKeyTuple = new VTuple(keyTuple.getValues());
+        prevTuple = new VTuple(tuple.getValues());
 
         aggregators[distinctSeq].merge(tuple);
         continue;
@@ -186,38 +182,36 @@ public class DistinctGroupbyThirdAggregationExec extends UnaryPhysicalExec {
       if (!prevKeyTuple.equals(keyTuple)) {
         // new grouping key
         for (int i = 0; i < numGroupingColumns; i++) {
-          resultTuple.put(resultTupleIndexes[i], prevTuple.asDatum(i + 1));
+          outTuple.put(resultTupleIndexes[i], prevTuple.asDatum(i + 1));
         }
         for (DistinctFinalAggregator eachAggr: aggregators) {
-          eachAggr.terminate(resultTuple);
+          eachAggr.terminate(outTuple);
         }
 
-        prevKeyTuple = keyTuple;
-        prevTuple = tuple;
+        prevKeyTuple.put(keyTuple.getValues());
+        prevTuple.put(tuple.getValues());
 
         aggregators[distinctSeq].merge(tuple);
-        break;
+        return outTuple;
       } else {
-        prevKeyTuple = keyTuple;
-        prevTuple = tuple;
+        prevKeyTuple.put(keyTuple.getValues());
+        prevTuple.put(tuple.getValues());
         aggregators[distinctSeq].merge(tuple);
       }
     }
 
-    return resultTuple;
+    return null;
   }
 
   private Tuple makeEmptyTuple() {
-    Tuple resultTuple = new VTuple(resultTupleLength);
     for (DistinctFinalAggregator eachAggr: aggregators) {
-      eachAggr.terminateEmpty(resultTuple);
+      eachAggr.terminateEmpty(outTuple);
     }
 
-    return resultTuple;
+    return outTuple;
   }
 
   private Tuple getGroupingKeyTuple(Tuple tuple) {
-    Tuple keyTuple = new VTuple(numGroupingColumns);
     for (int i = 0; i < numGroupingColumns; i++) {
       keyTuple.put(i, tuple.asDatum(i + 1));
     }