In Apache Hive, It’s always a matter of confusion that how SORT BY, ORDER BY, DISTRIBUTE BY and CLUSTER BY differs. I have compiled a set of differences between these based on attributes like how will final output look like and ordering of data in output –
Hive uses the columns in SORT BY to sort the rows before feeding the rows to a reducer. The sort order will be dependent on the column types. If the column is of numeric type, then the sort order is also in numeric order. If the column is of string type, then the sort order will be lexicographical order.
Ordering : It orders data at each of ‘N’ reducers , but each reducer can have overlapping ranges of data.
Outcome : N or more sorted files with overlapping ranges.
Let’s understand with an example :-
SELECT key, value FROM src SORT BY key ASC, value DESC
The query had 2 reducers, and the output of each is:
Reducer 1 :
Reducer 2 :
As, we can see, each reducer output is ordered but total ordering is missing , since we end up with multiple outputs per reducer.
This is similar to ORDER BY in SQL Language.
In Hive, ORDER BY guarantees total ordering of data, but for that it has to be passed on to a single reducer, which is normally unacceptable and therefore in strict mode, hive makes it compulsory to use LIMIT with ORDER BY so that reducer doesn’t get overburdened.
Ordering : Total Ordered data.
Outcome : Single output i.e. fully ordered.
For example :
SELECT key, value FROM src ORDER BY key ASC, value DESC
Hive uses the columns in Distribute By to distribute the rows among reducers. All rows with the same Distribute By columns will go to the same reducer.
It ensures each of N reducers gets non-overlapping ranges of column, but doesn’t sort the output of each reducer. You end up with N or more unsorted files with non-overlapping ranges.
Example ( taken directly from Hive wiki ):-
We are Distributing By x on the following 5 rows to 2 reducer:
Reducer 1 got
Reducer 2 got
Note that all rows with the same key x1 is guaranteed to be distributed to the same reducer (reducer 1 in this case), but they are not guaranteed to be clustered in adjacent positions.
Cluster By is a short-cut for both Distribute By and Sort By.
CLUSTER BY x ensures each of N reducers gets non-overlapping ranges, then sorts by those ranges at the reducers.
Ordering : Global ordering between multiple reducers.
Outcome : N or more sorted files with non-overlapping ranges.
For the same example as above , if we use Cluster By x, the two reducers will further sort rows on x:
Reducer 1 got
Reducer 2 got
Instead of specifying Cluster By, the user can specify Distribute By and Sort By, so the partition columns and sort columns can be different.
References : –
You may also be interested in some other BigData posts –