*** ## description: Functions and Operators (DML) # Functions and Operators ## Basic Mathematical Operators | Operator | Description | | ----------------------------- | ----------------------------------------------- | | `+`*`numeric`* | Returns *`numeric`* | | `–`*`numeric`* | Returns negative value of *`numeric`* | | *`numeric1`* `+` *`numeric2`* | Sum of *`numeric1`* and *`numeric2`* | | *`numeric1`* `–` *`numeric2`* | Difference of *`numeric1`* and *`numeric2`* | | *`numeric1`* `*` *`numeric2`* | Product of *`numeric1`* and *`numeric2`* | | *`numeric1`* `/` *`numeric2`* | Quotient (*`numeric1`* divided by *`numeric2`*) | ### **Mathematical Operator Precedence** 1. Parenthesization 2. Multiplication and division 3. Addition and subtraction ## Comparison Operators | Operator | Description | | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `=` | Equals | | `<>` | Not equals | | `>` | Greater than | | `>=` | Greater than or equal to | | `<` | Less than | | `<=` | Less than or equal to | | `BETWEEN` **`x`** `AND` **`y`** | Is a value within a range | | `NOT BETWEEN` **`x`** `AND` **`y`** | Is a value not within a range | | `IS NULL` | Is a value that is null | | `IS NOT NULL` | Is a value that is not null | | `NULLIF(`**`x`**`,` **`y`**`)` | Compare expressions **x** and **y**. If different, return **x**. If they are the same, return `null`. For example, if a dataset uses ‘NA’ for `null` values, you can use this statement to return `null` using `SELECT NULLIF(field_name,'NA')`. | | `IS TRUE` | True if a value resolves to TRUE. | | `IS NOT TRUE` | True if a value resolves to FALSE. | ## Mathematical Functions | Function | Description | | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ABS(`**`x`**`)` | Returns the absolute value of **x** | | `CEIL(`**`x`**`)` | Returns the smallest integer not less than the argument | | `DEGREES(`**`x`**`)` | Converts radians to degrees | | `EXP(`**`x`**`)` | Returns the value of e to the power of **x** | | `FLOOR(`**`x`**`)` | Returns the largest integer not greater than the argument | | `LN(`**`x`**`)` | Returns the natural logarithm of **x** | | `LOG(`**`x`**`)` | Returns the natural logarithm of **x** | | `LOG10(`**`x`**`)` | Returns the base-10 logarithm of the specified float expression **x** | | `MOD(`**`x,y`**`)` | Returns the remainder of int **x** divided by int **y** | | `PI()` | Returns the value of pi | | `POWER(`**`x,y`**`)` | Returns the value of **x** raised to the power of **y** | | `RADIANS(`**`x`**`)` | Converts degrees to radians | | `ROUND(`**`x`**) | Rounds **x** to the nearest integer value, but does not change the data type. For example, the double value 4.1 rounds to the double value 4. | | `ROUND_TO_DIGIT (`**`x,y`**`)` | Rounds **x** to **y** decimal places | | `SIGN(`**`x`**`)` | Returns the sign of **x** as -1, 0, 1 if **x** is negative, zero, or positive | | `SQRT(`**`x`**`)` | Returns the square root of **x**. | | `TRUNCATE(`**`x,y`**`)` | Truncates **x** to **y** decimal places | | `WIDTH_BUCKET(`**`target,lower-boundary,upper-boundary,bucket-count`**`)` |
Define equal-width intervals (buckets) in a range between the lower boundary and the upper boundary, and returns the bucket number to which the target expression is assigned.
target - A constant, column variable, or general expression for which a bucket number is returned.lower-boundary - Lower boundary for the range of values to be partitioned equally.upper-boundary - Upper boundary for the range of values to be partitioned equally.partition\_count - Number of equal-width buckets in the range defined by the lower and upper boundaries.Expressions can be constants, column variables, or general expressions.
Example
Create 10 age buckets of equal size, with lower bound 0 and upper bound 100 (\[0,10], \[10,20]... \[90,100]), and classify the
age of a customer accordingly:
SELECT WIDTH\_BUCKET(age, 0, 100, 10) FROM customer;
For example, a customer of age 34 is assigned to bucket 3 (\[30,40]) and the function returns the value 3.
| ## Trigonometric Functions | Function | Description | | ---------------------------- | ------------------------------------------------------------------------------------------------ | | `ACOS(`**`x`**`)` | Returns the arc cosine of **x** | | `ASIN(`**`x`**`)` | Returns the arc sine of **x** | | `ATAN(`**`x`**`)` | Returns the arc tangent of **x** | | `ATAN2(`**`y`**`,`**`x`**`)` | Returns the arc tangent of **(x, y)** in the range (-*π*,*π*]. Equal to `ATAN(y/x)` for `x > 0`. | | `COS(`**`x`**`)` | Returns the cosine of **x** | | `COT(`**`x`**`)` | Returns the cotangent of **x** | | `SIN(`**`x`**`)` | Returns the sine of **x** | | `TAN(`**`x`**`)` | Returns the tangent of **x** | ## Geometric Functions | Function | Description | | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------- | | `DISTANCE_IN_METERS(`**`fromLon`**`,` **`fromLat`**`,` **`toLon`**`,` **`toLat`**`)` | Calculates distance in meters between two WGS84 positions. | | `CONV_4326_900913_X(`**`x`**`)` | Converts WGS84 latitude to WGS84 Web Mercator **x** coordinate. | | `CONV_4326_900913_Y(`**`y`**`)` | Converts WGS84 longitude to WGS84 Web Mercator **y** coordinate. | ## String Functions | Function | Description | | ----------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `BASE64_DECODE(`**`str`**`)` | Decodes a BASE64-encoded string. | | `BASE64_ENCODE(`**`str`**`)` | Encodes a string to a BASE64-encoded string. | | `CHAR_LENGTH(`**`str`**`)` | Returns the number of characters in a string. Only works with unencoded fields (ENCODING set to `none`). | | **`str1`** \|\| **`str2`** \[ \|\| **`str3`**... ] |Returns the string that results from concatenating the strings specified. Note that numeric, date, timestamp, and time types will be implicitly casted to strings as necessary, so explicit casts of non-string types to string types is not required for inputs to the concatenation operator.
Note that concatenating a variable string with a string literal, i.e. county\_name
Deterministically Hashes a string input to a BIGINT output using a pseudo-random function. Can be useful for bucketing string values or deterministcally coloring by string values for a high-cardinality TEXT column.
Note that currently HASH only accepts TEXT inputs, but in the future may also accept other data types. It should also be noted that NULL values always hash to NULL outputs.
Returns the string of a field given by path instr. Paths start with the $ character, with sub-fields split by . and array members indexed by [], with array indices starting at 0. For example, JSON_VALUE('{"name": "Brenda", "scores": [89, 98, 94]}', '$.scores\[1]') would yield a TEXT return field of '98'.
Note that currentlyLAX parsing mode (any unmatched path returns null rather than errors) is the default, and STRICT parsing mode is not supported.
Left-pads the string with the string defined in lpad\_str to a total length of len. If the optional lpad\_str is not specified, the space character is used to pad.
If the length of str is greater than len, then characters from the end of str are truncated to the length of len.
Characters are added from lpad\_str successively until the target length len is met. If lpad\_str concatenated with str is not long enough to equal the target len, lpad\_str is repeated, partially if necessary, until the target length is met.
Replaces in str the number of characters defined in len with characters defined in replacement\_str at the location start.
Regardless of the length of replacement\_str, len characters are removed from str unless start + replacement\_str is greater than the length of str, in which case all characters from start to the end of str are replaced.
Ifstart is negative, it specifies the number of characters from the end of str.
Returns the position of the first character in search\_str if found in str, optionally starting the search at start\_position.
If search\_str is not found, 0 is returned. If search\_str or str are null, null is returned.
Returns the number of times that the provided pattern occurs in the search string str.
position specifies the starting position in str for which the search for pattern will start (all matches before position will be ignored. If position is negative, the search will start that many characters from the end of the string str.
Use the following optional flags to control the matching behavior:c - Case-sensitive matching.i - Case-insensitive matching.
Replace one or all matches of a substring in string str that matches pattern , which is a regular expression in POSIX regex syntax.
new\_str (optional) is the string that replaces the string matching the pattern. If new\_str is empty or not supplied, all found matches are removed.
The occurrence integer argument (optional) specifies the single match occurrence of the pattern to replace, starting from the beginning of str; 0 (replace all) is the default. Use a negative occurrence argument to signify the nth-to-last occurrence to be replaced.
pattern uses POSIX regular expression syntax.
Use a positive position argument to indicate the number of characters from the beginning of str. Use a negative position argument to indicate the number of characters from the end of str.
Back-references/capture groups can be used to capture and replace specific sub-expressions.
Use the following optional flags to control the matching behavior:c - Case-sensitive matching.i - Case-insensitive matching.
If not specified, REGEXP\_REPLACE defaults to case sensitive search.
Search string str for pattern, which is a regular expression in POSIX syntax, and return the matching substring.
Use position to set the character position to begin searching. Use occurrence to specify the occurrence of the pattern to match.
Use a positive position argument to indicate the number of characters from the beginning of str. Use a negative position argument to indicate the number of characters from the end of str.
The occurrence integer argument (optional) specifies the single match occurrence of the pattern to replace, with 0 being mapped to the first (1) occurrence. Use a negative occurrence argument to signify the nth-to-last group in pattern is returned.
Use optional flags to control the matching behavior:c - Case-sensitive matching.
e - Extract submatches.i - Case-insensitive matching.
The c and i flags cannot be used together; e can be used with either. If neither c nor i are specified, or if pattern is not provided, REGEXP\_SUBSTR defaults to case-sensitive search.
If the e flag is used, REGEXP\_SUBSTR returns the capture group group\_num of pattern matched in str. If the e flag is used, but no capture groups are provided in pattern, REGEXP\_SUBSTR returns the entire matching pattern, regardless of group\_num. If the e flag is used but no group\_num is provided, a value of 1 for group\_num is assumed, so the first capture group is returned.
Right-pads the string with the string defined in rpad\_str to a total length of len. If the optional rpad\_str is not specified, the space character is used to pad.
If the length of str is greater than len, then characters from the beginning of str are truncated to the length of len.
Characters are added from rpad\_str successively until the target length len is met. If rpad\_str concatenated with str is not long enough to equal the target len, rpad\_str is repeated, partially if necessary, until the target length is met.
Tokenizes the string str using optional delimiter(s) delim and returns an array of tokens.
An empty array is returned if no tokens are produced in tokenization. NULL is returned if either parameter is a NULL.
Returns a substring of str starting at index start for len characters.
The start position is 1-based (that is, the first character of str is at index 1, not 0). However, start 0 aliases to start 1.
If start is negative, it is considered to be
Removes characters defined in trim\_str from the beginning, end, or both of str. If trim\_str is not specified, the space character is the default.
If the trim location is not specified, defined characters are trimmed from both the beginning and end of str.
Attempts to cast/convert a string type to any valid numeric, timestamp, date, or time type. If the conversion cannot be performed, null is returned.
Note that TRY\_CAST is not valid for non-string input types.
CURRENT\_DATE
CURRENT\_DATE()
Returns the current date in the GMT time zone.
Example:
SELECT CURRENT\_DATE();
CURRENT\_TIME
CURRENT\_TIME()
Returns the current time of day in the GMT time zone.
Example:
SELECT CURRENT\_TIME();
CURRENT\_TIMESTAMP
CURRENT\_TIMESTAMP()
Return the current timestamp in the GMT time zone. Same as NOW().
Example:
SELECT CURRENT\_TIMESTAMP();
Returns a date after a specified time/date interval has been added.
Example:
SELECT DATEADD('MINUTE', 6000, dep\_timestamp) Arrival\_Estimate FROM flights\_2008\_10k LIMIT 10;
Returns the difference between two dates, calculated to the lowest level of the date\_part you specify. For example, if you set the date\_part as DAY, only the year, month, and day are used to calculate the result. Other fields, such as hour and minute, are ignored.
Example:
SELECT DATEDIFF('YEAR', plane\_issue\_date, now()) Years\_In\_Service FROM flights\_2008\_10k LIMIT 10;
Returns a specified part of a given date or timestamp as an integer value. Note that 'interval' must be enclosed in single quotes.
Example:
SELECT DATEPART('YEAR', plane\_issue\_date) Year\_Issued FROM flights\_2008\_10k LIMIT 10;
Truncates the timestamp to the specified date\_part. DATE\_TRUNC(week,...) starts on Monday (ISO), which is different than EXTRACT(dow,...), which starts on Sunday.
Example:
SELECT DATE\_TRUNC(MINUTE, arr\_timestamp) Arrival FROM flights\_2008\_10k LIMIT 10;
Returns the specified date\_part from timestamp.
Example:
SELECT EXTRACT(HOUR FROM arr\_timestamp) Arrival\_Hour FROM flights\_2008\_10k LIMIT 10;
Adds or Subtracts count date\_part units from a timestamp. Note that 'count' is enclosed in single quotes.
Example:
SELECT arr\_timestamp + INTERVAL '10' YEAR FROM flights\_2008\_10k LIMIT 10;
Return the current timestamp in the GMT time zone. Same as CURRENT\_TIMESTAMP().
Example:
NOW();
Adds an interval of count date\_part to timestamp or date and returns signed date\_part units in the provided timestamp or date form.
Example:
SELECT TIMESTAMPADD(DAY, 14, arr\_timestamp) Fortnight FROM flights\_2008\_10k LIMIT 10;
Subtracts timestamp1 from timestamp2 and returns the result in signed date\_part units.
Example:
SELECT TIMESTAMPDIFF(MINUTE, arr\_timestamp, dep\_timestamp) Flight\_Time FROM flights\_2008\_10k LIMIT 10;
| Double-precision FP Function | Single-precision FP Function | Description |
|---|---|---|
| Double-precision FP Function | Single-precision FP Function | Description |
AVG(x) | Returns the average value of x | |
COUNT() | Returns the count of the number of rows returned | |
COUNT(DISTINCT x) | Returns the count of distinct values of x | |
APPROX_COUNT_DISTINCT(x, e) | Returns the approximate count of distinct values of x with defined expected error rate e, where e is an integer from 1 to 100. If no value is set for e, the approximate count is calculated using the system-widehll-precision-bits configuration parameter. | |
APPROX_MEDIAN(x) | Returns the approximate median of x. Two server configuration parameters affect memory usage: Accuracy of APPROX_MEDIAN depends on the distribution of data; see Usage Notes. | |
APPROX_PERCENTILE(x,y) | Returns the approximate quantile of For example, | |
MAX(x) | Returns the maximum value of x | |
MIN(x) | Returns the minimum value of x | |
MODE(x) | Returns the most common value of x. Query steps with this operator will run on CPU. | |
SINGLE_VALUE | Returns the input value if there is only one distinct value in the input; otherwise, the query fails. | |
SUM(x) | Returns the sum of the values of x | |
SAMPLE(x) | Returns one sample value from aggregated column x. For example, the following query returns population grouped by city, along with one value from the state column for each group: Note: This was previously | |
CORRELATION(x, y) | CORRELATION_FLOAT(x, y) | Alias of CORR. Returns the coefficient of correlation of a set of number pairs. |
CORR(x, y) | CORR_FLOAT(x, y) | Returns the coefficient of correlation of a set of number pairs. |
COUNT_IF(conditional_expr) | Returns the number of rows satisfying the given condition_expr. | |
COVAR_POP(x, y) | COVAR_POP_FLOAT(x, y) | Returns the population covariance of a set of number pairs. |
COVAR_SAMP(x, y) | COVAR_SAMP_FLOAT(x, y) | Returns the sample covariance of a set of number pairs. |
STDDEV(x) | STDDEV_FLOAT(x) | Alias of STDDEV_SAMP. Returns sample standard deviation of the value. |
STDDEV_POP(x) | STDDEV_POP_FLOAT(x) | Returns the population standard the standard deviation of the value. |
STDDEV_SAMP(x) | STDDEV_SAMP_FLOAT(x) | Returns the sample standard deviation of the value. |
SUM_IF(conditional_expr) | Returns the sum of all expression values satisfying the given condition_expr. | |
VARIANCE(x) | VARIANCE_FLOAT(x) | Alias of VAR_SAMP. Returns the sample variance of the value. |
VAR_POP(x) | VAR_POP_FLOAT(x) | Returns the population variance sample variance of the value. |
VAR_SAMP(x) | VAR_SAMP_FLOAT(x) | Returns the sample variance of the value. |
Returns a Boolean value, with the probability of True being returned for a row equal to the input argument. The input argument is a numeric value between 0.0 and 1.0. Negative input values (return False), input values greater than 1.0 returns True, and null input values return False.
The result of the function is deterministic per row; that is, all calls of the operator for a given row return the same result. The sample ratio is probabilistic, but is generally within a thousandth of a percentile of the actual range when the underlying dataset is millions of records or larger.
The following example filters approximately 50% of the rows from t and returns a count that is approximately half the number of rows in t:
SELECT COUNT(\*) FROM t WHERE SAMPLE\_RATIO(0.5)