Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Tip
titleTipp

All Hive keywords are case-insensitive, including the names of Hive operators and functions. I.e: length and LENGTH are also accepted by the Hive.

Mathematical Functions

Built-in Aggregate Functions (UDAF)

Hive Aggregate Functions (UDAG) take multiple rows as input and return a single row as output. Depending on the functionality it mainly aggregates the values and returns a single result. These functions are mainly used in the GROUP BY statements.

Info

These functions can be used without GROUP BY as well

...


Return Type

Name(Signature)

Description

double

bigint

round

count(

DOUBLE a)

Returns the rounded BIGINT value of a.

double

round(DOUBLE a, INT d)

Returns a rounded to d decimal places.

doublebround(DOUBLE a)Returns the rounded BIGINT value of a using HALF_EVEN rounding mode. Also known as Gaussian rounding or bankers' rounding. Example: bround(2.5) = 2, bround(3.5) = 4.doublebround(DOUBLE a, INT d)Returns a rounded to d decimal places using HALF_EVEN rounding mode.  Example: bround(8.25, 1) = 8.2, bround(8.35, 1) = 8.4.

bigint

floor(DOUBLE a)

Returns the maximum BIGINT value that is equal to or less than a.

bigint

ceil(DOUBLE a), ceiling(DOUBLE a)

Returns the minimum BIGINT value that is equal to or greater than a.

double

rand(), rand(INT seed)

Returns a random number (that changes from row to row) that is distributed uniformly from 0 to 1. Specifying the seed will make sure the generated random number sequence is deterministic.

double

exp(DOUBLE a), exp(DECIMAL a)

Returns ea where e is the base of the natural logarithm.

double

ln(DOUBLE a), ln(DECIMAL a)

Returns the natural logarithm of the argument a.

double

log10(DOUBLE a), log10(DECIMAL a)

Returns the base-10 logarithm of the argument a.

double

log2(DOUBLE a), log2(DECIMAL a)

Returns the base-2 logarithm of the argument a

double

log(DOUBLE base, DOUBLE a)

log(DECIMAL base, DECIMAL a)

Returns the base-base logarithm of the argument a.

double

pow(DOUBLE a, DOUBLE p), power(DOUBLE a, DOUBLE p)

Returns ap.

double

sqrt(DOUBLE a), sqrt(DECIMAL a)

Returns the square root of a.

string

bin(BIGINT a)

Returns the number in binary format.

string

hex(BIGINT a) hex(STRING a) hex(BINARY a)

If the argument is an INT or binary, hex returns the number as a STRING in hexadecimal format. Otherwise if the number is a STRING, it converts each character into its hexadecimal representation and returns the resulting STRING

binary

unhex(STRING a)

Inverse of hex. Interprets each pair of characters as a hexadecimal number and converts to the byte representation of the number.

string

conv(BIGINT num, INT from_base, INT to_base), conv(STRING num, INT from_base, INT to_base)

Converts a number from a given base to another.

double

abs(DOUBLE a)

Returns the absolute value.

int or double

pmod(INT a, INT b), pmod(DOUBLE a, DOUBLE b)

Returns the positive value of a mod b.

double

sin(DOUBLE a), sin(DECIMAL a)

Returns the sine of a (a is in radians).

double

asin(DOUBLE a), asin(DECIMAL a)

Returns the arc sin of a if -1<=a<=1 or NULL otherwise

double

cos(DOUBLE a), cos(DECIMAL a)

Returns the cosine of a (a is in radians)

double

acos(DOUBLE a), acos(DECIMAL a)

Returns the arccosine of a if -1<=a<=1 or NULL otherwise.

double

tan(DOUBLE a), tan(DECIMAL a)

Returns the tangent of a (a is in radians).

double

atan(DOUBLE a), atan(DECIMAL a)

Returns the arctangent of a.

double

degrees(DOUBLE a), degrees(DECIMAL a)

Converts value of a from radians to degrees

double

radians(DOUBLE a), radians(DOUBLE a)

Converts value of a from degrees to radians

int or double

positive(INT a), positive(DOUBLE a)

Returns a.

int or double

negative(INT a), negative(DOUBLE a)

Returns -a.

double or int

sign(DOUBLE a), sign(DECIMAL a)

Returns the sign of a as '1.0' (if a is positive) or '-1.0' (if a is negative), '0.0' otherwise. The decimal version returns INT instead of DOUBLE. 

double

e()

Returns the value of e.

double

pi()

Returns the value of pi.

bigintfactorial(INT a)Returns the factorial of a Valid a is [0..20].doublecbrt(DOUBLE a)Returns the cube root of a double value.

int

bigint

shiftleft(TINYINT|SMALLINT|INT a, INT b)

shiftleft(BIGINT a, INT b)

Bitwise left shift. Shifts a b positions to the left.

Returns int for tinyint, smallint and int a. Returns bigint for bigint a.

int

bigint

shiftright(TINYINT|SMALLINT|INT a, INT b)

shiftright(BIGINT a, INT b)

Bitwise right shift. Shifts a b positions to the right.

Returns int for tinyint, smallint and int a. Returns bigint for bigint a.

int

bigint

shiftrightunsigned(TINYINT|SMALLINT|INT a, INT b),

shiftrightunsigned(BIGINT a, INT b)

Bitwise unsigned right shift. Shifts a b positions to the right.

Returns int for tinyint, smallint and int a. Returns bigint for bigint a.

Tgreatest(T v1, T v2, ...)Returns the greatest value of the list of values. Fixed to return NULL when one or more arguments are NULL, and strict type restriction relaxed, consistent with ">" operator.Tleast(T v1, T v2, ...)Returns the least value of the list of values. Fixed to return NULL when one or more arguments are NULL, and strict type restriction relaxed, consistent with "<" operator.intwidth_bucket(NUMERIC expr, NUMERIC min_value, NUMERIC max_value, INT num_buckets)

Returns an integer between 0 and num_buckets+1 by mapping expr into the ith equally sized bucket. Buckets are made by dividing [min_value, max_value] into equally sized regions. If expr < min_value, return 1, if expr > max_value return num_buckets+1. See https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions214.htm

Collection Functions

The following built-in collection functions are supported in Hive. 

...

Return Type

...

Name(Signature)

...

Description

...

int

...

size(Map<K.V>)

...

Returns the number of elements in the map type.

...

int

...

size(Array<T>)

...

Returns the number of elements in the array type.

...

array<K>

...

map_keys(Map<K.V>)

...

Returns an unordered array containing the keys of the input map.

...

array<V>

...

map_values(Map<K.V>)

...

Returns an unordered array containing the values of the input map.

...

boolean

...

array_contains(Array<T>, value)

...

Returns TRUE if the array contains the provided paramter value.

...

array<t>

...

sort_array(Array<T>)

...

Sorts the input array in ascending order according to the natural ordering of the array elements and returns it.

*), count(expr), count(DISTINCT expr[, expr...])

count(*) - Returns the total number of retrieved rows, including rows containing NULL values.

count(expr) - Returns the number of rows for which the supplied expression is non-NULL.

count(DISTINCT expr[, expr]) - Returns the number of rows for which the supplied expression(s) are unique and non-NULL. Execution of this can be optimized with hive.optimize.distinct.rewrite.

double

sum(col), sum(DISTINCT col)

Returns the sum of the elements in the group or the sum of the distinct values of the column in the group.

double

avg(col), avg(DISTINCT col)

Returns the average of the elements in the group or the average of the distinct values of the column in the group.

double

min(col)

Returns the minimum of the column in the group.

double

max(col)

Returns the maximum value of the column in the group.

double

variance(col), var_pop(col)

Returns the variance of a numeric column in the group.

double

var_samp(col)

Returns the unbiased sample variance of a numeric column in the group.

double

stddev_pop(col)

Returns the standard deviation of a numeric column in the group.

double

stddev_samp(col)

Returns the unbiased sample standard deviation of a numeric column in the group.

double

covar_pop(col1, col2)

Returns the population covariance of a pair of numeric columns in the group.

double

covar_samp(col1, col2)

Returns the sample covariance of a pair of numeric columns in the group.

double

corr(col1, col2)

Returns the Pearson coefficient of correlation of a pair of numeric columns in the group.

double

percentile(BIGINT col, p)

Returns the exact pth percentile of a column in the group (does not work with floating point types). p must be between 0 and 1. NOTE: A true percentile can only be computed for integer values. Use PERCENTILE_APPROX if your input is non-integral.

array<double>

percentile(BIGINT col, array(p1 [, p2]...))

Returns the exact percentiles p1, p2, ... of a column in the group (does not work with floating point types). pi must be between 0 and 1. NOTE: A true percentile can only be computed for integer values. Use PERCENTILE_APPROX if your input is non-integral.

double

percentile_approx(DOUBLE col, p [, B])

Returns an approximate pth percentile of a numeric column (including floating point types) in the group. The B parameter controls approximation accuracy at the cost of memory. Higher values yield better approximations, and the default is 10,000. When the number of distinct values in col is smaller than B, this gives an exact percentile value.

array<double>

percentile_approx(DOUBLE col, array(p1 [, p2]...) [, B])

Same as above, but accepts and returns an array of percentile values instead of a single one.

double

regr_avgx(independent, dependent)

Equivalent to avg(dependent). 

double

regr_avgy(independent, dependent)

Equivalent to avg(independent). 

double

regr_count(independent, dependent)

Returns the number of non-null pairs used to fit the linear regression line. 

double

regr_intercept(independent, dependent)

Returns the y-intercept of the linear regression line, i.e. the value of b in the equation dependent = a * independent + b.

double

regr_r2(independent, dependent)

Returns the coefficient of determination for the regression. 

double

regr_slope(independent, dependent)

Returns the slope of the linear regression line, i.e. the value of an in the equation dependent = a * independent + b. 

double

regr_sxx(independent, dependent)

Equivalent to regr_count(independent, dependent) * var_pop(dependent). 

double

regr_sxy(independent, dependent)

Equivalent to regr_count(independent, dependent) * covar_pop(independent, dependent). 

doubleregr_syy(independent, dependent)

Equivalent to regr_count(independent, dependent) * var_pop(independent).

array<struct {'x','y'}>

histogram_numeric(col, b)

Computes a histogram of a numeric column in the group using b non-uniformly spaced bins. The output is an array of size b of double-valued (x,y) coordinates that represent the bin centers and heights

array

collect_set(col)

Returns a set of objects with duplicate elements eliminated.

array

collect_list(col)

Returns a list of objects with duplicates. 

intntile(INTEGER x)

Divides an ordered partition into x groups called buckets and assign a bucket number to each row in the partition. This allows easy calculation of tertiles, quartiles, deciles, percentiles, and other common summary statistics.


Tip

Most of the UDAF ignore NULL values. 

String Functions

There is no good engine without string manipulation functions. Apache Hive has rich built-in string functions. 

Return Type

Name(Signature)

Description

int

ascii(string str)

Returns the numeric value of the first character of str.

string

base64(binary bin)

Converts the argument from binary to a base64 string.

intcharacter_length(string str)Returns the number of UTF-8 characters contained in str. The function char_length is shorthand for this function.
stringchr(bigint|double A)Returns the ASCII character having the binary equivalent to A. If A is larger than 256 the result is equivalent to chr(A % 256). Example: select chr(88); returns "X".

string

concat(string|binary A, string|binary B...)

Returns the string or bytes resulting from concatenating the strings or bytes passed in as parameters in order. For example, concat('foo', 'bar') results in 'foobar'. Note that this function can take any number of input strings.

array<struct<string,double>>

context_ngrams(array<array<string>>, array<string>, int K, int pf)

Returns the top-k contextual N-grams from a set of tokenized sentences, given a string of "context". See StatisticsAndDataMining for more information.

string

concat_ws(string SEP, string A, string B...)

Like concat() above, but with custom separator SEP.

string

concat_ws(string SEP, array<string>)

Like concat_ws() above, but taking an array of strings.

string

decode(binary bin, string charset)

Decodes the first argument into a String using the provided character set (one of 'US-ASCII', 'ISO-8859-1', 'UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16'). If either argument is null, the result will also be null.

stringelt(N int,str1 string,str2 string,str3 string,...)

Return string at index number. For example elt(2,'hello','world') returns 'world'. Returns NULL if N is less than 1 or greater than the number of arguments.

binary

encode(string src, string charset)

Encodes the first argument into a BINARY using the provided character set (one of 'US-ASCII', 'ISO-8859-1', 'UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16'). If either argument is null, the result will also be null. 

intfield(val T,val1 T,val2 T,val3 T,...)

Returns the index of val in the val1,val2,val3,... list or 0 if not found. For example field('world','say','hello','world') returns 3.
All primitive types are supported, arguments are compared using str.equals(x). If val is NULL, the return value is 0.

int

find_in_set(string str, string strList)

Returns the first occurance of str in strList where strList is a comma-delimited string. Returns null if either argument is null. Returns 0 if the first argument contains any commas. For example, find_in_set('ab', 'abc,b,ab,c,def') returns 3.

string

format_number(number x, int d)

Formats the number X to a format like '#,###,###.##', rounded to D decimal places, and returns the result as a string. If D is 0, the result has no decimal point or fractional part.

string

get_json_object(string json_string, string path)

Extracts json object from a json string based on json path specified, and returns json string of the extracted json object. It will return null if the input json string is invalid.

Note
titleNote

The json path can only have the characters [0-9a-z_], i.e., no upper-case or special characters. Also, the keys *cannot start with numbers.* This is due to restrictions on Hive column names.


boolean

in_file(string str, string filename)

Returns true if the string str appears as an entire line in filename.

int

instr(string str, string substr)

Returns the position of the first occurrence of substr in str. Returns null if either of the arguments are null and returns 0 if substr could not be found in str. Be aware that this is not zero-based. The first character in str has index 1.

int

length(string A)

Returns the length of the string.

int

locate(string substr, string str[, int pos])

Returns the position of the first occurrence of substr in str after position pos.

string

lower(string A) lcase(string A)

Returns the string resulting from converting all characters of B to lower case. For example, lower('fOoBaR') results in 'foobar'.

string

lpad(string str, int len, string pad)

Returns str, left-padded with pad to a length of len. If str is longer than len, the return value is shortened to len characters. In case of empty pad string, the return value is null.

string

ltrim(string A)

Returns the string resulting from trimming spaces from the beginning(left hand side) of A. For example, ltrim(' foobar ') results in 'foobar '.

array<struct<string,double>>

ngrams(array<array<string>>, int N, int K, int pf)

Returns the top-k N-grams from a set of tokenized sentences, such as those returned by the sentences() UDAF. See StatisticsAndDataMining for more information.

intoctet_length(string str)Returns the number of octets required to hold the string str in UTF-8 encoding.  Note that octet_length(str) can be larger than character_length(str).

string

parse_url(string urlString, string partToExtract [, string keyToExtract])

Returns the specified part from the URL. Valid values for partToExtract include HOST, PATH, QUERY, REF, PROTOCOL, AUTHORITY, FILE, and USERINFO. For example, parse_url('http://facebook.com/path1/p.php?k1=v1&k2=v2#Ref1', 'HOST') returns 'facebook.com'. Also, a value of a particular key in QUERY can be extracted by providing the key as the third argument, for example, parse_url('http://facebook.com/path1/p.php?k1=v1&k2=v2#Ref1', 'QUERY', 'k1') returns 'v1'.

string

printf(String format, Obj... args)

Returns the input formatted according to printf-style format strings.

stringquote(String text)

Returns the quoted string 

InputOutput
NULLNULL
DONT'DONT'
DON'T'DON\'T'

Status
colourGreen
titleNew
Includes escape character for any single quotes in Apache Hive 4.0.0

string

regexp_extract(string subject, string pattern, int index)

Returns the string extracted using the pattern. For example, regexp_extract('foothebar', 'foo(.*?)(bar)', 2) returns 'bar.' Note that some care is necessary in using predefined character classes: using '\s' as the second argument will match the letter s; '\\s' is necessary to match whitespace, etc. The 'index' parameter is the Java regex Matcher group() method index. 

string

regexp_replace(string INITIAL_STRING, string PATTERN, string REPLACEMENT)

Returns the string resulting from replacing all substrings in INITIAL_STRING that match the java regular expression syntax defined in PATTERN with instances of REPLACEMENT. For example, regexp_replace("foobar", "oo|ar", "") returns 'fb.' Note that some care is necessary in using predefined character classes: using '\s' as the second argument will match the letter s; '\\s' is necessary to match whitespace, etc.

string

repeat(string str, int n)

Repeats str n times.

stringreplace(string A, string OLD, string NEW)Returns the string A with all non-overlapping occurrences of OLD replaced with NEW. Example: select replace("ababab", "abab", "Z"); returns "Zab".

string

reverse(string A)

Returns the reversed string.

string

rpad(string str, int len, string pad)

Returns str, right-padded with pad to a length of len. If str is longer than len, the return value is shortened to len characters. In case of empty pad string, the return value is null.

string

rtrim(string A)

Returns the string resulting from trimming spaces from the end(right hand side) of A. For example, rtrim(' foobar ') results in ' foobar'.

array<array<string>>

sentences(string str, string lang, string locale)

Tokenizes a string of natural language text into words and sentences, where each sentence is broken at the appropriate sentence boundary and returned as an array of words. The 'lang' and 'locale' are optional arguments. For example, sentences('Hello there! How are you?') returns ( ("Hello", "there"), ("How", "are", "you") ).

string

space(int n)

Returns a string of n spaces.

array

split(string str, string pat)

Splits str around pat (pat is a regular expression).

map<string,string>

str_to_map(text[, delimiter1, delimiter2])

Splits text into key-value pairs using two delimiters. Delimiter1 separates text into K-V pairs, and Delimiter2 splits each K-V pair. Default delimiters are ',' for delimiter1 and ':' for delimiter2.

string

substr(string|binary A, int start) substring(string|binary A, int start)

Returns the substring or slice of the byte array of A starting from start position till the end of string A. For example, substr('foobar', 4) results in 'bar'.

string

substr(string|binary A, int start, int len) substring(string|binary A, int start, int len)

Returns the substring or slice of the byte array of A starting from start position with length len. For example, substr('foobar', 4, 1) results in 'b'.

stringsubstring_index(string A, string delim, int count)Returns the substring from string A before count occurrences of the delimiter delim. If count is positive, everything to the left of the final delimiter (counting from the left) is returned. If count is negative, everything to the right of the final delimiter (counting from the right) is returned. Substring_index performs a case-sensitive match when searching for delim. Example: substring_index('www.apache.org', '.', 2) = 'www.apache'.

string

translate(string|char|varchar input, string|char|varchar from, string|char|varchar to)

Translates the input string by replacing the characters present in the from string with the corresponding characters in the to string. This is similar to the translate function in PostgreSQL. If any of the parameters to this UDF are NULL, the result is NULL as well. (Available as of Hive 0.10.0, for string types)

string

trim(string A)

Returns the string resulting from trimming spaces from both ends of A. For example, trim(' foobar ') results in 'foobar'

binary

unbase64(string str)

Converts the argument from a base 64 string to BINARY.

string

upper(string A) ucase(string A)

Returns the string resulting from converting all characters of A to upper case. For example, upper('fOoBaR') results in 'FOOBAR'.

stringinitcap(string A)Returns string, with the first letter of each word in uppercase, all other letters in lowercase. Words are delimited by whitespace.
intlevenshtein(string A, string B)Returns the Levenshtein distance between two strings. Example: levenshtein('kitten', 'sitting') results in 3.
stringsoundex(string A)Returns the soundex code of the string. Example: soundex('Miller') results in M460.

Date Functions

In many analytical workloads Date is one of the most used built-in functions in Hive. The following list contains the supported built-in date functions in Hive.

Return Type

Name(Signature)

Description

string

from_unixtime(bigint unixtime[, string pattern])

Converts a number of seconds since epoch (1970-01-01 00:00:00 UTC) to a string representing the timestamp of that moment in the current time zone(using config "hive.local.time.zone") using the specified pattern. If the pattern is missing the default is used ('uuuu-MM-dd HH:mm:ss' or yyyy-MM-dd HH:mm:ss'). Example: from_unixtime(0)=1970-01-01 00:00:00 (hive.local.time.zone=Etc/GMT

Date Functions

In many analytical workloads Date is one of the most used built-in functions in Hive. The following list contains the supported built-in date functions in Hive.

Return Type

Name(Signature)

Description

string

from_unixtime(bigint unixtime[, string pattern])

Converts a number of seconds since epoch (1970-01-01 00:00:00 UTC) to a string representing the timestamp of that moment in the current time zone(using config "hive.local.time.zone") using the specified pattern. If the pattern is missing the default is used ('uuuu-MM-dd HH:mm:ss' or yyyy-MM-dd HH:mm:ss'). Example: from_unixtime(0)=1970-01-01 00:00:00 (hive.local.time.zone=Etc/GMT)

Status
colourGreen
titleNew

As of Hive 4.0.0 the "hive.datetime.formatter" property can be used to control the underlying formatter implementation and as a consequence the accepted patterns and their behavior.  Earlier versions used https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html as the underlying formatter.

bigint

unix_timestamp()

Gets the current Unix timestamp in seconds. This function is not deterministic and its value is not fixed for the scope of a query execution, therefore prevents proper optimization of queries - this has been deprecated since 2.0 in favour of CURRENT_TIMESTAMP constant.

bigint

unix_timestamp(string date)

Converts a DateTime string to unix time (seconds since epoch) using the default pattern(s). The default accepted patterns depend on the underlying formatter implementation. The datetime string does not contain a timezone so the conversion uses the local time zone as specified by "hive.local.time.zone" property. Returns null when the conversion fails. Example: unix_timestamp('2009-03-20 11:30:01') = 1237573801

Status
colourGreen
titleNew

As of Hive 4.0.0 the "hive.datetime.formatter" property can be used to control the underlying formatter implementation and as a consequence the accepted patterns and their behavior. Earlier versions used https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html as the underlying formatter.

bigint

unix_timestamp(string date, string pattern)

Converts a datetime string to unix time (seconds since epoch) using the specified pattern. The accepted patterns and their behavior depend on the underlying formatter implementation. Returns null when the conversion fails. Example: unix_timestamp('2009-03-20', 'uuuu-MM-dd') = 1237532400

Status
colourGreen
titleNew

As of Hive 4.0.0 the "hive.datetime.formatter" property can be used to control the underlying formatter implementation, and as a consequence the accepted patterns and their behavior.  Earlier versions used https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html as the underlying formatter.

date

to_date(string timestamp)

Returns the date part of a timestamp date object. Example: to_date("1970-01-01 00:00:00") 

int

year(string date)

Returns the year part of a date or a timestamp string: year("1970-01-01 00:00:00") = 1970, year("1970-01-01") = 1970.

int

quarter(date/timestamp/string)Returns the quarter of the year for a date, timestamp, or string in the range 1 to 4. Example: quarter('2015-04-08') = 2.

int

month(string date)

Returns the month part of a date or a timestamp string. Example: month("1970-11-01 00:00:00") = 11, month("1970-11-01") = 11.

int

day(string date) dayofmonth(date)

Returns the day part of a date or a timestamp string. Example: day("1970-11-01 00:00:00") = 1, day("1970-11-01") = 1.

int

hour(string date)

Returns the hour of the timestamp: Example: hour('2009-07-30 12:58:59') = 12, hour('12:58:59') = 12.

int

minute(string date)

Returns the minute of the timestamp.

int

second(string date)

Returns the second of the timestamp.

int

weekofyear(string date)

Returns the week number of a timestamp string. Example: weekofyear("1970-11-01 00:00:00") = 44 or weekofyear("1970-11-01") = 44.

int

extract(field FROM source)

Retrieve fields such as days or hours from the source. The source must be a date, timestamp, interval, or string that can be converted into either a date or timestamp. Supported fields include: day, dayofweek, hour, minute, month, quarter, second, week and year.

Examples:

  1. select extract(month from "2016-10-20") results in 10.

  2. select extract(hour from "2016-10-20 05:06:07") results in 5.

  3. select extract(dayofweek from "2016-10-20 05:06:07") results in 5.

  4. select extract(month from interval '1-3' year to month) results in 3.

  5. select extract(minute from interval '3 12:20:30' day to second) results in 20.

int

datediff(string enddate, string startdate)

Returns the number of days from startdate to end date. Example: datediff('2009-03-01', '2009-02-27') = 2.

date

date_add(date/timestamp/string startdate, tinyint/smallint/int days)

Adds a number of days to startdate. Example: date_add('2008-12-31', 1) = '2009-01-01'.

date

date_sub(date/timestamp/string startdate, tinyint/smallint/int days)

Subtracts a number of days to startdate: date_sub('2008-12-31', 1) = '2008-12-30'.

timestamp

from_utc_timestamp({any primitive type} ts, string timezone)

Converts a timestamp* in UTC to a given timezone.

* timestamp is a primitive type, including timestamp/date, tinyint/smallint/int/bigint, float/double and decimal.

Fractional values are considered as seconds. Integer values are considered as milliseconds. For example, from_utc_timestamp(2592000.0,'PST'), from_utc_timestamp(2592000000,'PST') and from_utc_timestamp(timestamp '1970-01-30 16:00:00','PST') all return the timestamp 1970-01-30 08:00:00.

timestamp

to_utc_timestamp({any primitive type} ts, string timezone)

Converts a timestamp* in a given timezone to UTC.

* timestamp is a primitive type, including timestamp/date, tinyint/smallint/int/bigint, float/double and decimal.

Fractional values are considered as seconds. Integer values are considered as milliseconds. For example, to_utc_timestamp(2592000.0,'PST'), to_utc_timestamp(2592000000,'PST') and to_utc_timestamp(timestamp '1970-01-30 16:00:00','PST') all return the timestamp 1970-01-31 00:00:00.

datecurrent_date

Returns the current date at the start of query evaluation. All calls of current_date within the same query return the same value.

timestampcurrent_timestamp

Returns the current timestamp at the start of query evaluation. All calls of current_timestamp within the same query return the same value.

stringadd_months(string start_date, int num_months, output_date_format)

Returns the date that is num_months after start_date. start_date is a string, date or timestamp. num_months is an integer. If start_date is the last day of the month or if the resulting month has fewer days than the day component of start_date, then the result is the last day of the resulting month. Otherwise, the result has the same day component as start_date. The default output format is 'yyyy-MM-dd'.

Status
colourGreen
titleNew

Before Hive 4.0.0, the time part of the date is ignored. As of Hive 4.0.0, add_months supports an optional argument output_date_format, which accepts a String that represents a valid date format for the output. This allows to retain the time format in the output.

For example :

add_months('2009-08-31', 1) returns '2009-09-30'.
add_months('2017-12-31 14:15:16', 2, 'YYYY-MM-dd HH:mm:ss') returns '2018-02-28 14:15:16'.

stringlast_day(string date)Returns the last day of the month to which the date belongs. date is a string in the format 'yyyy-MM-dd HH:mm:ss' or 'yyyy-MM-dd'. The time part of the date is ignored!stringnext_day(string start_date, string day_of_week)Returns the first date which is later than start_date and named as day_of_week.  start_date  is a string/date/timestamp. day_of_week is 2 letters, 3 letters or full name of the day of the week (e.g. Mo, tue, FRIDAY). The time part of start_date is ignored. Example: next_day('2015-01-14', 'TU') = 2015-01-20.stringtrunc(string date, string format)Returns date truncated to the unit specified by the format. Supported formats: MONTH/MON/MM, YEAR/YYYY/YY. Example: trunc('2015-03-17', 'MM') = 2015-03-01.doublemonths_between(date1, date2)Returns the number of months between dates date1 and date2. If date1 is later than date2, then the result is positive. If date1 is earlier than date , then the result is negative. If date1 and date2 are either the same days of the month or both last days of months, then the result is always an integer. Otherwise, the UDF calculates the fractional portion of the result based on a 31-day month and considers the difference in time components date1 and date2. date1 and date2 type can be date, timestamp or string in the format 'yyyy-MM-dd' or 'yyyy-MM-dd HH:mm:ss'. The result is rounded to 8 decimal places. Example: months_between('1997-02-28 10:30:00', '1996-10-30') = 3.94959677stringdate_format(date/timestamp/string ts, string pattern)

Converts a date/timestamp/string to a value of string using the specified pattern. The accepted patterns and their behavior depend on the underlying formatter implementation. The pattern argument should be constant. Example: date_format('2015-04-08', 'y') = '2015'.

date_format can be used to implement other UDFs, e.g.:

  • dayname(date) is date_format(date, 'EEEE')
  • dayofyear(date) is date_format(date, 'D'

    )

    Status
    colourGreen
    titleNew

    As of Hive 4.0.0 the "hive.datetime.formatter" property can be used to control the underlying formatter implementation and as a consequence the accepted patterns and their behavior.  Earlier versions used https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html as the underlying formatter.

    String Functions

    There is no good engine without a string manipulation functions. Apache Hive has rich built-in string functions. 

    ...

    Return Type

    ...

    Name(Signature)

    ...

    Description

    ...

    int

    ...

    ascii(string str)

    ...

    Returns the numeric value of the first character of str.

    ...

    string

    ...

    base64(binary bin)

    ...

    Converts the argument from binary to a base64 string.

    ...

    string

    ...

    concat(string|binary A, string|binary B...)

    ...

    Returns the string or bytes resulting from concatenating the strings or bytes passed in as parameters in order. For example, concat('foo', 'bar') results in 'foobar'. Note that this function can take any number of input strings.

    ...

    array<struct<string,double>>

    ...

    context_ngrams(array<array<string>>, array<string>, int K, int pf)

    ...

    Returns the top-k contextual N-grams from a set of tokenized sentences, given a string of "context". See StatisticsAndDataMining for more information.

    ...

    string

    ...

    concat_ws(string SEP, string A, string B...)

    ...

    Like concat() above, but with custom separator SEP.

    ...

    string

    ...

    concat_ws(string SEP, array<string>)

    ...

    Like concat_ws() above, but taking an array of strings.

    ...

    string

    ...

    decode(binary bin, string charset)

    ...

    Decodes the first argument into a String using the provided character set (one of 'US-ASCII', 'ISO-8859-1', 'UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16'). If either argument is null, the result will also be null.

    ...

    Return string at index number. For example elt(2,'hello','world') returns 'world'. Returns NULL if N is less than 1 or greater than the number of arguments.

    ...

    binary

    ...

    encode(string src, string charset)

    ...

    Encodes the first argument into a BINARY using the provided character set (one of 'US-ASCII', 'ISO-8859-1', 'UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16'). If either argument is null, the result will also be null. 

    ...

    Returns the index of val in the val1,val2,val3,... list or 0 if not found. For example field('world','say','hello','world') returns 3.
    All primitive types are supported, arguments are compared using str.equals(x). If val is NULL, the return value is 0.

    ...

    int

    ...

    find_in_set(string str, string strList)

    ...

    Returns the first occurance of str in strList where strList is a comma-delimited string. Returns null if either argument is null. Returns 0 if the first argument contains any commas. For example, find_in_set('ab', 'abc,b,ab,c,def') returns 3.

    ...

    string

    ...

    format_number(number x, int d)

    ...

    Formats the number X to a format like '#,###,###.##', rounded to D decimal places, and returns the result as a string. If D is 0, the result has no decimal point or fractional part.

    ...

    string

    ...

    get_json_object(string json_string, string path)

    Extracts json object from a json string based on json path specified, and returns json string of the extracted json object. It will return null if the input json string is invalid.

    Note
    titleNote

    The json path can only have the characters [0-9a-z_], i.e., no upper-case or special characters. Also, the keys *cannot start with numbers.* This is due to restrictions on Hive column names.

    ...

    boolean

    ...

    in_file(string str, string filename)

    ...

    Returns true if the string str appears as an entire line in filename.

    ...

    int

    ...

    instr(string str, string substr)

    ...

    Returns the position of the first occurrence of substr in str. Returns null if either of the arguments are null and returns 0 if substr could not be found in str. Be aware that this is not zero-based. The first character in str has index 1.

    ...

    int

    ...

    length(string A)

    ...

    Returns the length of the string.

    ...

    int

    ...

    locate(string substr, string str[, int pos])

    ...

    Returns the position of the first occurrence of substr in str after position pos.

    ...

    string

    ...

    lower(string A) lcase(string A)

    ...

    Returns the string resulting from converting all characters of B to lower case. For example, lower('fOoBaR') results in 'foobar'.

    ...

    string

    ...

    lpad(string str, int len, string pad)

    ...

    Returns str, left-padded with pad to a length of len. If str is longer than len, the return value is shortened to len characters. In case of empty pad string, the return value is null.

    ...

    string

    ...

    ltrim(string A)

    ...

    Returns the string resulting from trimming spaces from the beginning(left hand side) of A. For example, ltrim(' foobar ') results in 'foobar '.

    ...

    array<struct<string,double>>

    ...

    ngrams(array<array<string>>, int N, int K, int pf)

    ...

    Returns the top-k N-grams from a set of tokenized sentences, such as those returned by the sentences() UDAF. See StatisticsAndDataMining for more information.

    ...

    string

    ...

    parse_url(string urlString, string partToExtract [, string keyToExtract])

    ...

    Returns the specified part from the URL. Valid values for partToExtract include HOST, PATH, QUERY, REF, PROTOCOL, AUTHORITY, FILE, and USERINFO. For example, parse_url('http://facebook.com/path1/p.php?k1=v1&k2=v2#Ref1', 'HOST') returns 'facebook.com'. Also, a value of a particular key in QUERY can be extracted by providing the key as the third argument, for example, parse_url('http://facebook.com/path1/p.php?k1=v1&k2=v2#Ref1', 'QUERY', 'k1') returns 'v1'.

    ...

    string

    ...

    printf(String format, Obj... args)

    ...

    Returns the input formatted according to printf-style format strings.

    ...

    Returns the quoted string 

    InputOutput
    NULLNULL
    DONT'DONT'
    DON'T'DON\'T'

    Status
    colourGreen
    titleNew
    Includes escape character for any single quotes in Apache Hive 4.0.0

    ...

    string

    ...

    regexp_extract(string subject, string pattern, int index)

    ...

    Returns the string extracted using the pattern. For example, regexp_extract('foothebar', 'foo(.*?)(bar)', 2) returns 'bar.' Note that some care is necessary in using predefined character classes: using '\s' as the second argument will match the letter s; '\\s' is necessary to match whitespace, etc. The 'index' parameter is the Java regex Matcher group() method index. 

    ...

    string

    ...

    regexp_replace(string INITIAL_STRING, string PATTERN, string REPLACEMENT)

    ...

    Returns the string resulting from replacing all substrings in INITIAL_STRING that match the java regular expression syntax defined in PATTERN with instances of REPLACEMENT. For example, regexp_replace("foobar", "oo|ar", "") returns 'fb.' Note that some care is necessary in using predefined character classes: using '\s' as the second argument will match the letter s; '\\s' is necessary to match whitespace, etc.

    ...

    string

    ...

    repeat(string str, int n)

    ...

    Repeats str n times.

    ...

    string

    ...

    reverse(string A)

    ...

    Returns the reversed string.

    ...

    string

    ...

    rpad(string str, int len, string pad)

    ...

    Returns str, right-padded with pad to a length of len. If str is longer than len, the return value is shortened to len characters. In case of empty pad string, the return value is null.

    ...

    string

    ...

    rtrim(string A)

    ...

    Returns the string resulting from trimming spaces from the end(right hand side) of A. For example, rtrim(' foobar ') results in ' foobar'.

    ...

    array<array<string>>

    ...

    sentences(string str, string lang, string locale)

    ...

    Tokenizes a string of natural language text into words and sentences, where each sentence is broken at the appropriate sentence boundary and returned as an array of words. The 'lang' and 'locale' are optional arguments. For example, sentences('Hello there! How are you?') returns ( ("Hello", "there"), ("How", "are", "you") ).

    ...

    string

    ...

    space(int n)

    ...

    Returns a string of n spaces.

    ...

    array

    ...

    split(string str, string pat)

    ...

    Splits str around pat (pat is a regular expression).

    ...

    map<string,string>

    ...

    str_to_map(text[, delimiter1, delimiter2])

    ...

    Splits text into key-value pairs using two delimiters. Delimiter1 separates text into K-V pairs, and Delimiter2 splits each K-V pair. Default delimiters are ',' for delimiter1 and ':' for delimiter2.

    ...

    string

    ...

    substr(string|binary A, int start) substring(string|binary A, int start)

    ...

    Returns the substring or slice of the byte array of A starting from start position till the end of string A. For example, substr('foobar', 4) results in 'bar'.

    ...

    string

    ...

    substr(string|binary A, int start, int len) substring(string|binary A, int start, int len)

    ...

    Returns the substring or slice of the byte array of A starting from start position with length len. For example, substr('foobar', 4, 1) results in 'b'.

    ...

    string

    ...

    translate(string|char|varchar input, string|char|varchar from, string|char|varchar to)

    ...

    Translates the input string by replacing the characters present in the from string with the corresponding characters in the to string. This is similar to the translate function in PostgreSQL. If any of the parameters to this UDF are NULL, the result is NULL as well. (Available as of Hive 0.10.0, for string types)

    ...

    string

    ...

    trim(string A)

    ...

    Returns the string resulting from trimming spaces from both ends of A. For example, trim(' foobar ') results in 'foobar'

    ...

    binary

    ...

    unbase64(string str)

    ...

    Converts the argument from a base 64 string to BINARY.

    ...

    string

    ...

    upper(string A) ucase(string A)

    ...

    Returns the string resulting from converting all characters of A to upper case. For example, upper('fOoBaR') results in 'FOOBAR'.

    ...

    Type Conversion Functions

    The following built-in type conversion functions are supported in Hive. 

    ...

    Return Type

    ...

    Name(Signature)

    ...

    Description

    ...

    binary

    ...

    binary(string|binary)

    ...

    Casts the parameter into a binary.

    ...

    Expected "=" to follow "type"

    ...

    cast(expr as <type>)

    ...

    Converts the results of the expression expr to <type>. For example, cast('1' as BIGINT) will convert the string '1' to its integral representation. A null is returned if the conversion does not succeed. If cast(expr as boolean) Hive returns true for a non-empty string.

    bigint

    unix_timestamp()

    Gets the current Unix timestamp in seconds. This function is not deterministic and its value is not fixed for the scope of a query execution, therefore prevents proper optimization of queries - this has been deprecated since 2.0 in favour of CURRENT_TIMESTAMP constant.

    bigint

    unix_timestamp(string date)

    Converts a DateTime string to unix time (seconds since epoch) using the default pattern(s). The default accepted patterns depend on the underlying formatter implementation. The datetime string does not contain a timezone so the conversion uses the local time zone as specified by "hive.local.time.zone" property. Returns null when the conversion fails. Example: unix_timestamp('2009-03-20 11:30:01') = 1237573801

    Status
    colourGreen
    titleNew

    As of Hive 4.0.0 the "hive.datetime.formatter" property can be used to control the underlying formatter implementation and as a consequence the accepted patterns and their behavior. Earlier versions used https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html as the underlying formatter.

    bigint

    unix_timestamp(string date, string pattern)

    Converts a datetime string to unix time (seconds since epoch) using the specified pattern. The accepted patterns and their behavior depend on the underlying formatter implementation. Returns null when the conversion fails. Example: unix_timestamp('2009-03-20', 'uuuu-MM-dd') = 1237532400

    Status
    colourGreen
    titleNew

    As of Hive 4.0.0 the "hive.datetime.formatter" property can be used to control the underlying formatter implementation, and as a consequence the accepted patterns and their behavior.  Earlier versions used https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html as the underlying formatter.

    date

    to_date(string timestamp)

    Returns the date part of a timestamp date object. Example: to_date("1970-01-01 00:00:00") 

    int

    year(string date)

    Returns the year part of a date or a timestamp string: year("1970-01-01 00:00:00") = 1970, year("1970-01-01") = 1970.

    int

    quarter(date/timestamp/string)Returns the quarter of the year for a date, timestamp, or string in the range 1 to 4. Example: quarter('2015-04-08') = 2.

    int

    month(string date)

    Returns the month part of a date or a timestamp string. Example: month("1970-11-01 00:00:00") = 11, month("1970-11-01") = 11.

    int

    day(string date) dayofmonth(date)

    Returns the day part of a date or a timestamp string. Example: day("1970-11-01 00:00:00") = 1, day("1970-11-01") = 1.

    int

    hour(string date)

    Returns the hour of the timestamp: Example: hour('2009-07-30 12:58:59') = 12, hour('12:58:59') = 12.

    int

    minute(string date)

    Returns the minute of the timestamp.

    int

    second(string date)

    Returns the second of the timestamp.

    int

    weekofyear(string date)

    Returns the week number of a timestamp string. Example: weekofyear("1970-11-01 00:00:00") = 44 or weekofyear("1970-11-01") = 44.

    int

    extract(field FROM source)

    Retrieve fields such as days or hours from the source. The source must be a date, timestamp, interval, or string that can be converted into either a date or timestamp. Supported fields include: day, dayofweek, hour, minute, month, quarter, second, week and year.

    Examples:

    1. select extract(month from "2016-10-20") results in 10.

    2. select extract(hour from "2016-10-20 05:06:07") results in 5.

    3. select extract(dayofweek from "2016-10-20 05:06:07") results in 5.

    4. select extract(month from interval '1-3' year to month) results in 3.

    5. select extract(minute from interval '3 12:20:30' day to second) results in 20.

    int

    datediff(string enddate, string startdate)

    Returns the number of days from startdate to end date. Example: datediff('2009-03-01', '2009-02-27') = 2.

    date

    date_add(date/timestamp/string startdate, tinyint/smallint/int days)

    Adds a number of days to startdate. Example: date_add('2008-12-31', 1) = '2009-01-01'.

    date

    date_sub(date/timestamp/string startdate, tinyint/smallint/int days)

    Subtracts a number of days to startdate: date_sub('2008-12-31', 1) = '2008-12-30'.

    timestamp

    from_utc_timestamp({any primitive type} ts, string timezone)

    Converts a timestamp* in UTC to a given timezone.

    * timestamp is a primitive type, including timestamp/date, tinyint/smallint/int/bigint, float/double and decimal.

    Fractional values are considered as seconds. Integer values are considered as milliseconds. For example, from_utc_timestamp(2592000.0,'PST'), from_utc_timestamp(2592000000,'PST') and from_utc_timestamp(timestamp '1970-01-30 16:00:00','PST') all return the timestamp 1970-01-30 08:00:00.

    timestamp

    to_utc_timestamp({any primitive type} ts, string timezone)

    Converts a timestamp* in a given timezone to UTC.

    * timestamp is a primitive type, including timestamp/date, tinyint/smallint/int/bigint, float/double and decimal.

    Fractional values are considered as seconds. Integer values are considered as milliseconds. For example, to_utc_timestamp(2592000.0,'PST'), to_utc_timestamp(2592000000,'PST') and to_utc_timestamp(timestamp '1970-01-30 16:00:00','PST') all return the timestamp 1970-01-31 00:00:00.

    datecurrent_date

    Returns the current date at the start of query evaluation. All calls of current_date within the same query return the same value.

    timestampcurrent_timestamp

    Returns the current timestamp at the start of query evaluation. All calls of current_timestamp within the same query return the same value.

    stringadd_months(string start_date, int num_months, output_date_format)

    Returns the date that is num_months after start_date. start_date is a string, date or timestamp. num_months is an integer. If start_date is the last day of the month or if the resulting month has fewer days than the day component of start_date, then the result is the last day of the resulting month. Otherwise, the result has the same day component as start_date. The default output format is 'yyyy-MM-dd'.

    Status
    colourGreen
    titleNew

    Before Hive 4.0.0, the time part of the date is ignored. As of Hive 4.0.0, add_months supports an optional argument output_date_format, which accepts a String that represents a valid date format for the output. This allows to retain the time format in the output.

    For example :

    add_months('2009-08-31', 1) returns '2009-09-30'.
    add_months('2017-12-31 14:15:16', 2, 'YYYY-MM-dd HH:mm:ss') returns '2018-02-28 14:15:16'.

    stringlast_day(string date)Returns the last day of the month to which the date belongs. date is a string in the format 'yyyy-MM-dd HH:mm:ss' or 'yyyy-MM-dd'. The time part of the date is ignored!
    stringnext_day(string start_date, string day_of_week)Returns the first date which is later than start_date and named as day_of_week.  start_date  is a string/date/timestamp. day_of_week is 2 letters, 3 letters or full name of the day of the week (e.g. Mo, tue, FRIDAY). The time part of start_date is ignored. Example: next_day('2015-01-14', 'TU') = 2015-01-20.
    stringtrunc(string date, string format)Returns date truncated to the unit specified by the format. Supported formats: MONTH/MON/MM, YEAR/YYYY/YY. Example: trunc('2015-03-17', 'MM') = 2015-03-01.
    doublemonths_between(date1, date2)Returns the number of months between dates date1 and date2. If date1 is later than date2, then the result is positive. If date1 is earlier than date , then the result is negative. If date1 and date2 are either the same days of the month or both last days of months, then the result is always an integer. Otherwise, the UDF calculates the fractional portion of the result based on a 31-day month and considers the difference in time components date1 and date2. date1 and date2 type can be date, timestamp or string in the format 'yyyy-MM-dd' or 'yyyy-MM-dd HH:mm:ss'. The result is rounded to 8 decimal places. Example: months_between('1997-02-28 10:30:00', '1996-10-30') = 3.94959677
    stringdate_format(date/timestamp/string ts, string pattern)

    Converts a date/timestamp/string to a value of string using the specified pattern. The accepted patterns and their behavior depend on the underlying formatter implementation. The pattern argument should be constant. Example: date_format('2015-04-08', 'y') = '2015'.

    date_format can be used to implement other UDFs, e.g.:

    • dayname(date) is date_format(date, 'EEEE')
    • dayofyear(date) is date_format(date, 'D')

    Status
    colourGreen
    titleNew

    As of Hive 4.0.0 the "hive.datetime.formatter" property can be used to control the underlying formatter implementation and as a consequence the accepted patterns and their behavior.  Earlier versions used https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html as the underlying formatter.

    Mathematical Functions

    The following built-in mathematical functions are supported in Hive. 

    Return Type

    Name (Signature)

    Description

    double

    round(DOUBLE a)

    Returns the rounded BIGINT value of a.

    double

    round(DOUBLE a, INT d)

    Returns a rounded to d decimal places.

    doublebround(DOUBLE a)Returns the rounded BIGINT value of a using HALF_EVEN rounding mode. Also known as Gaussian rounding or bankers' rounding. Example: bround(2.5) = 2, bround(3.5) = 4.
    doublebround(DOUBLE a, INT d)Returns a rounded to d decimal places using HALF_EVEN rounding mode.  Example: bround(8.25, 1) = 8.2, bround(8.35, 1) = 8.4.

    bigint

    floor(DOUBLE a)

    Returns the maximum BIGINT value that is equal to or less than a.

    bigint

    ceil(DOUBLE a), ceiling(DOUBLE a)

    Returns the minimum BIGINT value that is equal to or greater than a.

    double

    rand(), rand(INT seed)

    Returns a random number (that changes from row to row) that is distributed uniformly from 0 to 1. Specifying the seed will make sure the generated random number sequence is deterministic.

    double

    exp(DOUBLE a), exp(DECIMAL a)

    Returns ea where e is the base of the natural logarithm.

    double

    ln(DOUBLE a), ln(DECIMAL a)

    Returns the natural logarithm of the argument a.

    double

    log10(DOUBLE a), log10(DECIMAL a)

    Returns the base-10 logarithm of the argument a.

    double

    log2(DOUBLE a), log2(DECIMAL a)

    Returns the base-2 logarithm of the argument a

    double

    log(DOUBLE base, DOUBLE a)

    log(DECIMAL base, DECIMAL a)

    Returns the base-base logarithm of the argument a.

    double

    pow(DOUBLE a, DOUBLE p), power(DOUBLE a, DOUBLE p)

    Returns ap.

    double

    sqrt(DOUBLE a), sqrt(DECIMAL a)

    Returns the square root of a.

    string

    bin(BIGINT a)

    Returns the number in binary format.

    string

    hex(BIGINT a) hex(STRING a) hex(BINARY a)

    If the argument is an INT or binary, hex returns the number as a STRING in hexadecimal format. Otherwise if the number is a STRING, it converts each character into its hexadecimal representation and returns the resulting STRING

    binary

    unhex(STRING a)

    Inverse of hex. Interprets each pair of characters as a hexadecimal number and converts to the byte representation of the number.

    string

    conv(BIGINT num, INT from_base, INT to_base), conv(STRING num, INT from_base, INT to_base)

    Converts a number from a given base to another.

    double

    abs(DOUBLE a)

    Returns the absolute value.

    int or double

    pmod(INT a, INT b), pmod(DOUBLE a, DOUBLE b)

    Returns the positive value of a mod b.

    double

    sin(DOUBLE a), sin(DECIMAL a)

    Returns the sine of a (a is in radians).

    double

    asin(DOUBLE a), asin(DECIMAL a)

    Returns the arc sin of a if -1<=a<=1 or NULL otherwise

    double

    cos(DOUBLE a), cos(DECIMAL a)

    Returns the cosine of a (a is in radians)

    double

    acos(DOUBLE a), acos(DECIMAL a)

    Returns the arccosine of a if -1<=a<=1 or NULL otherwise.

    double

    tan(DOUBLE a), tan(DECIMAL a)

    Returns the tangent of a (a is in radians).

    double

    atan(DOUBLE a), atan(DECIMAL a)

    Returns the arctangent of a.

    double

    degrees(DOUBLE a), degrees(DECIMAL a)

    Converts value of a from radians to degrees

    double

    radians(DOUBLE a), radians(DOUBLE a)

    Converts value of a from degrees to radians

    int or double

    positive(INT a), positive(DOUBLE a)

    Returns a.

    int or double

    negative(INT a), negative(DOUBLE a)

    Returns -a.

    double or int

    sign(DOUBLE a), sign(DECIMAL a)

    Returns the sign of a as '1.0' (if a is positive) or '-1.0' (if a is negative), '0.0' otherwise. The decimal version returns INT instead of DOUBLE. 

    double

    e()

    Returns the value of e.

    double

    pi()

    Returns the value of pi.

    bigintfactorial(INT a)Returns the factorial of a Valid a is [0..20].
    doublecbrt(DOUBLE a)Returns the cube root of a double value.

    int

    bigint

    shiftleft(TINYINT|SMALLINT|INT a, INT b)

    shiftleft(BIGINT a, INT b)

    Bitwise left shift. Shifts a b positions to the left.

    Returns int for tinyint, smallint and int a. Returns bigint for bigint a.

    int

    bigint

    shiftright(TINYINT|SMALLINT|INT a, INT b)

    shiftright(BIGINT a, INT b)

    Bitwise right shift. Shifts a b positions to the right.

    Returns int for tinyint, smallint and int a. Returns bigint for bigint a.

    int

    bigint

    shiftrightunsigned(TINYINT|SMALLINT|INT a, INT b),

    shiftrightunsigned(BIGINT a, INT b)

    Bitwise unsigned right shift. Shifts a b positions to the right.

    Returns int for tinyint, smallint and int a. Returns bigint for bigint a.

    Tgreatest(T v1, T v2, ...)Returns the greatest value of the list of values. Fixed to return NULL when one or more arguments are NULL, and strict type restriction relaxed, consistent with ">" operator.
    Tleast(T v1, T v2, ...)Returns the least value of the list of values. Fixed to return NULL when one or more arguments are NULL, and strict type restriction relaxed, consistent with "<" operator.
    intwidth_bucket(NUMERIC expr, NUMERIC min_value, NUMERIC max_value, INT num_buckets)

    Returns an integer between 0 and num_buckets+1 by mapping expr into the ith equally sized bucket. Buckets are made by dividing [min_value, max_value] into equally sized regions. If expr < min_value, return 1, if expr > max_value return num_buckets+1. See https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions214.htm


    Collection Functions

    The following built-in collection functions are supported in Hive. 

    Return Type

    Name(Signature)

    Description

    int

    size(Map<K.V>)

    Returns the number of elements in the map type.

    int

    size(Array<T>)

    Returns the number of elements in the array type.

    array<K>

    map_keys(Map<K.V>)

    Returns an unordered array containing the keys of the input map.

    array<V>

    map_values(Map<K.V>)

    Returns an unordered array containing the values of the input map.

    boolean

    array_contains(Array<T>, value)

    Returns TRUE if the array contains the provided paramter value.

    array<t>

    sort_array(Array<T>)

    Sorts the input array in ascending order according to the natural ordering of the array elements and returns it.



    Type Conversion Functions

    The following built-in type conversion functions are supported in Hive. 

    Return Type

    Name(Signature)

    Description

    binary

    binary(string|binary)

    Casts the parameter into a binary.

    Expected "=" to follow "type"

    cast(expr as <type>)

    Converts the results of the expression expr to <type>. For example, cast('1' as BIGINT) will convert the string '1' to its integral representation. A null is returned if the conversion does not succeed. If cast(expr as boolean) Hive returns true for a non-empty string.

    Conditional Functions

    The following built-in conditional functions are supported in Hive.

    Return Type

    Name(Signature)

    Description

    T

    if(boolean testCondition, T valueTrue, T valueFalseOrNull)

    Returns valueTrue when testCondition is true, returns valueFalseOrNull otherwise.

    booleanisnull( a )Returns true if a is NULL and false otherwise.
    booleanisnotnull ( a )Returns true if a is not NULL and false otherwise.
    Tnvl(T value, T default_value)Returns default value if value is null else returns value.

    T

    COALESCE(T v1, T v2, ...)

    Returns the first v that is not NULL, or NULL if all v's are NULL.

    T

    CASE a WHEN b THEN c [WHEN d THEN e]* [ELSE f] END

    When a = b, returns c; when a = d, returns e; else returns f.

    T

    CASE WHEN a THEN b [WHEN c THEN d]* [ELSE e] END

    When a = true, returns b; when c = true, returns d; else returns e.

    Tnullif( a, b )

    Returns NULL if a=b; otherwise returns a.

    Tip
    titleShorthand for

    CASE WHEN a = b then NULL else a


    voidassert_true(boolean condition)Throw an exception if 'condition' is not true, otherwise return null. For example, select assert_true (2<1).


    Data Masking Functions


    Misc. Functions


    Geospatial
    Status
    colourGreen
    titleNew

    Conditional Functions

    The following built-in conditional functions are supported in Hive.

    ...

    Return Type

    ...

    Name(Signature)

    ...

    Description

    ...

    T

    ...

    if(boolean testCondition, T valueTrue, T valueFalseOrNull)

    ...

    Returns valueTrue when testCondition is true, returns valueFalseOrNull otherwise.

    ...

    T

    ...

    COALESCE(T v1, T v2, ...)

    ...

    Returns the first v that is not NULL, or NULL if all v's are NULL.

    ...

    T

    ...

    CASE a WHEN b THEN c [WHEN d THEN e]* [ELSE f] END

    ...

    When a = b, returns c; when a = d, returns e; else returns f.

    ...

    T

    ...

    CASE WHEN a THEN b [WHEN c THEN d]* [ELSE e] END

    ...

    When a = true, returns b; when c = true, returns d; else returns e.

    ...

    Returns NULL if a=b; otherwise returns a.

    Tip
    titleShorthand for

    CASE WHEN a = b then NULL else a

    ...

    Data Masking Functions

    Misc. Functions

    Geospatial
    Status
    colourGreen
    titleNew

    Built-in Aggregate Functions (UDAF)

    Hive Aggregate Functions (UDAG) take multiple rows as input and return a single row as output. Depending on the functionality it mainly aggregates the values and returns a single result. These functions are mainly used in the GROUP BY statements.

    Info

    These functions can be used without GROUP BY as well. 

    ...

    Return Type

    ...

    Name(Signature)

    ...

    Description

    ...

    bigint

    ...

    count(*), count(expr), count(DISTINCT expr[, expr...])

    ...

    count(*) - Returns the total number of retrieved rows, including rows containing NULL values.

    count(expr) - Returns the number of rows for which the supplied expression is non-NULL.

    count(DISTINCT expr[, expr]) - Returns the number of rows for which the supplied expression(s) are unique and non-NULL. Execution of this can be optimized with hive.optimize.distinct.rewrite.

    ...

    double

    ...

    sum(col), sum(DISTINCT col)

    ...

    Returns the sum of the elements in the group or the sum of the distinct values of the column in the group.

    ...

    double

    ...

    avg(col), avg(DISTINCT col)

    ...

    Returns the average of the elements in the group or the average of the distinct values of the column in the group.

    ...

    double

    ...

    min(col)

    ...

    Returns the minimum of the column in the group.

    ...

    double

    ...

    max(col)

    ...

    Returns the maximum value of the column in the group.

    ...

    double

    ...

    variance(col), var_pop(col)

    ...

    Returns the variance of a numeric column in the group.

    ...

    double

    ...

    var_samp(col)

    ...

    Returns the unbiased sample variance of a numeric column in the group.

    ...

    double

    ...

    stddev_pop(col)

    ...

    Returns the standard deviation of a numeric column in the group.

    ...

    double

    ...

    stddev_samp(col)

    ...

    Returns the unbiased sample standard deviation of a numeric column in the group.

    ...

    double

    ...

    covar_pop(col1, col2)

    ...

    Returns the population covariance of a pair of numeric columns in the group.

    ...

    double

    ...

    covar_samp(col1, col2)

    ...

    Returns the sample covariance of a pair of numeric columns in the group.

    ...

    double

    ...

    corr(col1, col2)

    ...

    Returns the Pearson coefficient of correlation of a pair of numeric columns in the group.

    ...

    double

    ...

    percentile(BIGINT col, p)

    ...

    Returns the exact pth percentile of a column in the group (does not work with floating point types). p must be between 0 and 1. NOTE: A true percentile can only be computed for integer values. Use PERCENTILE_APPROX if your input is non-integral.

    ...

    array<double>

    ...

    percentile(BIGINT col, array(p1 [, p2]...))

    ...

    Returns the exact percentiles p1, p2, ... of a column in the group (does not work with floating point types). pi must be between 0 and 1. NOTE: A true percentile can only be computed for integer values. Use PERCENTILE_APPROX if your input is non-integral.

    ...

    double

    ...

    percentile_approx(DOUBLE col, p [, B])

    ...

    Returns an approximate pth percentile of a numeric column (including floating point types) in the group. The B parameter controls approximation accuracy at the cost of memory. Higher values yield better approximations, and the default is 10,000. When the number of distinct values in col is smaller than B, this gives an exact percentile value.

    ...

    array<double>

    ...

    percentile_approx(DOUBLE col, array(p1 [, p2]...) [, B])

    ...

    Same as above, but accepts and returns an array of percentile values instead of a single one.

    ...

    regr_avgx(independent, dependent)

    ...

    Equivalent to avg(dependent). 

    ...

    regr_avgy(independent, dependent)

    ...

    Equivalent to avg(independent). 

    ...

    regr_count(independent, dependent)

    ...

    Returns the number of non-null pairs used to fit the linear regression line. 

    ...

    regr_intercept(independent, dependent)

    ...

    Returns the y-intercept of the linear regression line, i.e. the value of b in the equation dependent = a * independent + b.

    ...

    regr_r2(independent, dependent)

    ...

    Returns the coefficient of determination for the regression. 

    ...

    regr_slope(independent, dependent)

    ...

    Returns the slope of the linear regression line, i.e. the value of an in the equation dependent = a * independent + b. 

    ...

    regr_sxx(independent, dependent)

    ...

    Equivalent to regr_count(independent, dependent) * var_pop(dependent). 

    ...

    regr_sxy(independent, dependent)

    ...

    Equivalent to regr_count(independent, dependent) * covar_pop(independent, dependent). 

    ...

    Equivalent to regr_count(independent, dependent) * var_pop(independent).

    ...

    array<struct {'x','y'}>

    ...

    histogram_numeric(col, b)

    ...

    Computes a histogram of a numeric column in the group using b non-uniformly spaced bins. The output is an array of size b of double-valued (x,y) coordinates that represent the bin centers and heights

    ...

    array

    ...

    collect_set(col)

    ...

    Returns a set of objects with duplicate elements eliminated.

    ...

    array

    ...

    collect_list(col)

    ...

    Returns a list of objects with duplicates. 

    ...

    Divides an ordered partition into x groups called buckets and assign a bucket number to each row in the partition. This allows easy calculation of tertiles, quartiles, deciles, percentiles, and other common summary statistics.

    ...



    Built-in Table-Generating Functions (UDTF)

    ...