diff --git a/docs/aggregate-dp-functions.md b/docs/aggregate-dp-functions.md index a8671d6ce..30513d467 100644 --- a/docs/aggregate-dp-functions.md +++ b/docs/aggregate-dp-functions.md @@ -29,151 +29,165 @@ determine the optimal privacy parameters for your dataset and organization.
ANON_AVG
+ AVG
DIFFERENTIAL_PRIVACY
-supported AVG
.NULL
,
- non-NaN
values in a query with an
- ANONYMIZATION
clause.
+ non-NaN
values in a query with a
+ DIFFERENTIAL_PRIVACY
clause.
ANON_COUNT
+ COUNT
ANONYMIZATION
clause.
+ DIFFERENTIAL_PRIVACY
-supported COUNT
.DIFFERENTIAL_PRIVACY
clause.
NULL
expression in a query with an
- ANONYMIZATION
clause.
+ non-NULL
expression in a query with a
+ DIFFERENTIAL_PRIVACY
clause.
ANON_PERCENTILE_CONT
+ PERCENTILE_CONT
DIFFERENTIAL_PRIVACY
-supported PERCENTILE_CONT
.ANONYMIZATION
clause.
+ in a query with a DIFFERENTIAL_PRIVACY
clause.
ANON_QUANTILES
+ SUM
ANONYMIZATION
clause.
+ DIFFERENTIAL_PRIVACY
-supported SUM
.NULL
,
+ non-NaN
values in a query with a
+ DIFFERENTIAL_PRIVACY
clause.
ANON_STDDEV_POP
+ VAR_POP
ANONYMIZATION
clause.
+ DIFFERENTIAL_PRIVACY
-supported VAR_POP
.DIFFERENTIAL_PRIVACY
clause.
ANON_SUM
+ ANON_AVG
NULL
,
+ Deprecated.
+ Gets the differentially-private average of non-NULL
,
non-NaN
values in a query with an
ANONYMIZATION
clause.
ANON_VAR_POP
+ ANON_COUNT
ANONYMIZATION
clause.
+ Deprecated.
+ ANONYMIZATION
clause.
+ NULL
expression in a query with an
+ ANONYMIZATION
clause.
AVG
(differential privacy)
+ ANON_PERCENTILE_CONT
NULL
,
- non-NaN
values in a query with a
- DIFFERENTIAL_PRIVACY
clause.
+ Deprecated.
+ Computes a differentially-private percentile across privacy unit columns
+ in a query with an ANONYMIZATION
clause.
COUNT
(differential privacy)
+ ANON_QUANTILES
DIFFERENTIAL_PRIVACY
clause.
- NULL
expression in a query with a
- DIFFERENTIAL_PRIVACY
clause.
+ Deprecated.
+ Produces an array of differentially-private quantile boundaries
+ in a query with an ANONYMIZATION
clause.
PERCENTILE_CONT
(differential privacy)
+ ANON_STDDEV_POP
DIFFERENTIAL_PRIVACY
clause.
+ Deprecated.
+ Computes a differentially-private population (biased) standard deviation of
+ values in a query with an ANONYMIZATION
clause.
SUM
(differential privacy)
+ ANON_SUM
NULL
,
- non-NaN
values in a query with a
- DIFFERENTIAL_PRIVACY
clause.
+ non-NaN
values in a query with an
+ ANONYMIZATION
clause.
VAR_POP
(differential privacy)
+ ANON_VAR_POP
DIFFERENTIAL_PRIVACY
clause.
+ Deprecated.
+ Computes a differentially-private population (biased) variance of values
+ in a query with an ANONYMIZATION
clause.
ARRAY_ZIP
+
+FLATTEN
@@ -1305,6 +1314,174 @@ SELECT
[lambda-definition]: https://github.com/google/zetasql/blob/master/docs/functions-reference.md#lambdas
+### `ARRAY_ZIP`
+
+```sql
+ARRAY_ZIP(
+ array_input [ AS alias ],
+ array_input [ AS alias ][, ... ]
+ [, transformation => lambda_expression ]
+ [, mode => { 'STRICT' | 'TRUNCATE' | 'PAD' } ]
+)
+```
+
+**Description**
+
+Combines the elements from two to four arrays into one array.
+
+**Definitions**
+
++ `array_input`: An input `ARRAY` value to be zipped with the other array
+ inputs. `ARRAY_ZIP` supports two to four input arrays.
++ `alias`: An alias optionally supplied for an `array_input`. In the results,
+ the alias is the name of the associated `STRUCT` field.
++ `transformation`: A optionally-named lambda argument. `lambda_expression`
+ specifies how elements are combined as they are zipped. This overrides
+ the default `STRUCT` creation behavior.
++ `mode`: A mandatory-named argument that determines how arrays of differing
+ lengths are zipped. If this optional argument is not supplied, the function
+ uses `STRICT` mode by default. This argument can be one of the following
+ values:
+
+ + `STRICT` (default): If the length of any array is different from the
+ others, produce an error.
+
+ + `TRUNCATE`: Truncate longer arrays to match the length of the shortest
+ array.
+
+ + `PAD`: Pad shorter arrays with `NULL` values to match the length of the
+ longest array.
+
+**Details**
+
++ If an `array_input` or `mode` is `NULL`, this function returns `NULL`, even when
+ `mode` is `STRICT`.
++ Argument aliases can't be used with the `transformation` argument.
+
+**Return type**
+
++ If `transformation` is used and `lambda_expression` returns type `T`, the
+ return type is `ARRAYSTRING
BOOL
INT32
INT64
UINT32
UINT64
NUMERIC
BIGNUMERIC
FLOAT
DOUBLE
STRING
BYTES
DATE
DATETIME
TIME
TIMESTAMP
ENUM
PROTO
BOOL
INT32
INT64
UINT32
UINT64
NUMERIC
BIGNUMERIC
FLOAT
DOUBLE
STRING
BYTES
DATE
DATETIME
TIME
TIMESTAMP
ENUM
PROTO
RANGE
PROTO
(with the same PROTO
name)RANGE
RANGE
STRING
RANGE
RANGE
with the same subtype.Name | +Range | +
---|---|
RANGE |
+ + Contiguous range between two dates, datetimes, or timestamps. + The lower and upper bound for the range are optional. The lower bound + is inclusive and the upper bound is exclusive. + | +
Type Declaration | +Meaning | +
---|---|
RANGE<DATE> |
+ Contiguous range between two dates. | +
RANGE<DATETIME> |
+ Contiguous range between two datetimes. | +
RANGE<TIMESTAMP> |
+ Contiguous range between two timestamps. | +
[H]H
: One or two digit hour (valid values from 00 to 23).
@@ -2336,5 +2452,13 @@ when there is a leap second.
[json-literals]: https://github.com/google/zetasql/blob/master/docs/lexical.md#json_literals
+[range-literals]: https://github.com/google/zetasql/blob/master/docs/lexical.md#range_literals
+
+[range-with-constructor]: #range_with_constructor
+
+[range-constructor]: https://github.com/google/zetasql/blob/master/docs/range-functions.md#range
+
+[range-with-literal]: #range_with_literal
+
diff --git a/docs/date_functions.md b/docs/date_functions.md
index 889970e07..35992a43e 100644
--- a/docs/date_functions.md
+++ b/docs/date_functions.md
@@ -351,7 +351,7 @@ the output is negative.
`FRIDAY`, and `SATURDAY`.
+ `ISOWEEK`: Uses [ISO 8601 week][ISO-8601-week]
boundaries. ISO weeks begin on Monday.
-+ `MONTH`, except when the first two arguments are `TIMESTAMP` objects.
++ `MONTH`
+ `QUARTER`
+ `YEAR`
+ `ISOYEAR`: Uses the [ISO 8601][ISO-8601]
diff --git a/docs/datetime_functions.md b/docs/datetime_functions.md
index 2e01e45a3..33c2e0cf1 100644
--- a/docs/datetime_functions.md
+++ b/docs/datetime_functions.md
@@ -294,7 +294,7 @@ between the two `DATETIME` objects would overflow an
`FRIDAY`, and `SATURDAY`.
+ `ISOWEEK`: Uses [ISO 8601 week][ISO-8601-week]
boundaries. ISO weeks begin on Monday.
-+ `MONTH`, except when the first two arguments are `TIMESTAMP` objects.
++ `MONTH`
+ `QUARTER`
+ `YEAR`
+ `ISOYEAR`: Uses the [ISO 8601][ISO-8601]
@@ -823,6 +823,7 @@ SELECT LAST_DAY(DATETIME '2008-11-10 15:30:00', WEEK(MONDAY)) AS last_day
```sql
PARSE_DATETIME(format_string, datetime_string)
```
+
**Description**
Converts a [string representation of a datetime][datetime-format] to a
diff --git a/docs/debugging_functions.md b/docs/debugging_functions.md
index b22f0c30d..251170e13 100644
--- a/docs/debugging_functions.md
+++ b/docs/debugging_functions.md
@@ -67,9 +67,16 @@ ERROR(error_message)
**Description**
-Returns an error. The `error_message` argument is a `STRING`.
+Returns an error.
-ZetaSQL treats `ERROR` in the same way as any expression that may
+**Definitions**
+
++ `error_message`: A `STRING` value that represents the error message to
+ produce.
+
+**Details**
+
+`ERROR` is treated like any other expression that may
result in an error: there is no special guarantee of evaluation order.
**Return Data Type**
@@ -367,6 +374,7 @@ SELECT ISERROR((SELECT e FROM UNNEST([1, 2]) AS e)) AS is_error
```sql
NULLIFERROR(try_expression)
```
+
**Description**
Evaluates `try_expression`.
diff --git a/docs/differential-privacy.md b/docs/differential-privacy.md
index c7a3a875e..530a66554 100644
--- a/docs/differential-privacy.md
+++ b/docs/differential-privacy.md
@@ -155,17 +155,17 @@ table called `students`.
```sql
SELECT WITH DIFFERENTIAL_PRIVACY
- OPTIONS (epsilon=1.09, delta=1e-5, privacy_unit_column=id)
+ OPTIONS (epsilon=10, delta=.01, privacy_unit_column=id)
item,
- COUNT(*)
+ COUNT(*, contribution_bounds_per_group=>(0, 100))
FROM students;
```
```sql
SELECT WITH DIFFERENTIAL_PRIVACY
- OPTIONS (epsilon=1.09, delta=1e-5, privacy_unit_column=members.id)
+ OPTIONS (epsilon=10, delta=.01, privacy_unit_column=members.id)
item,
- COUNT(*)
+ COUNT(*, contribution_bounds_per_group=>(0, 100))
FROM (SELECT * FROM students) AS members;
```
@@ -178,9 +178,10 @@ table expressions][dp-from-rules].
```sql {.bad}
-- This produces an error
-SELECT
- WITH ANONYMIZATION OPTIONS(epsilon=10, delta=.01, max_groups_contributed=2)
- item, ANON_AVG(quantity CLAMPED BETWEEN 0 AND 100) average_quantity
+SELECT WITH DIFFERENTIAL_PRIVACY
+ OPTIONS(epsilon=10, delta=.01, max_groups_contributed=2)
+ item,
+ AVG(quantity, contribution_bounds_per_group => (0,100)) average_quantity
FROM {{USERNAME}}.view_on_professors, {{USERNAME}}.view_on_students
GROUP BY item;
```
@@ -362,7 +363,7 @@ individual's ID, you could expose sensitive data.
[qs-remove-noise]: https://github.com/google/zetasql/blob/master/docs/query-syntax.md#eliminate_noise
-[qs-limit-groups]: https://github.com/google/zetasql/blob/master/docs/query-syntax.md#limit_groups
+[qs-limit-groups]: https://github.com/google/zetasql/blob/master/docs/query-syntax.md#limit_groups_for_privacy_unit
[data-types-groupable]: https://github.com/google/zetasql/blob/master/docs/data-types.md#groupable_data_types
diff --git a/docs/functions-and-operators.md b/docs/functions-and-operators.md
index 8a46418ad..3541c7c8d 100644
--- a/docs/functions-and-operators.md
+++ b/docs/functions-and-operators.md
@@ -33,7 +33,7 @@ Common conventions:
### Operator precedence
The following table lists all ZetaSQL operators from highest to
-lowest precedence, i.e. the order in which they will be evaluated within a
+lowest precedence, i.e., the order in which they will be evaluated within a
statement.
Shifts the first operand X to the right. This operator does not
-do sign bit extension with a signed type (i.e. it fills vacant bits on the left
+do sign bit extension with a signed type (i.e., it fills vacant bits on the left
with 0 ). This operator returns
0 or a byte sequence of
b'\x00'
@@ -1576,187 +1576,190 @@ SELECT entry FROM entry_table WHERE entry IS NULL
### Comparison operators
-Comparisons always return `BOOL`. Comparisons generally
-require both operands to be of the same type. If operands are of different
-types, and if ZetaSQL can convert the values of those types to a
-common type without loss of precision, ZetaSQL will generally coerce
-them to that common type for the comparison; ZetaSQL will generally
-coerce literals to the type of non-literals, where
-present. Comparable data types are defined in
-[Data Types][operators-link-to-data-types].
-NOTE: ZetaSQL allows comparisons
-between signed and unsigned integers.
-
-Structs support only these comparison operators: equal
-(`=`), not equal (`!=` and `<>`), and `IN`.
-
-The comparison operators in this section cannot be used to compare
-`JSON` ZetaSQL literals with other `JSON` ZetaSQL literals.
-If you need to compare values inside of `JSON`, convert the values to
-SQL values first. For more information, see [`JSON` functions][json-functions].
-
-The following rules apply when comparing these data types:
-
-+ Floating point:
- All comparisons with `NaN` return `FALSE`,
- except for `!=` and `<>`, which return `TRUE`.
-+ `BOOL`: `FALSE` is less than `TRUE`.
-+ `STRING`: Strings are
- compared codepoint-by-codepoint, which means that canonically equivalent
- strings are only guaranteed to compare as equal if
- they have been normalized first.
-+ `NULL`: The convention holds here: any operation with a `NULL` input returns
- `NULL`.
+Compares operands and produces the results of the comparison as a `BOOL`
+value. These comparison operators are available:
|
- - Computes the population (biased) standard deviation of the values. - | - +### `APPROX_COUNT_DISTINCT` -||||
STDDEV_SAMP
+```sql
+APPROX_COUNT_DISTINCT(
+ expression
+)
+```
- |
- - Computes the sample (unbiased) standard deviation of the values. - | -||||
VAR_POP
+Returns the approximate result for `COUNT(DISTINCT expression)`. The value
+returned is a statistical estimate, not necessarily the actual value.
- |
- - Computes the population (biased) variance of the values. - | -||||
VAR_SAMP
+**Supported Argument Types**
- |
- - Computes the sample (unbiased) variance of the values. - | -||||
VARIANCE
++ `ARRAY`
++ `STRUCT`
++ `PROTO`
- |
-
- An alias of VAR_SAMP .
- |
-
Name | +Summary | +
---|---|
ARRAY
-over_clause:
- { named_window | ( [ window_specification ] ) }
+ |
+ + Produces an array with one element for each row in a subquery. + | +
ARRAY_AVG
-```
+ |
+
+ Gets the average of non-NULL values in an array.
+ |
+
ARRAY_CONCAT
-Returns the population (biased) standard deviation of the values. The return
-result is between `0` and `+Inf`.
+ |
+ + Concatenates one or more arrays with the same element type into a + single array. + | +
ARRAY_FILTER
-This function ignores any `NULL` inputs. If all inputs are ignored, this
-function returns `NULL`. If this function receives a single non-`NULL` input,
-it returns `0`.
+ |
+ + Takes an array, filters out unwanted elements, and returns the results + in a new array. + | +
ARRAY_FIRST
-+ Any input value is `NaN`
-+ Any input value is positive infinity or negative infinity.
+ |
+ + Gets the first element in an array. + | +
ARRAY_INCLUDES
-
+ |
+ + Checks if there is an element in the array that is + equal to a search value. + | +
ARRAY_INCLUDES_ALL
-
+ |
+ + Checks if all search values are in an array. + | +
ARRAY_INCLUDES_ANY
-
+ |
+ + Checks if any search values are in an array. + | +
ARRAY_IS_DISTINCT
-
+ |
+ + Checks if an array contains no repeated elements. + | +
ARRAY_LAST
-**Return Data Type**
+ |
+ + Gets the last element in an array. + | +
ARRAY_LENGTH
-**Examples**
+ |
+ + Gets the number of elements in an array. + | +
ARRAY_MAX
-/*-------------------*
- | results |
- +-------------------+
- | 3.265986323710904 |
- *-------------------*/
-```
+ |
+
+ Gets the maximum non-NULL value in an array.
+ |
+
ARRAY_MIN
-/*---------*
- | results |
- +---------+
- | 2 |
- *---------*/
-```
+ |
+
+ Gets the minimum non-NULL value in an array.
+ |
+
ARRAY_REVERSE
-/*---------*
- | results |
- +---------+
- | 0 |
- *---------*/
-```
+ |
+ + Reverses the order of elements in an array. + | +
ARRAY_SLICE
-/*---------*
- | results |
- +---------+
- | NULL |
- *---------*/
-```
+ |
+ + Produces an array containing zero or more consecutive elements from an + input array. + | +
ARRAY_SUM
-/*---------*
- | results |
- +---------+
- | NaN |
- *---------*/
-```
+ |
+
+ Gets the sum of non-NULL values in an array.
+ |
+
ARRAY_TO_STRING
-### `STDDEV_SAMP`
+ |
+
+ Produces a concatenation of the elements in an array as a
+ STRING value.
+ |
+
ARRAY_TRANSFORM
-over_clause:
- { named_window | ( [ window_specification ] ) }
+ |
+ + Transforms the elements of an array, and returns the results in a new + array. + | +
ARRAY_ZIP
-```
+ |
+ + Combines elements from two to four arrays into one array. + | +
FLATTEN
-Returns the sample (unbiased) standard deviation of the values. The return
-result is between `0` and `+Inf`.
+ |
+ + Flattens arrays of nested data to create a single flat array. + | +
GENERATE_ARRAY
-This function ignores any `NULL` inputs. If there are fewer than two non-`NULL`
-inputs, this function returns `NULL`.
+ |
+ + Generates an array of values in a range. + | +
GENERATE_DATE_ARRAY
-+ Any input value is `NaN`
-+ Any input value is positive infinity or negative infinity.
+ |
+ + Generates an array of dates in a range. + | +
GENERATE_TIMESTAMP_ARRAY
-
+ |
+ + Generates an array of timestamps in a range. + | +
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE | INTERVAL |
+
---|---|---|---|---|---|---|---|---|---|
OUTPUT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | INTERVAL |
Name | -Summary | -
---|---|
ANON_AVG
++ `array_to_search`: The array to search.
++ `search_values`: The array that contains the elements to search for.
- |
-
- Gets the differentially-private average of non-NULL ,
- non-NaN values in a query with an
- ANONYMIZATION clause.
- |
-
ANON_COUNT
+**Return type**
- |
-
- Signature 1: Gets the differentially-private count of rows in a query
- with an ANONYMIZATION clause.
- - - Signature 2: Gets the differentially-private count of rows with a - non- NULL expression in a query with an
- ANONYMIZATION clause.
- |
-
ANON_PERCENTILE_CONT
+**Example**
- |
-
- Computes a differentially-private percentile across privacy unit columns
- in a query with an ANONYMIZATION clause.
- |
-
ANON_QUANTILES
-
- |
-
- Produces an array of differentially-private quantile boundaries
- in a query with an ANONYMIZATION clause.
- |
-
ANON_STDDEV_POP
-
- |
-
- Computes a differentially-private population (biased) standard deviation of
- values in a query with an ANONYMIZATION clause.
- |
-
ANON_SUM
+In the following example, the query first checks to see if `3`, `4`, and `5`
+exists in an array. Then the query checks to see if `4`, `5`, and `6` exists in
+an array.
- |
-
- Gets the differentially-private sum of non-NULL ,
- non-NaN values in a query with an
- ANONYMIZATION clause.
- |
-
ANON_VAR_POP
+/*------+-------*
+ | a1 | a2 |
+ +------+-------+
+ | true | false |
+ *------+-------*/
+```
- |
-
- Computes a differentially-private population (biased) variance of values
- in a query with an ANONYMIZATION clause.
- |
-
AVG (differential privacy)
+```sql
+ARRAY_INCLUDES_ANY(array_to_search, search_values)
+```
- |
-
- Gets the differentially-private average of non-NULL ,
- non-NaN values in a query with a
- DIFFERENTIAL_PRIVACY clause.
- |
-
COUNT (differential privacy)
+Takes an array to search and an array of search values. Returns `TRUE` if any
+search values are in the array to search, otherwise returns `FALSE`.
- |
-
- Signature 1: Gets the differentially-private count of rows in a query with a
- DIFFERENTIAL_PRIVACY clause.
- - - Signature 2: Gets the differentially-private count of rows with a - non- NULL expression in a query with a
- DIFFERENTIAL_PRIVACY clause.
- |
-
PERCENTILE_CONT (differential privacy)
+Returns `NULL` if `array_to_search` or `search_values` is
+`NULL`.
- |
-
- Computes a differentially-private percentile across privacy unit columns
- in a query with a DIFFERENTIAL_PRIVACY clause.
- |
-
SUM (differential privacy)
+`BOOL`
- |
-
- Gets the differentially-private sum of non-NULL ,
- non-NaN values in a query with a
- DIFFERENTIAL_PRIVACY clause.
- |
-
VAR_POP (differential privacy)
+In the following example, the query first checks to see if `3`, `4`, or `5`
+exists in an array. Then the query checks to see if `4`, `5`, or `6` exists in
+an array.
- |
-
- Computes the differentially-private population (biased) variance of values
- in a query with a DIFFERENTIAL_PRIVACY clause.
- |
-
Input offset | +Final offset in array | +Notes | +
---|---|---|
0 | +['a', 'b', 'c', 'd'] | +The final offset is 0 . |
+
3 | +['a', 'b', 'c', 'd'] | +The final offset is 3 . |
+
5 | +['a', 'b', 'c', 'd'] | +
+ Because the input offset is out of bounds,
+ the final offset is 3 (array length - 1 ).
+ |
+
-1 | +['a', 'b', 'c', 'd'] | +
+ Because a negative offset is used, the offset starts at the end of the
+ array. The final offset is 3
+ (array length - 1 ).
+ |
+
-2 | +['a', 'b', 'c', 'd'] | +
+ Because a negative offset is used, the offset starts at the end of the
+ array. The final offset is 2
+ (array length - 2 ).
+ |
+
-4 | +['a', 'b', 'c', 'd'] | +
+ Because a negative offset is used, the offset starts at the end of the
+ array. The final offset is 0
+ (array length - 4 ).
+ |
+
-5 | +['a', 'b', 'c', 'd'] | +
+ Because the offset is negative and out of bounds, the final offset is
+ 0 (array length - array length ).
+ |
+
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE | INTERVAL |
+
---|---|---|---|---|---|---|---|---|---|
OUTPUT | INT64 | INT64 | UINT64 | UINT64 | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | INTERVAL |
APPROX_COUNT_DISTINCT
+ BIT_CAST_TO_INT32
COUNT(DISTINCT expression)
.
+ Cast bits to an INT32
value.
APPROX_QUANTILES
+ BIT_CAST_TO_INT64
INT64
value.
APPROX_TOP_COUNT
+ BIT_CAST_TO_UINT32
UINT32
value.
APPROX_TOP_SUM
+ BIT_CAST_TO_UINT64
UINT64
value.
+ BIT_COUNT
+
+HLL_COUNT.EXTRACT
-
-HLL_COUNT.INIT
-
-HLL_COUNT.MERGE
+ CAST
HLL_COUNT.MERGE_PARTIAL
+ SAFE_CAST
CAST
function, but returns NULL
+ when a runtime error is produced.
From | +To | +Rule(s) when casting x |
+
---|---|---|
ARRAY |
+ ARRAY |
+
+
+ The element types of the input
+ array must be castable to the
+ element types of the target array.
+ For example, casting from type
+ ARRAY<INT64> to
+ ARRAY<DOUBLE> or
+ ARRAY<STRING> is valid;
+ casting from type ARRAY<INT64>
+ to ARRAY<BYTES> is not valid.
+
+ |
+
From | +To | +Rule(s) when casting x |
+
---|---|---|
Floating Point | +BIGNUMERIC |
+
+ The floating point number will round
+ half away from zero.
-```sql
-SELECT
- country,
- HLL_COUNT.INIT(customer_id, 10)
- AS hll_sketch
-FROM
- UNNEST(
- ARRAYNaN , +inf or
+ -inf will return an error. Casting a value outside the range
+ of BIGNUMERIC returns an overflow error.
+ |
+
STRING |
+ BIGNUMERIC |
+
+ The numeric literal contained in the string must not exceed
+ the maximum precision or range of the
+ BIGNUMERIC type, or an error will occur. If the number of
+ digits after the decimal point exceeds 38, then the resulting
+ BIGNUMERIC value will round
+ half away from zero
-[precision_hll]: https://github.com/google/zetasql/blob/master/docs/sketches.md#precision_hll
+ to have 38 digits after the decimal point.
+ |
+
From | +To | +Rule(s) when casting x |
+
---|---|---|
Integer | +BOOL |
+
+ Returns FALSE if x is 0 ,
+ TRUE otherwise.
+ |
+
STRING |
+ BOOL |
+
+ Returns TRUE if x is "true" and
+ FALSE if x is "false" + All other values of x are invalid and throw an error instead
+ of casting to a boolean.+ A string is case-insensitive when converting + to a boolean. + |
+
From | +To | +Rule(s) when casting x |
+
---|---|---|
STRING |
+ BYTES |
+ + Strings are cast to bytes using UTF-8 encoding. For example, + the string "©", when cast to + bytes, would become a 2-byte sequence with the + hex values C2 and A9. + | +
PROTO |
+ BYTES |
+
+ Returns the proto2 wire format bytes
+ of x .
+ |
+
Name | -Summary | -|
---|---|---|
KLL_QUANTILES.EXTRACT_INT64
-
- |
-
- Gets a selected number of quantiles from an
- INT64 -initialized KLL sketch.
- |
-|
KLL_QUANTILES.EXTRACT_UINT64
-
- |
-
- Gets a selected number of quantiles from an
- UINT64 -initialized KLL sketch.
- |
-|
KLL_QUANTILES.EXTRACT_DOUBLE
-
- |
-
- Gets a selected number of quantiles from a
- DOUBLE -initialized KLL sketch.
- |
-|
KLL_QUANTILES.EXTRACT_POINT_INT64
-
- |
-
- Gets a specific quantile from an
- INT64 -initialized KLL sketch.
- |
-|
KLL_QUANTILES.EXTRACT_POINT_UINT64
+ | ||
From | +To | +Rule(s) when casting x |
+
STRING |
+ DATE |
+ + When casting from string to date, the string must conform to + the supported date literal format, and is independent of time zone. If the + string expression is invalid or represents a date that is outside of the + supported min/max range, then an error is produced. + | +
TIMESTAMP |
+ DATE |
+ + Casting from a timestamp to date effectively truncates the timestamp as + of the default time zone. + | +
UINT64
-initialized KLL sketch.
- KLL_QUANTILES.EXTRACT_POINT_DOUBLE
+### CAST AS DATETIME
-DOUBLE
-initialized KLL sketch.
- KLL_QUANTILES.INIT_INT64
+**Description**
-INT64
-initialized KLL sketch.
- KLL_QUANTILES.INIT_UINT64
+ZetaSQL supports [casting][con-func-cast] to `DATETIME`. The
+`expression` parameter can represent an expression for these data types:
-UINT64
-initialized KLL sketch.
- KLL_QUANTILES.INIT_DOUBLE
++ `STRING`
++ `DATETIME`
++ `TIMESTAMP`
-DOUBLE
-initialized KLL sketch.
- KLL_QUANTILES.MERGE_INT64
+When an expression of one type is cast to another type, you can use the
+[format clause][formatting-syntax] to provide instructions for how to conduct
+the cast. You can use the format clause in this section if `expression` is a
+`STRING`.
-INT64
-initialized KLL sketches into a new sketch, and
- then gets the quantiles from the new sketch.
- KLL_QUANTILES.MERGE_UINT64
++ [Format string as date and time][format-string-as-date-time]
-UINT64
-initialized KLL sketches into a new sketch, and
- then gets the quantiles from the new sketch.
- KLL_QUANTILES.MERGE_DOUBLE
+**Conversion rules**
-DOUBLE
-initialized KLL sketches
- into a new sketch, and then gets the quantiles from the new sketch.
- From | +To | +Rule(s) when casting x |
+
---|---|---|
STRING |
+ DATETIME |
+ + When casting from string to datetime, the string must conform to the + supported datetime literal format, and is independent of time zone. If + the string expression is invalid or represents a datetime that is outside + of the supported min/max range, then an error is produced. + | +
TIMESTAMP |
+ DATETIME |
+ + Casting from a timestamp to datetime effectively truncates the timestamp + as of the default time zone. + | +
KLL_QUANTILES.MERGE_PARTIAL
+### CAST AS ENUM
-KLL_QUANTILES.MERGE_POINT_INT64
+**Description**
-INT64
-initialized KLL sketches into a new sketch, and
- then gets a specific quantile from the new sketch.
- KLL_QUANTILES.MERGE_POINT_UINT64
+ZetaSQL supports [casting][con-func-cast] to `ENUM`. The `expression`
+parameter can represent an expression for these data types:
-UINT64
-initialized KLL sketches into a new sketch, and
- then gets a specific quantile from the new sketch.
- KLL_QUANTILES.MERGE_POINT_DOUBLE
++ `INT32`
++ `UINT32`
++ `INT64`
++ `UINT64`
++ `STRING`
++ `ENUM`
-DOUBLE
-initialized KLL sketches
- into a new sketch, and then gets a specific quantile from the new sketch.
- From | +To | +Rule(s) when casting x |
+
---|---|---|
ENUM |
+ ENUM |
+ Must have the same enum name. | +
From | +To | +Rule(s) when casting x |
+
---|---|---|
Integer | +Floating Point | ++ Returns a close but potentially not exact floating point value. + | +
NUMERIC |
+ Floating Point | +
+ NUMERIC will convert to the closest floating point number
+ with a possible loss of precision.
+ |
+
BIGNUMERIC |
+ Floating Point | +
+ BIGNUMERIC will convert to the closest floating point number
+ with a possible loss of precision.
+ |
+
STRING |
+ Floating Point | +
+ Returns x as a floating point value, interpreting it as
+ having the same form as a valid floating point literal.
+ Also supports casts from "[+,-]inf" to
+ [,-]Infinity ,
+ "[+,-]infinity" to [,-]Infinity , and
+ "[+,-]nan" to NaN .
+ Conversions are case-insensitive.
+ |
+
From | +To | +Rule(s) when casting x |
+
---|---|---|
+ Floating Point + | ++ Integer + | +
+ Returns the closest integer value. + Halfway cases such as 1.5 or -0.5 round away from zero. + |
+
BOOL |
+ Integer | +
+ Returns 1 if x is TRUE ,
+ 0 otherwise.
+ |
+
STRING |
+ Integer | +
+ A hex string can be cast to an integer. For example,
+ 0x123 to 291 or -0x123 to
+ -291 .
+ |
+
From | +To | +Rule(s) when casting x |
+
---|---|---|
STRING |
+ INTERVAL |
+ + When casting from string to interval, the string must conform to either + ISO 8601 Duration -**Example** + standard or to interval literal + format 'Y-M D H:M:S.F'. Partial interval literal formats are also accepted + when they are not ambiguous, for example 'H:M:S'. + If the string expression is invalid or represents an interval that is + outside of the supported min/max range, then an error is produced. + | +
From | +To | +Rule(s) when casting x |
+
---|---|---|
Floating Point |
+ NUMERIC |
+
+ The floating point number will round
+ half away from zero.
-`UINT64`
+ Casting a NaN , +inf or
+ -inf will return an error. Casting a value outside the range
+ of NUMERIC returns an overflow error.
+ |
+
STRING |
+ NUMERIC |
+
+ The numeric literal contained in the string must not exceed
+ the maximum precision or range of the NUMERIC
+ type, or an error will occur. If the number of digits
+ after the decimal point exceeds nine, then the resulting
+ NUMERIC value will round
+ half away from zero.
-### `KLL_QUANTILES.EXTRACT_POINT_DOUBLE`
+ to have nine digits after the decimal point.
+ |
+
From | +To | +Rule(s) when casting x |
+
---|---|---|
STRING |
+ PROTO |
+
+ Returns the protocol buffer that results from parsing
+ from proto2 text format. + Throws an error if parsing fails, e.g., if not all required fields are + set. + |
+
BYTES |
+ PROTO |
+
+ Returns the protocol buffer that results from parsing
+ x from the proto2 wire format.+ Throws an error if parsing fails, e.g., if not all required fields are + set. + |
+
PROTO |
+ PROTO |
+ Must have the same protocol buffer name. | +
From | +To | +Rule(s) when casting x |
+
---|---|---|
STRING |
+ RANGE |
+ + When casting from string to range, the string must conform to the + supported range literal format. If the string expression is invalid or + represents a range that is outside of the supported subtype min/max range, + then an error is produced. + | +
‑inf
.
++ `INT32`
++ `UINT32`
++ `INT64`
++ `UINT64`
++ `FLOAT`
++ `DOUBLE`
++ `NUMERIC`
++ `BIGNUMERIC`
++ `ENUM`
++ `BOOL`
++ `BYTES`
++ `PROTO`
++ `TIME`
++ `DATE`
++ `DATETIME`
++ `TIMESTAMP`
++ `RANGE`
++ `INTERVAL`
++ `STRING`
-**Supported Argument Types**
+**Format clause**
-+ `input`: `DOUBLE`
-+ `precision`: `INT64`
-+ `input_weight`: `INT64`
+When an expression of one type is cast to another type, you can use the
+[format clause][formatting-syntax] to provide instructions for how to conduct
+the cast. You can use the format clause in this section if `expression` is one
+of these data types:
-**Return Type**
++ `INT32`
++ `UINT32`
++ `INT64`
++ `UINT64`
++ `FLOAT`
++ `DOUBLE`
++ `NUMERIC`
++ `BIGNUMERIC`
++ `BYTES`
++ `TIME`
++ `DATE`
++ `DATETIME`
++ `TIMESTAMP`
-KLL sketch as `BYTES`
+The format clause for `STRING` has an additional optional clause called
+`AT TIME ZONE timezone_expr`, which you can use to specify a specific time zone
+to use during formatting of a `TIMESTAMP`. If this optional clause is not
+included when formatting a `TIMESTAMP`, your current time zone is used.
-[kll-sketches]: https://github.com/google/zetasql/blob/master/docs/sketches.md#sketches_kll
+For more information, see the following topics:
-[sort-order]: https://github.com/google/zetasql/blob/master/docs/data-types.md#comparison_operator_examples
++ [Format bytes as string][format-bytes-as-string]
++ [Format date and time as string][format-date-time-as-string]
++ [Format numeric type as string][format-numeric-type-as-string]
-### `KLL_QUANTILES.MERGE_INT64`
+**Conversion rules**
-```sql
-KLL_QUANTILES.MERGE_INT64(sketch, number)
-```
+From | +To | +Rule(s) when casting x |
+
---|---|---|
Floating Point | +STRING |
+ Returns an approximate string representation. A returned
+ NaN or 0 will not be signed.+ |
+
BOOL |
+ STRING |
+
+ Returns "true" if x is TRUE ,
+ "false" otherwise. |
+
BYTES |
+ STRING |
+
+ Returns x interpreted as a UTF-8 string.+ For example, the bytes literal + b'\xc2\xa9' , when cast to a string,
+ is interpreted as UTF-8 and becomes the unicode character "©".+ An error occurs if x is not valid UTF-8. |
+
ENUM |
+ STRING |
+
+ Returns the canonical enum value name of
+ x .+ If an enum value has multiple names (aliases), + the canonical name/alias for that value is used. |
+
PROTO |
+ STRING |
+ Returns the proto2 text format representation of x . |
+
TIME |
+ STRING |
+
+ Casting from a time type to a string is independent of time zone and
+ is of the form HH:MM:SS .
+ |
+
DATE |
+ STRING |
+
+ Casting from a date type to a string is independent of time zone and is
+ of the form YYYY-MM-DD .
+ |
+
DATETIME |
+ STRING |
+
+ Casting from a datetime type to a string is independent of time zone and
+ is of the form YYYY-MM-DD HH:MM:SS .
+ |
+
TIMESTAMP |
+ STRING |
+ + When casting from timestamp types to string, the timestamp is interpreted + using the default time zone, which is implementation defined. The number of + subsecond digits produced depends on the number of trailing zeroes in the + subsecond part: the CAST function will truncate zero, three, or six + digits. + | +
INTERVAL |
+ STRING |
+
+ Casting from an interval to a string is of the form
+ Y-M D H:M:S .
+ |
+
From | +To | +Rule(s) when casting x |
+
---|---|---|
STRUCT |
+ STRUCT |
+
+ Allowed if the following conditions are met: +
|
+
‑inf
.
++ `STRING`
++ `TIME`
++ `DATETIME`
++ `TIMESTAMP`
-**Supported Argument Types**
+**Format clause**
-+ `sketch`: `BYTES` KLL sketch initialized on
- `DOUBLE` data type
-+ `number`: `INT64`
+When an expression of one type is cast to another type, you can use the
+[format clause][formatting-syntax] to provide instructions for how to conduct
+the cast. You can use the format clause in this section if `expression` is a
+`STRING`.
-**Return Type**
++ [Format string as date and time][format-string-as-date-time]
-`ARRAYFrom | +To | +Rule(s) when casting x |
+
---|---|---|
STRING |
+ TIME |
+ + When casting from string to time, the string must conform to + the supported time literal format, and is independent of time zone. If the + string expression is invalid or represents a time that is outside of the + supported min/max range, then an error is produced. + | +
From | +To | +Rule(s) when casting x |
+
---|---|---|
STRING |
+ TIMESTAMP |
+
+ When casting from string to a timestamp, string_expression
+ must conform to the supported timestamp literal formats, or else a runtime
+ error occurs. The string_expression may itself contain a
+ time zone.
+ + If there is a time zone in the string_expression , that
+ time zone is used for conversion, otherwise the default time zone,
+ which is implementation defined, is used. If the string has fewer than six digits,
+ then it is implicitly widened.
+ + An error is produced if the string_expression is invalid,
+ has more than six subsecond digits (i.e., precision greater than
+ microseconds), or represents a time outside of the supported timestamp
+ range.
+ |
+
DATE |
+ TIMESTAMP |
+
+ Casting from a date to a timestamp interprets date_expression
+ as of midnight (start of the day) in the default time zone,
+ which is implementation defined.
+ |
+
DATETIME |
+ TIMESTAMP |
+
+ Casting from a datetime to a timestamp interprets
+ datetime_expression in the default time zone,
+ which is implementation defined.
+ + Most valid datetime values have exactly one corresponding timestamp + in each time zone. However, there are certain combinations of valid + datetime values and time zones that have zero or two corresponding + timestamp values. This happens in a time zone when clocks are set forward + or set back, such as for Daylight Savings Time. + When there are two valid timestamps, the earlier one is used. + When there is no valid timestamp, the length of the gap in time + (typically one hour) is added to the datetime. + |
+
+SAFE_CAST(expression AS typename [format_clause])
+
-The following query initializes two KLL sketches from five rows of data each.
-Then it merges these two sketches and returns the value of the ninth decile or
-90th percentile of the merged sketch.
+**Description**
-```sql
-SELECT KLL_QUANTILES.MERGE_POINT_INT64(kll_sketch, .9) AS merged_sketch
-FROM (SELECT KLL_QUANTILES.INIT_INT64(x, 1000) AS kll_sketch
- FROM (SELECT 1 AS x UNION ALL
- SELECT 2 AS x UNION ALL
- SELECT 3 AS x UNION ALL
- SELECT 4 AS x UNION ALL
- SELECT 5)
- UNION ALL
- SELECT KLL_QUANTILES.INIT_INT64(x, 1000) AS kll_sketch
- FROM (SELECT 6 AS x UNION ALL
- SELECT 7 AS x UNION ALL
- SELECT 8 AS x UNION ALL
- SELECT 9 AS x UNION ALL
- SELECT 10 AS x));
+When using `CAST`, a query can fail if ZetaSQL is unable to perform
+the cast. For example, the following query generates an error:
-/*---------------*
- | merged_sketch |
- +---------------+
- | 9 |
- *---------------*/
+```sql
+SELECT CAST("apple" AS INT64) AS not_a_number;
```
-### `KLL_QUANTILES.MERGE_POINT_UINT64`
+If you want to protect your queries from these types of errors, you can use
+`SAFE_CAST`. `SAFE_CAST` replaces runtime errors with `NULL`s. However, during
+static analysis, impossible casts between two non-castable types still produce
+an error because the query is invalid.
```sql
-KLL_QUANTILES.MERGE_POINT_UINT64(sketch, phi)
+SELECT SAFE_CAST("apple" AS INT64) AS not_a_number;
+
+/*--------------*
+ | not_a_number |
+ +--------------+
+ | NULL |
+ *--------------*/
```
-**Description**
+Some casts can include a [format clause][formatting-syntax], which provides
+instructions for how to conduct the
+cast. For example, you could
+instruct a cast to convert a sequence of bytes to a BASE64-encoded string
+instead of a UTF-8-encoded string.
-Like [`KLL_QUANTILES.MERGE_POINT_INT64`](#kll-quantilesmerge-point-int64),
-but accepts KLL sketches initialized on data of type `UINT64`.
+The structure of the format clause is unique to each type of cast and more
+information is available in the section for that cast.
-**Supported Argument Types**
+If you are casting from bytes to strings, you can also use the
+function, [`SAFE_CONVERT_BYTES_TO_STRING`][SC_BTS]. Any invalid UTF-8 characters
+are replaced with the unicode replacement character, `U+FFFD`.
-+ `sketch`: `BYTES` KLL sketch initialized on `UINT64` data type
-+ `phi`: `DOUBLE` between 0 and 1
+[SC_BTS]: #safe_convert_bytes_to_string
-**Return Type**
+[formatting-syntax]: https://github.com/google/zetasql/blob/master/docs/format-elements.md#formatting_syntax
-`UINT64`
+### Other conversion functions
+
-### `KLL_QUANTILES.MERGE_POINT_DOUBLE`
+You can learn more about these conversion functions elsewhere in the
+documentation:
-```sql
-KLL_QUANTILES.MERGE_POINT_DOUBLE(sketch, phi)
-```
+
-**Description**
+Conversion function | From | To
+------- | -------- | -------
+[ARRAY_TO_STRING][ARRAY_STRING] | ARRAY | STRING
+[BIT_CAST_TO_INT32][BIT_I32] | UINT32 | INT32
+[BIT_CAST_TO_INT64][BIT_I64] | UINT64 | INT64
+[BIT_CAST_TO_UINT32][BIT_U32] | INT32 | UINT32
+[BIT_CAST_TO_UINT64][BIT_U64] | INT64 | UINT64
+[BOOL][JSON_TO_BOOL] | JSON | BOOL
+[DATE][T_DATE] | Various data types | DATE
+[DATE_FROM_UNIX_DATE][T_DATE_FROM_UNIX_DATE] | INT64 | DATE
+[DATETIME][T_DATETIME] | Various data types | DATETIME
+[FLOAT64][JSON_TO_DOUBLE] | JSON | DOUBLE
+[FROM_BASE32][F_B32] | STRING | BYTEs
+[FROM_BASE64][F_B64] | STRING | BYTES
+[FROM_HEX][F_HEX] | STRING | BYTES
+[FROM_PROTO][F_PROTO] | PROTO value | Most data types
+[INT64][JSON_TO_INT64] | JSON | INT64
+[PARSE_DATE][P_DATE] | STRING | DATE
+[PARSE_DATETIME][P_DATETIME] | STRING | DATETIME
+[PARSE_JSON][P_JSON] | STRING | JSON
+[PARSE_TIME][P_TIME] | STRING | TIME
+[PARSE_TIMESTAMP][P_TIMESTAMP] | STRING | TIMESTAMP
+[SAFE_CONVERT_BYTES_TO_STRING][SC_BTS] | BYTES | STRING
+[STRING][STRING_TIMESTAMP] | TIMESTAMP | STRING
+[STRING][JSON_TO_STRING] | JSON | STRING
+[TIME][T_TIME] | Various data types | TIME
+[TIMESTAMP][T_TIMESTAMP] | Various data types | TIMESTAMP
+[TIMESTAMP_FROM_UNIX_MICROS][T_TIMESTAMP_FROM_UNIX_MICROS] | INT64 | TIMESTAMP
+[TIMESTAMP_FROM_UNIX_MILLIS][T_TIMESTAMP_FROM_UNIX_MILLIS] | INT64 | TIMESTAMP
+[TIMESTAMP_FROM_UNIX_SECONDS][T_TIMESTAMP_FROM_UNIX_SECONDS] | INT64 | TIMESTAMP
+[TIMESTAMP_MICROS][T_TIMESTAMP_MICROS] | INT64 | TIMESTAMP
+[TIMESTAMP_MILLIS][T_TIMESTAMP_MILLIS] | INT64 | TIMESTAMP
+[TIMESTAMP_SECONDS][T_TIMESTAMP_SECONDS] | INT64 | TIMESTAMP
+[TO_BASE32][T_B32] | BYTES | STRING
+[TO_BASE64][T_B64] | BYTES | STRING
+[TO_HEX][T_HEX] | BYTES | STRING
+[TO_JSON][T_JSON] | All data types | JSON
+[TO_JSON_STRING][T_JSON_STRING] | All data types | STRING
+[TO_PROTO][T_PROTO] | Most data types | PROTO value
-Like [`KLL_QUANTILES.MERGE_POINT_INT64`](#kll-quantilesmerge-point-int64),
-but accepts KLL sketches initialized on data of type
-`DOUBLE`.
+
-`KLL_QUANTILES.MERGE_POINT_DOUBLE` orders values according to the
-ZetaSQL [floating point sort order][sort-order]. For example, `NaN`
-orders before ‑inf
.
+
-**Supported Argument Types**
+[conversion-rules]: https://github.com/google/zetasql/blob/master/docs/conversion_rules.md
-+ `sketch`: `BYTES` KLL sketch initialized on
- `DOUBLE` data type
-+ `phi`: `DOUBLE` between 0 and 1
+[ARRAY_STRING]: #array_to_string
-**Return Type**
+[BIT_I32]: #bit_cast_to_int32
-`DOUBLE`
+[BIT_U32]: #bit_cast_to_uint32
-[sort-order]: https://github.com/google/zetasql/blob/master/docs/data-types.md#comparison_operator_examples
+[BIT_I64]: #bit_cast_to_int64
-[kll-sketches]: https://github.com/google/zetasql/blob/master/docs/sketches.md#sketches_kll
+[BIT_U64]: #bit_cast_to_uint64
-[approx-functions-reference]: #approximate_aggregate_functions
+[F_B32]: #from_base32
-## Numbering functions
+[F_B64]: #from_base64
-ZetaSQL supports numbering functions.
-Numbering functions are a subset of window functions. To create a
-window function call and learn about the syntax for window functions,
-see [Window function calls][window-function-calls].
+[F_HEX]: #from_hex
-Numbering functions assign integer values to each row based on their position
-within the specified window. The `OVER` clause syntax varies across
-numbering functions.
+[F_PROTO]: #from_proto
+
+[P_DATE]: #parse_date
+
+[P_DATETIME]: #parse_datetime
+
+[P_JSON]: #parse_json
+
+[P_TIME]: #parse_time
+
+[P_TIMESTAMP]: #parse_timestamp
+
+[SC_BTS]: #safe_convert_bytes_to_string
+
+[STRING_TIMESTAMP]: #string
+
+[T_B32]: #to_base32
+
+[T_B64]: #to_base64
+
+[T_HEX]: #to_hex
+
+[T_JSON]: #to_json
+
+[T_JSON_STRING]: #to_json_string
+
+[T_PROTO]: #to_proto
+
+[T_DATE]: #date
+
+[T_DATETIME]: #datetime
+
+[T_TIMESTAMP]: #timestamp
+
+[T_TIME]: #time
+
+[JSON_TO_BOOL]: #bool_for_json
+
+[JSON_TO_STRING]: #string_for_json
+
+[JSON_TO_INT64]: #int64_for_json
+
+[JSON_TO_DOUBLE]: #double_for_json
+
+[T_DATE_FROM_UNIX_DATE]: #date_from_unix_date
+
+[T_TIMESTAMP_FROM_UNIX_MICROS]: #timestamp_from_unix_micros
+
+[T_TIMESTAMP_FROM_UNIX_MILLIS]: #timestamp_from_unix_millis
+
+[T_TIMESTAMP_FROM_UNIX_SECONDS]: #timestamp_from_unix_seconds
+
+[T_TIMESTAMP_MICROS]: #timestamp_micros
+
+[T_TIMESTAMP_MILLIS]: #timestamp_millis
+
+[T_TIMESTAMP_SECONDS]: #timestamp_seconds
+
+
+
+## Date functions
+
+ZetaSQL supports the following date functions.
### Function list
@@ -9536,2264 +9508,1866 @@ numbering functions.
CUME_DIST
+ CURRENT_DATE
DATE
value.
DENSE_RANK
+ DATE
DATE
value.
NTILE
+ DATE_ADD
DATE
value.
PERCENT_RANK
+ DATE_DIFF
DATE
values.
RANK
+ DATE_FROM_UNIX_DATE
INT64
expression as the number of days
+ since 1970-01-01.
ROW_NUMBER
+ DATE_SUB
DATE
value.
DATE_TRUNC
-```sql
-CUME_DIST()
-OVER over_clause
+DATE
value.
+ EXTRACT
-window_specification:
- [ named_window ]
- [ PARTITION BY partition_expression [, ...] ]
- ORDER BY expression [ { ASC | DESC } ] [, ...]
+DATE
value.
+ FORMAT_DATE
-**Description**
+DATE
value according to a specified format string.
+ LAST_DAY
-To learn more about the `OVER` clause and how to use it, see
-[Window function calls][window-function-calls].
+DATE
value.
+ PARSE_DATE
-[window-function-calls]: https://github.com/google/zetasql/blob/master/docs/window-function-calls.md
+STRING
value to a DATE
value.
+ UNIX_DATE
-**Return Type**
+DATE
value to the number of days since 1970-01-01.
+ Name | -Summary | -
---|---|
BIT_CAST_TO_INT32
+[ISO-8601]: https://en.wikipedia.org/wiki/ISO_8601
- |
-
- Cast bits to an INT32 value.
- |
-
BIT_CAST_TO_INT64
+### `DATE_FROM_UNIX_DATE`
- |
-
- Cast bits to an INT64 value.
- |
-
BIT_CAST_TO_UINT32
+**Description**
- |
-
- Cast bits to an UINT32 value.
- |
-
BIT_CAST_TO_UINT64
+**Return Data Type**
- |
-
- Cast bits to an UINT64 value.
- |
-
BIT_COUNT
+**Example**
- |
- - Gets the number of bits that are set in an input expression. - | -
Name | -Summary | -
---|---|
CAST
+/*------------*
+ | last_day |
+ +------------+
+ | 2008-12-31 |
+ *------------*/
+```
- |
- - Convert the results of an expression to the given type. - | -
SAFE_CAST
+```sql
+SELECT LAST_DAY(DATE '2008-11-10', WEEK(SUNDAY)) AS last_day
- |
-
- Similar to the CAST function, but returns NULL
- when a runtime error is produced.
- |
-
From | -To | -Rule(s) when casting x |
-
---|---|---|
ARRAY |
- ARRAY |
-
-
- The element types of the input
- array must be castable to the
- element types of the target array.
- For example, casting from type
- ARRAY<INT64> to
- ARRAY<DOUBLE> or
- ARRAY<STRING> is valid;
- casting from type ARRAY<INT64>
- to ARRAY<BYTES> is not valid.
-
- |
-
From | -To | -Rule(s) when casting x |
-
---|---|---|
Floating Point | -BIGNUMERIC |
-
- The floating point number will round
- half away from zero.
-
- Casting a NaN , +inf or
- -inf will return an error. Casting a value outside the range
- of BIGNUMERIC returns an overflow error.
- |
-
STRING |
- BIGNUMERIC |
-
- The numeric literal contained in the string must not exceed
- the maximum precision or range of the
- BIGNUMERIC type, or an error will occur. If the number of
- digits after the decimal point exceeds 38, then the resulting
- BIGNUMERIC value will round
- half away from zero
+**Return Data Type**
- to have 38 digits after the decimal point.
- |
-
From | -To | -Rule(s) when casting x |
-
---|---|---|
Integer | -BOOL |
-
- Returns FALSE if x is 0 ,
- TRUE otherwise.
- |
-
STRING |
- BOOL |
-
- Returns TRUE if x is "true" and
- FALSE if x is "false" - All other values of x are invalid and throw an error instead
- of casting to a boolean.- A string is case-insensitive when converting - to a boolean. - |
-
CURRENT_DATETIME
-```sql
-CAST(expression AS BYTES [format_clause])
-```
+DATETIME
value.
+ DATETIME
-ZetaSQL supports [casting][con-func-cast] to `BYTES`. The
-`expression` parameter can represent an expression for these data types:
+DATETIME
value.
+ DATETIME_ADD
-**Format clause**
+DATETIME
value.
+ DATETIME_DIFF
-+ [Format string as bytes][format-string-as-bytes]
+DATETIME
values.
+ DATETIME_SUB
-From | -To | -Rule(s) when casting x |
-
---|---|---|
STRING |
- BYTES |
- - Strings are cast to bytes using UTF-8 encoding. For example, - the string "©", when cast to - bytes, would become a 2-byte sequence with the - hex values C2 and A9. - | -
PROTO |
- BYTES |
-
- Returns the proto2 wire format bytes
- of x .
- |
-
DATETIME
value.
+ DATETIME_TRUNC
-```sql
-CAST(expression AS DATE [format_clause])
-```
+DATETIME
value.
+ EXTRACT
-ZetaSQL supports [casting][con-func-cast] to `DATE`. The `expression`
-parameter can represent an expression for these data types:
+DATETIME
value.
+ FORMAT_DATETIME
-**Format clause**
+DATETIME
value according to a specified
+ format string.
+ LAST_DAY
-+ [Format string as date and time][format-string-as-date-time]
+DATETIME
value.
+ PARSE_DATETIME
-From | -To | -Rule(s) when casting x |
-
---|---|---|
STRING |
- DATE |
- - When casting from string to date, the string must conform to - the supported date literal format, and is independent of time zone. If the - string expression is invalid or represents a date that is outside of the - supported min/max range, then an error is produced. - | -
TIMESTAMP |
- DATE |
- - Casting from a timestamp to date effectively truncates the timestamp as - of the default time zone. - | -
+ Converts a STRING value to a DATETIME value.
+ |
+
+
+
From | -To | -Rule(s) when casting x |
-
---|---|---|
STRING |
- DATETIME |
- - When casting from string to datetime, the string must conform to the - supported datetime literal format, and is independent of time zone. If - the string expression is invalid or represents a datetime that is outside - of the supported min/max range, then an error is produced. - | -
TIMESTAMP |
- DATETIME |
- - Casting from a timestamp to datetime effectively truncates the timestamp - as of the default time zone. - | -
From | -To | -Rule(s) when casting x |
-
---|---|---|
ENUM |
- ENUM |
- Must have the same enum name. | -
From | -To | -Rule(s) when casting x |
-
---|---|---|
Integer | -Floating Point | -- Returns a close but potentially not exact floating point value. - | -
NUMERIC |
- Floating Point | -
- NUMERIC will convert to the closest floating point number
- with a possible loss of precision.
- |
-
BIGNUMERIC |
- Floating Point | -
- BIGNUMERIC will convert to the closest floating point number
- with a possible loss of precision.
- |
-
STRING |
- Floating Point | -
- Returns x as a floating point value, interpreting it as
- having the same form as a valid floating point literal.
- Also supports casts from "[+,-]inf" to
- [,-]Infinity ,
- "[+,-]infinity" to [,-]Infinity , and
- "[+,-]nan" to NaN .
- Conversions are case-insensitive.
- |
-
From | -To | -Rule(s) when casting x |
-
---|---|---|
- Floating Point - | -- Integer - | -
- Returns the closest integer value. - Halfway cases such as 1.5 or -0.5 round away from zero. - |
-
BOOL |
- Integer | -
- Returns 1 if x is TRUE ,
- 0 otherwise.
- |
-
STRING |
- Integer | -
- A hex string can be cast to an integer. For example,
- 0x123 to 291 or -0x123 to
- -291 .
- |
-
From | -To | -Rule(s) when casting x |
-
---|---|---|
STRING |
- INTERVAL |
- - When casting from string to interval, the string must conform to either - ISO 8601 Duration +[ISO-8601]: https://en.wikipedia.org/wiki/ISO_8601 - standard or to interval literal - format 'Y-M D H:M:S.F'. Partial interval literal formats are also accepted - when they are not ambiguous, for example 'H:M:S'. - If the string expression is invalid or represents an interval that is - outside of the supported min/max range, then an error is produced. - | -
From | -To | -Rule(s) when casting x |
-
---|---|---|
Floating Point | -NUMERIC |
-
- The floating point number will round
- half away from zero.
+`DATETIME`
- Casting a NaN , +inf or
- -inf will return an error. Casting a value outside the range
- of NUMERIC returns an overflow error.
- |
-
STRING |
- NUMERIC |
-
- The numeric literal contained in the string must not exceed
- the maximum precision or range of the NUMERIC
- type, or an error will occur. If the number of digits
- after the decimal point exceeds nine, then the resulting
- NUMERIC value will round
- half away from zero.
+**Example**
- to have nine digits after the decimal point.
- |
-
From | -To | -Rule(s) when casting x |
-
---|---|---|
STRING |
- PROTO |
-
- Returns the protocol buffer that results from parsing
- from proto2 text format. - Throws an error if parsing fails, e.g. if not all required fields are set. - |
-
BYTES |
- PROTO |
-
- Returns the protocol buffer that results from parsing
- x from the proto2 wire format.- Throws an error if parsing fails, e.g. if not all required fields are set. - |
-
PROTO |
- PROTO |
- Must have the same protocol buffer name. | -
From | -To | -Rule(s) when casting x |
-
---|---|---|
Floating Point | -STRING |
- Returns an approximate string representation. A returned
- NaN or 0 will not be signed.- |
-
BOOL |
- STRING |
-
- Returns "true" if x is TRUE ,
- "false" otherwise. |
-
BYTES |
- STRING |
-
- Returns x interpreted as a UTF-8 string.- For example, the bytes literal - b'\xc2\xa9' , when cast to a string,
- is interpreted as UTF-8 and becomes the unicode character "©".- An error occurs if x is not valid UTF-8. |
-
ENUM |
- STRING |
-
- Returns the canonical enum value name of
- x .- If an enum value has multiple names (aliases), - the canonical name/alias for that value is used. |
-
PROTO |
- STRING |
- Returns the proto2 text format representation of x . |
-
TIME |
- STRING |
-
- Casting from a time type to a string is independent of time zone and
- is of the form HH:MM:SS .
- |
-
DATE |
- STRING |
-
- Casting from a date type to a string is independent of time zone and is
- of the form YYYY-MM-DD .
- |
-
DATETIME |
- STRING |
-
- Casting from a datetime type to a string is independent of time zone and
- is of the form YYYY-MM-DD HH:MM:SS .
- |
-
TIMESTAMP |
- STRING |
- - When casting from timestamp types to string, the timestamp is interpreted - using the default time zone, which is implementation defined. The number of - subsecond digits produced depends on the number of trailing zeroes in the - subsecond part: the CAST function will truncate zero, three, or six - digits. - | -
INTERVAL |
- STRING |
-
- Casting from an interval to a string is of the form
- Y-M D H:M:S .
- |
-
From | -To | -Rule(s) when casting x |
-
---|---|---|
STRUCT |
- STRUCT |
-
- Allowed if the following conditions are met: -
|
-
From | -To | -Rule(s) when casting x |
-
---|---|---|
STRING |
- TIME |
- - When casting from string to time, the string must conform to - the supported time literal format, and is independent of time zone. If the - string expression is invalid or represents a time that is outside of the - supported min/max range, then an error is produced. - | -
From | -To | -Rule(s) when casting x |
-
---|---|---|
STRING |
- TIMESTAMP |
-
- When casting from string to a timestamp, string_expression
- must conform to the supported timestamp literal formats, or else a runtime
- error occurs. The string_expression may itself contain a
- time zone.
- - If there is a time zone in the string_expression , that
- time zone is used for conversion, otherwise the default time zone,
- which is implementation defined, is used. If the string has fewer than six digits,
- then it is implicitly widened.
- - An error is produced if the string_expression is invalid,
- has more than six subsecond digits (i.e. precision greater than
- microseconds), or represents a time outside of the supported timestamp
- range.
- |
-
DATE |
- TIMESTAMP |
-
- Casting from a date to a timestamp interprets date_expression
- as of midnight (start of the day) in the default time zone,
- which is implementation defined.
- |
-
DATETIME |
- TIMESTAMP |
-
- Casting from a datetime to a timestamp interprets
- datetime_expression in the default time zone,
- which is implementation defined.
- - Most valid datetime values have exactly one corresponding timestamp - in each time zone. However, there are certain combinations of valid - datetime values and time zones that have zero or two corresponding - timestamp values. This happens in a time zone when clocks are set forward - or set back, such as for Daylight Savings Time. - When there are two valid timestamps, the earlier one is used. - When there is no valid timestamp, the length of the gap in time - (typically one hour) is added to the datetime. - |
-
-SAFE_CAST(expression AS typename [format_clause])
-
+```sql
+PARSE_DATETIME(format_string, datetime_string)
+```
**Description**
-When using `CAST`, a query can fail if ZetaSQL is unable to perform
-the cast. For example, the following query generates an error:
-
-```sql
-SELECT CAST("apple" AS INT64) AS not_a_number;
-```
+Converts a [string representation of a datetime][datetime-format] to a
+`DATETIME` object.
-If you want to protect your queries from these types of errors, you can use
-`SAFE_CAST`. `SAFE_CAST` replaces runtime errors with `NULL`s. However, during
-static analysis, impossible casts between two non-castable types still produce
-an error because the query is invalid.
+`format_string` contains the [format elements][datetime-format-elements]
+that define how `datetime_string` is formatted. Each element in
+`datetime_string` must have a corresponding element in `format_string`. The
+location of each element in `format_string` must match the location of
+each element in `datetime_string`.
```sql
-SELECT SAFE_CAST("apple" AS INT64) AS not_a_number;
-
-/*--------------*
- | not_a_number |
- +--------------+
- | NULL |
- *--------------*/
-```
-
-Some casts can include a [format clause][formatting-syntax], which provides
-instructions for how to conduct the
-cast. For example, you could
-instruct a cast to convert a sequence of bytes to a BASE64-encoded string
-instead of a UTF-8-encoded string.
-
-The structure of the format clause is unique to each type of cast and more
-information is available in the section for that cast.
-
-If you are casting from bytes to strings, you can also use the
-function, [`SAFE_CONVERT_BYTES_TO_STRING`][SC_BTS]. Any invalid UTF-8 characters
-are replaced with the unicode replacement character, `U+FFFD`.
-
-[SC_BTS]: #safe_convert_bytes_to_string
-
-[formatting-syntax]: https://github.com/google/zetasql/blob/master/docs/format-elements.md#formatting_syntax
-
-### Other conversion functions
-
-
-You can learn more about these conversion functions elsewhere in the
-documentation:
-
-
-
-Conversion function | From | To
-------- | -------- | -------
-[ARRAY_TO_STRING][ARRAY_STRING] | ARRAY | STRING
-[BIT_CAST_TO_INT32][BIT_I32] | UINT32 | INT32
-[BIT_CAST_TO_INT64][BIT_I64] | UINT64 | INT64
-[BIT_CAST_TO_UINT32][BIT_U32] | INT32 | UINT32
-[BIT_CAST_TO_UINT64][BIT_U64] | INT64 | UINT64
-[BOOL][JSON_TO_BOOL] | JSON | BOOL
-[DATE][T_DATE] | Various data types | DATE
-[DATE_FROM_UNIX_DATE][T_DATE_FROM_UNIX_DATE] | INT64 | DATE
-[DATETIME][T_DATETIME] | Various data types | DATETIME
-[FLOAT64][JSON_TO_DOUBLE] | JSON | DOUBLE
-[FROM_BASE32][F_B32] | STRING | BYTEs
-[FROM_BASE64][F_B64] | STRING | BYTES
-[FROM_HEX][F_HEX] | STRING | BYTES
-[FROM_PROTO][F_PROTO] | PROTO value | Most data types
-[INT64][JSON_TO_INT64] | JSON | INT64
-[PARSE_DATE][P_DATE] | STRING | DATE
-[PARSE_DATETIME][P_DATETIME] | STRING | DATETIME
-[PARSE_JSON][P_JSON] | STRING | JSON
-[PARSE_TIME][P_TIME] | STRING | TIME
-[PARSE_TIMESTAMP][P_TIMESTAMP] | STRING | TIMESTAMP
-[SAFE_CONVERT_BYTES_TO_STRING][SC_BTS] | BYTES | STRING
-[STRING][STRING_TIMESTAMP] | TIMESTAMP | STRING
-[STRING][JSON_TO_STRING] | JSON | STRING
-[TIME][T_TIME] | Various data types | TIME
-[TIMESTAMP][T_TIMESTAMP] | Various data types | TIMESTAMP
-[TIMESTAMP_FROM_UNIX_MICROS][T_TIMESTAMP_FROM_UNIX_MICROS] | INT64 | TIMESTAMP
-[TIMESTAMP_FROM_UNIX_MILLIS][T_TIMESTAMP_FROM_UNIX_MILLIS] | INT64 | TIMESTAMP
-[TIMESTAMP_FROM_UNIX_SECONDS][T_TIMESTAMP_FROM_UNIX_SECONDS] | INT64 | TIMESTAMP
-[TIMESTAMP_MICROS][T_TIMESTAMP_MICROS] | INT64 | TIMESTAMP
-[TIMESTAMP_MILLIS][T_TIMESTAMP_MILLIS] | INT64 | TIMESTAMP
-[TIMESTAMP_SECONDS][T_TIMESTAMP_SECONDS] | INT64 | TIMESTAMP
-[TO_BASE32][T_B32] | BYTES | STRING
-[TO_BASE64][T_B64] | BYTES | STRING
-[TO_HEX][T_HEX] | BYTES | STRING
-[TO_JSON][T_JSON] | All data types | JSON
-[TO_JSON_STRING][T_JSON_STRING] | All data types | STRING
-[TO_PROTO][T_PROTO] | Most data types | PROTO value
-
-
-
-
-
-[conversion-rules]: https://github.com/google/zetasql/blob/master/docs/conversion_rules.md
-
-[ARRAY_STRING]: #array_to_string
-
-[BIT_I32]: #bit_cast_to_int32
-
-[BIT_U32]: #bit_cast_to_uint32
-
-[BIT_I64]: #bit_cast_to_int64
-
-[BIT_U64]: #bit_cast_to_uint64
-
-[F_B32]: #from_base32
-
-[F_B64]: #from_base64
-
-[F_HEX]: #from_hex
-
-[F_PROTO]: #from_proto
-
-[P_DATE]: #parse_date
-
-[P_DATETIME]: #parse_datetime
-
-[P_JSON]: #parse_json
-
-[P_TIME]: #parse_time
-
-[P_TIMESTAMP]: #parse_timestamp
-
-[SC_BTS]: #safe_convert_bytes_to_string
-
-[STRING_TIMESTAMP]: #string
-
-[T_B32]: #to_base32
-
-[T_B64]: #to_base64
-
-[T_HEX]: #to_hex
-
-[T_JSON]: #to_json
+-- This works because elements on both sides match.
+SELECT PARSE_DATETIME("%a %b %e %I:%M:%S %Y", "Thu Dec 25 07:30:00 2008")
-[T_JSON_STRING]: #to_json_string
+-- This produces an error because the year element is in different locations.
+SELECT PARSE_DATETIME("%a %b %e %Y %I:%M:%S", "Thu Dec 25 07:30:00 2008")
-[T_PROTO]: #to_proto
+-- This produces an error because one of the year elements is missing.
+SELECT PARSE_DATETIME("%a %b %e %I:%M:%S", "Thu Dec 25 07:30:00 2008")
-[T_DATE]: #date
+-- This works because %c can find all matching elements in datetime_string.
+SELECT PARSE_DATETIME("%c", "Thu Dec 25 07:30:00 2008")
+```
-[T_DATETIME]: #datetime
+`PARSE_DATETIME` parses `string` according to the following rules:
-[T_TIMESTAMP]: #timestamp
++ **Unspecified fields.** Any unspecified field is initialized from
+ `1970-01-01 00:00:00.0`. For example, if the year is unspecified then it
+ defaults to `1970`.
++ **Case insensitivity.** Names, such as `Monday` and `February`,
+ are case insensitive.
++ **Whitespace.** One or more consecutive white spaces in the format string
+ matches zero or more consecutive white spaces in the
+ `DATETIME` string. Leading and trailing
+ white spaces in the `DATETIME` string are always
+ allowed, even if they are not in the format string.
++ **Format precedence.** When two or more format elements have overlapping
+ information, the last one generally overrides any earlier ones, with some
+ exceptions. For example, both `%F` and `%Y` affect the year, so the earlier
+ element overrides the later. See the descriptions
+ of `%s`, `%C`, and `%y` in
+ [Supported Format Elements For DATETIME][datetime-format-elements].
++ **Format divergence.** `%p` can be used with `am`, `AM`, `pm`, and `PM`.
-[T_TIME]: #time
+**Return Data Type**
-[JSON_TO_BOOL]: #bool_for_json
+`DATETIME`
-[JSON_TO_STRING]: #string_for_json
+**Examples**
-[JSON_TO_INT64]: #int64_for_json
+The following examples parse a `STRING` literal as a
+`DATETIME`.
-[JSON_TO_DOUBLE]: #double_for_json
+```sql
+SELECT PARSE_DATETIME('%Y-%m-%d %H:%M:%S', '1998-10-18 13:45:55') AS datetime;
-[T_DATE_FROM_UNIX_DATE]: #date_from_unix_date
+/*---------------------*
+ | datetime |
+ +---------------------+
+ | 1998-10-18 13:45:55 |
+ *---------------------*/
+```
-[T_TIMESTAMP_FROM_UNIX_MICROS]: #timestamp_from_unix_micros
+```sql
+SELECT PARSE_DATETIME('%m/%d/%Y %I:%M:%S %p', '8/30/2018 2:23:38 pm') AS datetime
-[T_TIMESTAMP_FROM_UNIX_MILLIS]: #timestamp_from_unix_millis
+/*---------------------*
+ | datetime |
+ +---------------------+
+ | 2018-08-30 14:23:38 |
+ *---------------------*/
+```
-[T_TIMESTAMP_FROM_UNIX_SECONDS]: #timestamp_from_unix_seconds
+The following example parses a `STRING` literal
+containing a date in a natural language format as a
+`DATETIME`.
-[T_TIMESTAMP_MICROS]: #timestamp_micros
+```sql
+SELECT PARSE_DATETIME('%A, %B %e, %Y','Wednesday, December 19, 2018')
+ AS datetime;
-[T_TIMESTAMP_MILLIS]: #timestamp_millis
+/*---------------------*
+ | datetime |
+ +---------------------+
+ | 2018-12-19 00:00:00 |
+ *---------------------*/
+```
-[T_TIMESTAMP_SECONDS]: #timestamp_seconds
+[datetime-format]: #format_datetime
-
+[datetime-format-elements]: https://github.com/google/zetasql/blob/master/docs/format-elements.md#format_elements_date_time
-## Mathematical functions
+[ISO-8601]: https://en.wikipedia.org/wiki/ISO_8601
-ZetaSQL supports mathematical functions.
-All mathematical functions have the following behaviors:
+## Debugging functions
-+ They return `NULL` if any of the input parameters is `NULL`.
-+ They return `NaN` if any of the arguments is `NaN`.
+ZetaSQL supports the following debugging functions.
### Function list
@@ -11807,1715 +11381,1646 @@ All mathematical functions have the following behaviors:
ABS
+ ERROR
X
.
+ Produces an error with a custom error message.
ACOS
+ IFERROR
X
.
+ Evaluates a try expression, and if an evaluation error is produced, returns
+ the result of a catch expression.
ACOSH
+ ISERROR
X
.
+ Evaluates a try expression, and if an evaluation error is produced, returns
+ TRUE
.
ASIN
+ NULLIFERROR
X
.
+ Evaluates a try expression, and if an evaluation error is produced, returns
+ NULL
.
ASINH
+ X
.
- ATAN
+```sql
+ERROR(error_message)
+```
-X
.
- ATAN2
+Returns an error.
-X/Y
, using the signs of
- X
and Y
to determine the quadrant.
- ATANH
++ `error_message`: A `STRING` value that represents the error message to
+ produce.
-X
.
- CBRT
+`ERROR` is treated like any other expression that may
+result in an error: there is no special guarantee of evaluation order.
-X
.
- CEIL
+ZetaSQL infers the return type in context.
-X
.
- CEILING
+In the following example, the query returns an error message if the value of the
+row does not match one of two defined values.
-CEIL
.
- COS
+-- Found unexpected value: baz
+```
-X
.
- COSH
+```sql
+SELECT *
+FROM (SELECT -1 AS x)
+WHERE x > 0 AND ERROR('Example error');
+```
-X
.
- COSINE_DISTANCE
+```sql
+SELECT *
+FROM (SELECT -1 AS x)
+WHERE IF(x > 0, true, ERROR(FORMAT('Error: x must be positive but is %t', x)));
-COT
+### `IFERROR`
-X
.
- COTH
+**Description**
-X
.
- CSC
+When `try_expression` is evaluated:
-X
.
- CSCH
+If `catch_expression` is evaluated:
-X
.
- DIV
+**Arguments**
-X
by integer Y
.
- EXP
+The results of `try_expression` and `catch_expression` must share a
+[supertype][supertype].
-e
to the power of X
.
- EUCLIDEAN_DISTANCE
+The [supertype][supertype] for `try_expression` and
+`catch_expression`.
-FLOOR
+In the following examples, the query successfully evaluates `try_expression`.
-X
.
- GREATEST
+/*--------*
+ | result |
+ +--------+
+ | a |
+ *--------*/
+```
-X1,...,XN
.
- IEEE_DIVIDE
+/*--------*
+ | result |
+ +--------+
+ | 1 |
+ *--------*/
+```
-X
by Y
, but does not generate errors for
- division by zero or overflow.
- IS_INF
+```sql
+SELECT IFERROR(ERROR('a'), 'b') AS result
-X
is positive or negative infinity.
- IS_NAN
+```sql
+SELECT IFERROR((SELECT [1,2,3][OFFSET(9)]), -1) AS result
-X
is a NaN
value.
- LEAST
+In the following query, the error is handled by the innermost `IFERROR`
+operation, `IFERROR(ERROR('a'), 'b')`.
-X1,...,XN
.
- LN
+/*--------*
+ | result |
+ +--------+
+ | b |
+ *--------*/
+```
-X
.
- LOG
+```sql
+SELECT IFERROR(IFERROR(ERROR('a'), ERROR('b')), 'c') AS result
-X
or the logarithm of
- X
to base Y
.
- LOG10
+In the following example, an evaluation error is produced because the subquery
+passed in as the `try_expression` evaluates to a table, not a scalar value.
-X
to base 10.
- MOD
+/*--------*
+ | result |
+ +--------+
+ | 3 |
+ *--------*/
+```
-X
by Y
.
- PI
+```sql
+SELECT IFERROR(ERROR('a'), ERROR('b')) AS result
-DOUBLE
value.
- PI_BIGNUMERIC
+[supertype]: https://github.com/google/zetasql/blob/master/docs/conversion_rules.md#supertypes
-BIGNUMERIC
value.
- PI_NUMERIC
+```sql
+ISERROR(try_expression)
+```
-NUMERIC
value.
- POW
+Evaluates `try_expression`.
-X
raised to the power of Y
.
- POWER
+**Arguments**
-POW
.
- RAND
+**Return Data Type**
-DOUBLE
in the range of
- [0, 1)
.
- ROUND
+**Example**
-X
to the nearest integer or rounds X
- to N
decimal places after the decimal point.
- SAFE_ADD
+```sql
+SELECT ISERROR('a') AS is_error
-X + Y
), but returns
- NULL
if overflow occurs.
- SAFE_DIVIDE
+```sql
+SELECT ISERROR(2/1) AS is_error
-X / Y
), but returns
- NULL
if an error occurs.
- Name | +Summary | +|
---|---|---|
SAFE_MULTIPLY
+ | AVG
|
- Equivalent to the multiplication operator (X * Y ),
- but returns NULL if overflow occurs.
+ DIFFERENTIAL_PRIVACY -supported AVG .+ Gets the differentially-private average of non- NULL ,
+ non-NaN values in a query with a
+ DIFFERENTIAL_PRIVACY clause.
|
SAFE_NEGATE
+ | COUNT
|
- Equivalent to the unary minus operator (-X ), but returns
- NULL if overflow occurs.
+ DIFFERENTIAL_PRIVACY -supported COUNT .+ Signature 1: Gets the differentially-private count of rows in a query with a + DIFFERENTIAL_PRIVACY clause.
+ + + Signature 2: Gets the differentially-private count of rows with a + non- NULL expression in a query with a
+ DIFFERENTIAL_PRIVACY clause.
|
SAFE_SUBTRACT
+ | PERCENTILE_CONT
|
- Equivalent to the subtraction operator (X - Y ), but
- returns NULL if overflow occurs.
+ DIFFERENTIAL_PRIVACY -supported PERCENTILE_CONT .+ Computes a differentially-private percentile across privacy unit columns + in a query with a DIFFERENTIAL_PRIVACY clause.
|
SEC
+ | SUM
|
- Computes the secant of X .
+ DIFFERENTIAL_PRIVACY -supported SUM .+ Gets the differentially-private sum of non- NULL ,
+ non-NaN values in a query with a
+ DIFFERENTIAL_PRIVACY clause.
|
SECH
+ | VAR_POP
|
- Computes the hyperbolic secant of X .
+ DIFFERENTIAL_PRIVACY -supported VAR_POP .+ Computes the differentially-private population (biased) variance of values + in a query with a DIFFERENTIAL_PRIVACY clause.
|
SIGN
+ | ANON_AVG
|
- Produces -1 , 0, or +1 for negative, zero, and positive arguments
- respectively.
+ Deprecated.
+ Gets the differentially-private average of non-NULL ,
+ non-NaN values in a query with an
+ ANONYMIZATION clause.
|
SIN
+ | ANON_COUNT
|
- Computes the sine of X .
+ Deprecated.
+ + + Signature 1: Gets the differentially-private count of rows in a query + with an ANONYMIZATION clause.
+ + + Signature 2: Gets the differentially-private count of rows with a + non- NULL expression in a query with an
+ ANONYMIZATION clause.
|
SINH
+ | ANON_PERCENTILE_CONT
|
- Computes the hyperbolic sine of X .
+ Deprecated.
+ Computes a differentially-private percentile across privacy unit columns
+ in a query with an ANONYMIZATION clause.
|
SQRT
+ | ANON_QUANTILES
|
- Computes the square root of X .
+ Deprecated.
+ Produces an array of differentially-private quantile boundaries
+ in a query with an ANONYMIZATION clause.
|
TAN
+ | ANON_STDDEV_POP
|
- Computes the tangent of X .
+ Deprecated.
+ Computes a differentially-private population (biased) standard deviation of
+ values in a query with an ANONYMIZATION clause.
|
TANH
+ | ANON_SUM
|
- Computes the hyperbolic tangent of X .
+ Deprecated.
+ Gets the differentially-private sum of non-NULL ,
+ non-NaN values in a query with an
+ ANONYMIZATION clause.
|
TRUNC
+ | ANON_VAR_POP
|
- Rounds a number like ROUND(X) or ROUND(X, N) ,
- but always rounds towards zero and never overflows.
+ Deprecated.
+ Computes a differentially-private population (biased) variance of values
+ in a query with an ANONYMIZATION clause.
|
X | -ABS(X) | -
---|---|
25 | -25 | -
-25 | -25 | -
+inf |
- +inf |
-
-inf |
- +inf |
-
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
-
---|---|---|---|---|---|---|---|---|
OUTPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
X | -ACOS(X) | -
---|---|
+inf |
- NaN |
-
-inf |
- NaN |
-
NaN |
- NaN |
-
X < -1 | -Error | -
X > 1 | -Error | -
X | -ACOSH(X) | -
---|---|
+inf |
- +inf |
-
-inf |
- NaN |
-
NaN |
- NaN |
-
X < 1 | -Error | -
X | -ASIN(X) | -
---|---|
+inf |
- NaN |
-
-inf |
- NaN |
-
NaN |
- NaN |
-
X < -1 | -Error | -
X > 1 | -Error | -
X | -ASINH(X) | -
---|---|
+inf |
- +inf |
-
-inf |
- -inf |
-
NaN |
- NaN |
-
X | -ATAN(X) | -
---|---|
+inf |
- π/2 | -
-inf |
- -π/2 | -
NaN |
- NaN |
-
X | -Y | -ATAN2(X, Y) | -
---|---|---|
NaN |
- Any value | -NaN |
-
Any value | -NaN |
- NaN |
-
0.0 | -0.0 | -0.0 | -
Positive Finite value | --inf |
- π | -
Negative Finite value | --inf |
- -π | -
Finite value | -+inf |
- 0.0 | -
+inf |
- Finite value | -π/2 | -
-inf |
- Finite value | --π/2 | -
+inf |
- -inf |
- ¾π | -
-inf |
- -inf |
- -¾π | -
+inf |
- +inf |
- π/4 | -
-inf |
- +inf |
- -π/4 | -
X | -ATANH(X) | -
---|---|
+inf |
- NaN |
-
-inf |
- NaN |
-
NaN |
- NaN |
-
X < -1 | -Error | -
X > 1 | -Error | -
X | -CBRT(X) | -
---|---|
+inf |
- inf |
-
-inf |
- -inf |
-
NaN |
- NaN |
-
0 |
- 0 |
-
NULL |
- NULL |
-
X | -CEIL(X) | -
---|---|
2.0 | -2.0 | -
2.3 | -3.0 | -
2.8 | -3.0 | -
2.5 | -3.0 | -
-2.3 | --2.0 | -
-2.8 | --2.0 | -
-2.5 | --2.0 | -
0 | -0 | -
+inf |
- +inf |
-
-inf |
- -inf |
-
NaN |
- NaN |
-
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
-
---|---|---|---|---|---|---|---|---|
OUTPUT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
X | -COS(X) | -
---|---|
+inf |
- NaN |
-
-inf |
- NaN |
-
NaN |
- NaN |
-
X | -COSH(X) | -
---|---|
+inf |
- +inf |
-
-inf |
- +inf |
-
NaN |
- NaN |
-
X | -COT(X) | -
---|---|
+inf |
- NaN |
-
-inf |
- NaN |
-
NaN |
- NaN |
-
0 |
- Error |
-
NULL |
- NULL |
-
X | -COTH(X) | -
---|---|
+inf |
- 1 |
-
-inf |
- -1 |
-
NaN |
- NaN |
-
0 |
- Error |
-
NULL |
- NULL |
-
X | -CSC(X) | -
---|---|
+inf |
- NaN |
-
-inf |
- NaN |
-
NaN |
- NaN |
-
0 |
- Error |
-
NULL |
- NULL |
-
X | -CSCH(X) | -
---|---|
+inf |
- 0 |
-
-inf |
- 0 |
-
NaN |
- NaN |
-
0 |
- Error |
-
NULL |
- NULL |
-
X | -Y | -DIV(X, Y) | -
---|---|---|
20 | -4 | -5 | -
12 | --7 | --1 | -
20 | -3 | -6 | -
0 | -20 | -0 | -
20 | -0 | -Error | -
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC |
-
---|---|---|---|---|---|---|
INT32 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC |
INT64 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC |
UINT32 | INT64 | INT64 | UINT64 | UINT64 | NUMERIC | BIGNUMERIC |
UINT64 | ERROR | ERROR | UINT64 | UINT64 | NUMERIC | BIGNUMERIC |
NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | BIGNUMERIC |
BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC |
X | -EXP(X) | -
---|---|
0.0 | -1.0 | -
+inf |
- +inf |
-
-inf |
- 0.0 | -
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
-
---|---|---|---|---|---|---|---|---|
OUTPUT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
X | -FLOOR(X) | -
---|---|
2.0 | -2.0 | -
2.3 | -2.0 | -
2.8 | -2.0 | -
2.5 | -2.0 | -
-2.3 | --3.0 | -
-2.8 | --3.0 | -
-2.5 | --3.0 | -
0 | -0 | -
+inf |
- +inf |
-
-inf |
- -inf |
-
NaN |
- NaN |
-
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
-
---|---|---|---|---|---|---|---|---|
OUTPUT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
X1,...,XN | -GREATEST(X1,...,XN) | -
---|---|
3,5,1 | -5 | -
X | -Y | -IEEE_DIVIDE(X, Y) | -
---|---|---|
20.0 | -4.0 | -5.0 | -
0.0 | -25.0 | -0.0 | -
25.0 | -0.0 | -+inf |
-
-25.0 | -0.0 | --inf |
-
0.0 | -0.0 | -NaN |
-
0.0 | -NaN |
- NaN |
-
NaN |
- 0.0 | -NaN |
-
+inf |
- +inf |
- NaN |
-
-inf |
- -inf |
- NaN |
-
X | -IS_INF(X) | -
---|---|
+inf |
- TRUE |
-
-inf |
- TRUE |
-
25 | -FALSE |
-
X | -IS_NAN(X) | -
---|---|
NaN |
- TRUE |
-
25 | -FALSE |
-
X1,...,XN | -LEAST(X1,...,XN) | -
---|---|
3,5,1 | -1 | -
X | -LN(X) | -
---|---|
1.0 | -0.0 | -
+inf |
- +inf |
-
X < 0 |
- Error | -
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
-
---|---|---|---|---|---|---|---|---|
OUTPUT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
X | -Y | -LOG(X, Y) | -
---|---|---|
100.0 | -10.0 | -2.0 | -
-inf |
- Any value | -NaN |
-
Any value | -+inf |
- NaN |
-
+inf |
- 0.0 < Y < 1.0 | --inf |
-
+inf |
- Y > 1.0 | -+inf |
-
X <= 0 | -Any value | -Error | -
Any value | -Y <= 0 | -Error | -
Any value | -1.0 | -Error | -
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
-
---|---|---|---|---|---|---|---|---|
INT32 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
INT64 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
UINT32 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
UINT64 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
FLOAT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE |
DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE |
X | -LOG10(X) | -
---|---|
100.0 | -2.0 | -
-inf |
- NaN |
-
+inf |
- +inf |
-
X <= 0 | -Error | -
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
-
---|---|---|---|---|---|---|---|---|
OUTPUT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
X | -Y | -MOD(X, Y) | -
---|---|---|
25 | -12 | -1 | -
25 | -0 | -Error | -
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC |
-
---|---|---|---|---|---|---|
INT32 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC |
INT64 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC |
UINT32 | INT64 | INT64 | UINT64 | UINT64 | NUMERIC | BIGNUMERIC |
UINT64 | ERROR | ERROR | UINT64 | UINT64 | NUMERIC | BIGNUMERIC |
NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | BIGNUMERIC |
BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC |
X | -Y | -POW(X, Y) | +Category | +Functions | +Description |
---|---|---|---|---|---|
2.0 | -3.0 | -8.0 | -|||
1.0 | -Any value including NaN |
- 1.0 | -|||
Any value including NaN |
- 0 | -1.0 | -|||
-1.0 | -+inf |
- 1.0 | -|||
-1.0 | --inf |
- 1.0 | -|||
ABS(X) < 1 | --inf |
- +inf |
- |||
ABS(X) > 1 | --inf |
- 0.0 | -|||
ABS(X) < 1 | -+inf |
- 0.0 | +Constructors | +
+ ST_GEOGPOINT + ST_MAKELINE + ST_MAKEPOLYGON + ST_MAKEPOLYGONORIENTED
+ |
+ + Functions that build new + geography values from coordinates + or existing geographies. + |
ABS(X) > 1 | -+inf |
- +inf |
+ Parsers | +
+ ST_GEOGFROM + ST_GEOGFROMGEOJSON + ST_GEOGFROMKML + ST_GEOGFROMTEXT + ST_GEOGFROMWKB + ST_GEOGPOINTFROMGEOHASH + |
+ + Functions that create geographies + from an external format such as + WKT and + GeoJSON. + |
-inf |
- Y < 0 | -0.0 | +Formatters | +
+ ST_ASBINARY + ST_ASGEOJSON + ST_ASKML + ST_ASTEXT + ST_GEOHASH
+ |
+ + Functions that export geographies + to an external format such as WKT. + |
-inf |
- Y > 0 | --inf if Y is an odd integer, +inf otherwise |
+ Transformations | +
+ ST_ACCUM (Aggregate)+ ST_BOUNDARY + ST_BUFFER + ST_BUFFERWITHTOLERANCE + ST_CENTROID + ST_CENTROID_AGG (Aggregate)+ ST_CLOSESTPOINT + ST_CONVEXHULL + ST_DIFFERENCE + ST_EXTERIORRING + ST_INTERIORRINGS + ST_INTERSECTION + ST_LINEINTERPOLATEPOINT + ST_LINESUBSTRING + ST_SIMPLIFY + ST_SNAPTOGRID + ST_UNION + ST_UNION_AGG (Aggregate)+ |
+ + Functions that generate a new + geography based on input. + |
+inf |
- Y < 0 | -0 | +Accessors | +
+ ST_DIMENSION + ST_DUMP + ST_DUMPPOINTS + ST_ENDPOINT + ST_GEOMETRYTYPE + ST_ISCLOSED + ST_ISCOLLECTION + ST_ISEMPTY + ST_ISRING + ST_NPOINTS + ST_NUMGEOMETRIES + ST_NUMPOINTS + ST_POINTN + ST_STARTPOINT + ST_X + ST_Y + |
+ + Functions that provide access to + properties of a geography without + side-effects. + |
+inf |
- Y > 0 | -+inf |
+ Predicates | +
+ ST_CONTAINS + ST_COVEREDBY + ST_COVERS + ST_DISJOINT + ST_DWITHIN + ST_EQUALS + ST_INTERSECTS + ST_INTERSECTSBOX + ST_TOUCHES + ST_WITHIN + |
+
+ Functions that return TRUE or
+ FALSE for some spatial
+ relationship between two
+ geographies or some property of
+ a geography. These functions
+ are commonly used in filter
+ clauses.
+ |
Finite value < 0 | -Non-integer | -Error | +Measures | +
+ ST_ANGLE + ST_AREA + ST_AZIMUTH + ST_BOUNDINGBOX + ST_DISTANCE + ST_EXTENT (Aggregate)+ ST_HAUSDORFFDISTANCE + ST_LINELOCATEPOINT + ST_LENGTH + ST_MAXDISTANCE + ST_PERIMETER + |
+ + Functions that compute measurements + of one or more geographies. + |
0 | -Finite value < 0 | -Error | +Clustering | +
+ ST_CLUSTERDBSCAN
+ |
+ + Functions that perform clustering on geographies. + |
Name | +Summary | +
---|
ST_ACCUM
+
+ |
+
+ Aggregates GEOGRAPHY values into an array of
+ GEOGRAPHY elements.
+ |
+|||||||||
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+ ST_ANGLE
+
+ |
+
+ Takes three point GEOGRAPHY values, which represent two
+ intersecting lines, and returns the angle between these lines.
+ |
---|---|---|---|---|---|---|---|---|---|---|
INT32 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
INT64 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
UINT32 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
UINT64 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
FLOAT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | ||
DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE |
ST_AREA
-### `POWER`
+GEOGRAPHY
value.
+ ST_ASBINARY
-**Description**
+GEOGRAPHY
value to a
+ BYTES
WKB geography value.
+ ST_ASGEOJSON
-[pow]: #pow
+GEOGRAPHY
value to a STRING
+ GeoJSON geography value.
+ ST_ASKML
-```
-RAND()
-```
+GEOGRAPHY
value to a STRING
+ KML geometry value.
+ ST_ASTEXT
-Generates a pseudo-random value of type `DOUBLE` in
-the range of [0, 1), inclusive of 0 and exclusive of 1.
+GEOGRAPHY
value to a
+ STRING
WKT geography value.
+ ST_AZIMUTH
-```
-ROUND(X [, N])
-```
+GEOGRAPHY
values.
+ ST_BOUNDARY
-If only X is present, rounds X to the nearest integer. If N is present,
-rounds X to N decimal places after the decimal point. If N is negative,
-rounds off digits to the left of the decimal point. Rounds halfway cases
-away from zero. Generates an error if overflow occurs.
+GEOGRAPHY
value.
+ Expression | -Return Value | -
---|---|
ROUND(2.0) |
- 2.0 | -
ROUND(2.3) |
- 2.0 | -
ROUND(2.8) |
- 3.0 | -
ROUND(2.5) |
- 3.0 | -
ROUND(-2.3) |
- -2.0 | -
ROUND(-2.8) |
- -3.0 | -
ROUND(-2.5) |
- -3.0 | -
ROUND(0) |
- 0 | -
ROUND(+inf) |
- +inf |
-
ROUND(-inf) |
- -inf |
-
ROUND(NaN) |
- NaN |
-
ROUND(123.7, -1) |
- 120.0 | -
ROUND(1.235, 2) |
- 1.24 | -
ST_BOUNDINGBOX
-**Return Data Type**
+GEOGRAPHY
value.
+ ST_BUFFER
+
+ |
+
+ Gets the buffer around a GEOGRAPHY value, using a specific
+ number of segments.
+ |
+|||||||||
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+ ST_BUFFERWITHTOLERANCE
+
+ |
+
+ Gets the buffer around a GEOGRAPHY value, using tolerance.
+ |
---|---|---|---|---|---|---|---|---|---|---|
OUTPUT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
ST_CENTROID
-### `SAFE_ADD`
+GEOGRAPHY
value.
+ ST_CLOSESTPOINT
-**Description**
+GEOGRAPHY
value which is closest to any
+ point in a second GEOGRAPHY
value.
+ ST_CLUSTERDBSCAN
-X | -Y | -SAFE_ADD(X, Y) | -
---|---|---|
5 | -4 | -9 | -
GEOGRAPHY
values and
+ produces a 0-based cluster number for this row.
+ ST_CONTAINS
-
+ Checks if one GEOGRAPHY value contains another
+ GEOGRAPHY value.
+ |
+
-
||||||||||
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+ ST_CONVEXHULL
+
+ |
+
+ Returns the convex hull for a GEOGRAPHY value.
+ |
---|---|---|---|---|---|---|---|---|---|---|
INT32 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
INT64 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
UINT32 | INT64 | INT64 | UINT64 | UINT64 | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
UINT64 | ERROR | ERROR | UINT64 | UINT64 | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
FLOAT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | ||
DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE |
ST_COVEREDBY
-### `SAFE_DIVIDE`
+GEOGRAPHY
value are on the boundary
+ or interior of another GEOGRAPHY
value.
+ ST_COVERS
-**Description**
+GEOGRAPHY
value are on the boundary
+ or interior of another GEOGRAPHY
value.
+ ST_DIFFERENCE
-X | -Y | -SAFE_DIVIDE(X, Y) | -
---|---|---|
20 | -4 | -5 | -
0 | -20 | -0 |
-
20 | -0 | -NULL |
-
+ Gets the point set difference between two GEOGRAPHY values.
+ |
+
-
||||||||||
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+ ST_DIMENSION
+
+ |
+
+ Gets the dimension of the highest-dimensional element in a
+ GEOGRAPHY value.
+ |
---|---|---|---|---|---|---|---|---|---|---|
INT32 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
INT64 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
UINT32 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
UINT64 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
FLOAT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | ||
DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE |
ST_DISJOINT
-### `SAFE_MULTIPLY`
+GEOGRAPHY
values are disjoint (do not intersect).
+ ST_DISTANCE
-**Description**
+GEOGRAPHY
+ values.
+ ST_DUMP
-X | -Y | -SAFE_MULTIPLY(X, Y) | -
---|---|---|
20 | -4 | -80 | -
GEOGRAPHY
components in a
+ GEOGRAPHY
value.
+ ST_DUMPPOINTS
-
+ Produces an array of GEOGRAPHY points with all points, line
+ vertices, and polygon vertices in a GEOGRAPHY value.
+ |
+
-
||||||||||
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+ ST_DWITHIN
+
+ |
+
+ Checks if any points in two GEOGRAPHY values are within a given
+ distance.
+ |
---|---|---|---|---|---|---|---|---|---|---|
INT32 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
INT64 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
UINT32 | INT64 | INT64 | UINT64 | UINT64 | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
UINT64 | ERROR | ERROR | UINT64 | UINT64 | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
FLOAT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | ||
DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE |
ST_ENDPOINT
-### `SAFE_NEGATE`
+GEOGRAPHY
value.
+ ST_EQUALS
-**Description**
+GEOGRAPHY
values represent the same
+ GEOGRAPHY
value.
+ ST_EXTENT
-X | -SAFE_NEGATE(X) | -
---|---|
+1 | --1 | -
-1 | -+1 | -
0 | -0 | -
GEOGRAPHY
values.
+ ST_EXTERIORRING
-
+ Returns a linestring GEOGRAPHY value that corresponds to the
+ outermost ring of a polygon GEOGRAPHY value.
+ |
+
-
||||||||||
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+ ST_GEOGFROM
+
+ |
+
+ Converts a STRING or BYTES value
+ into a GEOGRAPHY value.
+ |
---|---|---|---|---|---|---|---|---|---|---|
OUTPUT | INT32 | INT64 | ERROR | ERROR | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
ST_GEOGFROMGEOJSON
-### `SAFE_SUBTRACT`
+STRING
GeoJSON geometry value into a
+ GEOGRAPHY
value.
+ ST_GEOGFROMKML
-**Description**
+STRING
KML geometry value into a
+ GEOGRAPHY
value.
+ ST_GEOGFROMTEXT
-X | -Y | -SAFE_SUBTRACT(X, Y) | -
---|---|---|
5 | -4 | -1 | -
STRING
WKT geometry value into a
+ GEOGRAPHY
value.
+ ST_GEOGFROMWKB
-
+ Converts a BYTES or hexadecimal-text STRING WKT
+ geometry value into a GEOGRAPHY value.
+ |
+
-
||||||||||
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+ ST_GEOGPOINT
+
+ |
+
+ Creates a point GEOGRAPHY value for a given longitude and
+ latitude.
+ |
---|---|---|---|---|---|---|---|---|---|---|
INT32 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
INT64 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
UINT32 | INT64 | INT64 | INT64 | INT64 | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
UINT64 | ERROR | ERROR | INT64 | INT64 | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
FLOAT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | ||
DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE |
ST_GEOGPOINTFROMGEOHASH
-### `SEC`
+GEOGRAPHY
value that is in the middle of a
+ bounding box defined in a STRING
GeoHash value.
+ ST_GEOHASH
-**Description**
+GEOGRAPHY
value to a STRING
+ GeoHash value.
+ ST_GEOMETRYTYPE
-X | -SEC(X) | -
---|---|
+inf |
- NaN |
-
-inf |
- NaN |
-
NaN |
- NaN |
-
NULL |
- NULL |
-
GEOGRAPHY
value.
+ ST_HAUSDORFFDISTANCE
-`DOUBLE`
+ST_INTERIORRINGS
-```sql
-SELECT SEC(100) AS a, SEC(-1) AS b;
+GEOGRAPHY
value.
+ ST_INTERSECTION
-[conversion-rules]: https://github.com/google/zetasql/blob/master/docs/conversion_rules.md#conversion_rules
+GEOGRAPHY
values.
+ ST_INTERSECTS
-```
-SECH(X)
-```
+GEOGRAPHY
+ values.
+ ST_INTERSECTSBOX
-Computes the hyperbolic secant for the angle of `X`, where `X` is specified
-in radians. `X` can be any data type
-that [coerces to `DOUBLE`][conversion-rules].
-Never produces an error.
+GEOGRAPHY
value intersects a rectangle.
+ X | -SECH(X) | -
---|---|
+inf |
- 0 |
-
-inf |
- 0 |
-
NaN |
- NaN |
-
NULL |
- NULL |
-
ST_ISCLOSED
-**Return Data Type**
+GEOGRAPHY
value are closed.
+ ST_ISCOLLECTION
-**Example**
+GEOGRAPHY
value.
+ ST_ISEMPTY
-/*----------------+----------------+---------------------*
- | a | b | c |
- +----------------+----------------+---------------------+
- | 0.88681888397 | 0.265802228834 | 7.4401519520417E-44 |
- *----------------+----------------+---------------------*/
-```
+GEOGRAPHY
value is empty.
+ ST_ISRING
-### `SIGN`
+GEOGRAPHY
value is a closed, simple
+ linestring.
+ ST_LENGTH
-**Description**
+GEOGRAPHY
value.
+ ST_LINEINTERPOLATEPOINT
-X | -SIGN(X) | -
---|---|
25 | -+1 | -
0 | -0 | -
-25 | --1 | -
NaN | -NaN | -
GEOGRAPHY
+ value.
+ ST_LINELOCATEPOINT
-INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+
+
+ Gets a section of a linestring GEOGRAPHY value between the
+ start point and a point GEOGRAPHY value.
+ |
---|---|---|---|---|---|---|---|---|---|
OUTPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
X | -SIN(X) | -
---|---|
+inf |
- NaN |
-
-inf |
- NaN |
-
NaN |
- NaN |
-
X | -SINH(X) | -
---|---|
+inf |
- +inf |
-
-inf |
- -inf |
-
NaN |
- NaN |
-
X | -SQRT(X) | -
---|---|
25.0 |
- 5.0 |
-
+inf |
- +inf |
-
X < 0 |
- Error | -
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
-
---|---|---|---|---|---|---|---|---|
OUTPUT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
ST_LINESUBSTRING
-**Description**
+ST_MAKELINE
-X | -TAN(X) | -
---|---|
+inf |
- NaN |
-
-inf |
- NaN |
-
NaN |
- NaN |
-
GEOGRAPHY
value by concatenating the point
+ and linestring vertices of GEOGRAPHY
values.
+ ST_MAKEPOLYGON
-```
-TANH(X)
-```
+GEOGRAPHY
value by combining
+ a polygon shell with polygon holes.
+ ST_MAKEPOLYGONORIENTED
-Computes the hyperbolic tangent of X where X is specified in radians. Does not
-fail.
+GEOGRAPHY
value, using an array of
+ linestring GEOGRAPHY
values. The vertex ordering of each
+ linestring determines the orientation of each polygon ring.
+ X | -TANH(X) | -
---|---|
+inf |
- 1.0 | -
-inf |
- -1.0 | -
NaN |
- NaN |
-
ST_MAXDISTANCE
-### `TRUNC`
+GEOGRAPHY
values.
+ ST_NPOINTS
-**Description**
+ST_NUMPOINTS
.
+ ST_NUMGEOMETRIES
-X | -TRUNC(X) | -
---|---|
2.0 | -2.0 | -
2.3 | -2.0 | -
2.8 | -2.0 | -
2.5 | -2.0 | -
-2.3 | --2.0 | -
-2.8 | --2.0 | -
-2.5 | --2.0 | -
0 | -0 | -
+inf |
- +inf |
-
-inf |
- -inf |
-
NaN |
- NaN |
-
GEOGRAPHY
value.
+ ST_NUMPOINTS
-
+ Gets the number of vertices in the a GEOGRAPHY value.
+ |
+
-
||||||||
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
-
---|---|---|---|---|---|---|---|---|
OUTPUT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ST_PERIMETER
- |
GEOGRAPHY
value.
+ ST_POINTN
-ZetaSQL supports navigation functions.
-Navigation functions are a subset window functions. To create a
-window function call and learn about the syntax for window functions,
-see [Window function_calls][window-function-calls].
+GEOGRAPHY
+ value.
+ ST_SIMPLIFY
-For all navigation functions, the result data type is the same type as
-`value_expression`.
+GEOGRAPHY
value into a simplified
+ GEOGRAPHY
value, using tolerance.
+ ST_SNAPTOGRID
-Name | -Summary | -
+ Produces a GEOGRAPHY value, where each vertex has
+ been snapped to a longitude/latitude grid.
+ |
+
---|---|---|
FIRST_VALUE
+ | ST_STARTPOINT
|
- Gets a value for the first row in the current window frame.
+ Gets the first point of a linestring GEOGRAPHY value.
|
LAG
+ | ST_TOUCHES
|
- Gets a value for a preceding row.
+ Checks if two GEOGRAPHY values intersect and their interiors
+ have no elements in common.
|
LAST_VALUE
+ | ST_UNION
|
- Gets a value for the last row in the current window frame.
+ Gets the point set union of multiple GEOGRAPHY values.
|
LEAD
+ | ST_UNION_AGG
|
- Gets a value for a subsequent row.
+ Aggregates over GEOGRAPHY values and gets their
+ point set union.
|
NTH_VALUE
+ | ST_WITHIN
|
- Gets a value for the Nth row of the current window frame.
+ Checks if one GEOGRAPHY value contains another
+ GEOGRAPHY value.
|
PERCENTILE_CONT
+ | ST_X
|
- Computes the specified percentile for a value, using
- linear interpolation.
+ Gets the longitude from a point GEOGRAPHY value.
|
PERCENTILE_DISC
+ | ST_Y
|
- Computes the specified percentile for a discrete value.
+ Gets the latitude from a point GEOGRAPHY value.
|
INPUT | NUMERIC | BIGNUMERIC | DOUBLE |
-
---|---|---|---|
NUMERIC | NUMERIC | BIGNUMERIC | DOUBLE |
BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | DOUBLE |
DOUBLE | DOUBLE | DOUBLE | DOUBLE |
Name | -Summary | -
---|---|
FARM_FINGERPRINT
+**Example**
- |
-
- Computes the fingerprint of a STRING or
- BYTES value, using the FarmHash Fingerprint64 algorithm.
- |
-
MD5
+```sql
+SELECT
+ ST_GEOGPOINT(i, i) AS p,
+ ST_CONTAINS(ST_GEOGFROMTEXT('POLYGON((1 1, 20 1, 10 20, 1 1))'),
+ ST_GEOGPOINT(i, i)) AS `contains`
+FROM UNNEST([0, 1, 10]) AS i;
- |
-
- Computes the hash of a STRING or
- BYTES value, using the MD5 algorithm.
- |
-
SHA1
+[st_covers]: #st_covers
- |
-
- Computes the hash of a STRING or
- BYTES value, using the SHA-1 algorithm.
- |
-
SHA256
-
- |
-
- Computes the hash of a STRING or
- BYTES value, using the SHA-256 algorithm.
- |
-
SHA512
-
- |
-
- Computes the hash of a STRING or
- BYTES value, using the SHA-512 algorithm.
- |
-
Name | -Summary | -
---|---|
ASCII
+```sql
+WITH example AS (
+ SELECT ST_GEOGFROMTEXT('POINT(0 0)') AS geography
+ UNION ALL
+ SELECT ST_GEOGFROMTEXT('MULTIPOINT(0 0, 1 1)') AS geography
+ UNION ALL
+ SELECT ST_GEOGFROMTEXT('GEOMETRYCOLLECTION(POINT(0 0), LINESTRING(1 2, 2 1))'))
+SELECT
+ geography AS original_geography,
+ ST_DUMP(geography) AS dumped_geographies
+FROM example
- |
-
- Gets the ASCII code for the first character or byte in a STRING
- or BYTES value.
- |
-
BYTE_LENGTH
+The following example shows how `ST_DUMP` with the dimension argument only
+returns simple geographies of the given dimension.
- |
-
- Gets the number of BYTES in a STRING or
- BYTES value.
- |
-
CHAR_LENGTH
+/*-------------------------------------+------------------------------*
+ | original_geographies | dumped_geographies |
+ +-------------------------------------+------------------------------+
+ | GEOMETRYCOLLECTION(POINT(0 0), | [LINESTRING(1 2, 2 1)] |
+ | LINESTRING(1 2, 2 1)) | |
+ *-------------------------------------+------------------------------*/
+```
- |
-
- Gets the number of characters in a STRING value.
- |
-
CHARACTER_LENGTH
+```sql
+ST_DUMPPOINTS(geography)
+```
- |
-
- Synonym for CHAR_LENGTH .
- |
-
CHR
+Takes an input geography and returns all of its points, line vertices, and
+polygon vertices as an array of point geographies.
- |
- - Converts a Unicode code point to a character. - | -
CODE_POINTS_TO_BYTES
+`ARRAY |
-
- Converts an array of extended ASCII code points to a
- BYTES value.
- |
-
CODE_POINTS_TO_STRING
+```sql
+WITH example AS (
+ SELECT ST_GEOGFROMTEXT('POINT(0 0)') AS geography
+ UNION ALL
+ SELECT ST_GEOGFROMTEXT('MULTIPOINT(0 0, 1 1)') AS geography
+ UNION ALL
+ SELECT ST_GEOGFROMTEXT('GEOMETRYCOLLECTION(POINT(0 0), LINESTRING(1 2, 2 1))'))
+SELECT
+ geography AS original_geography,
+ ST_DUMPPOINTS(geography) AS dumped_points_geographies
+FROM example
- |
-
- Converts an array of extended ASCII code points to a
- STRING value.
- |
-
COLLATE
+### `ST_DWITHIN`
- |
-
- Combines a STRING value and a collation specification into a
- collation specification-supported STRING value.
- |
-
CONCAT
+**Description**
- |
-
- Concatenates one or more STRING or BYTES
- values into a single result.
- |
-
EDIT_DISTANCE
+The optional `use_spheroid` parameter determines how this function measures
+distance. If `use_spheroid` is `FALSE`, the function measures distance on the
+surface of a perfect sphere.
- |
-
- Computes the Levenshtein distance between two STRING
- or BYTES values.
- |
-
ENDS_WITH
+**Return type**
- |
-
- Checks if a STRING or BYTES value is the suffix
- of another value.
- |
-
FORMAT
+[wgs84-link]: https://en.wikipedia.org/wiki/World_Geodetic_System
- |
-
- Formats data and produces the results as a STRING value.
- |
-
FROM_BASE32
+```sql
+ST_ENDPOINT(linestring_geography)
+```
- |
-
- Converts a base32-encoded STRING value into a
- BYTES value.
- |
-
FROM_BASE64
+Returns the last point of a linestring geography as a point geography. Returns
+an error if the input is not a linestring or if the input is empty. Use the
+`SAFE` prefix to obtain `NULL` for invalid input instead of an error.
- |
-
- Converts a base64-encoded STRING value into a
- BYTES value.
- |
-
FROM_HEX
+Point `GEOGRAPHY`
- |
-
- Converts a hexadecimal-encoded STRING value into a
- BYTES value.
- |
-
INITCAP
+```sql
+SELECT ST_ENDPOINT(ST_GEOGFROMTEXT('LINESTRING(1 1, 2 1, 3 2, 3 3)')) last
- |
-
- Formats a STRING as proper case, which means that the first
- character in each word is uppercase and all other characters are lowercase.
- |
-
INSTR
+### `ST_EQUALS`
- |
- - Finds the position of a subvalue inside another value, optionally starting - the search at a given offset or occurrence. - | -
LEFT
+**Description**
- |
-
- Gets the specified leftmost portion from a STRING or
- BYTES value.
- |
-
LENGTH
+`GEOGRAPHY` value. More precisely, this means that
+one of the following conditions holds:
++ `ST_COVERS(geography_1, geography_2) = TRUE` and `ST_COVERS(geography_2,
+ geography_1) = TRUE`
++ Both `geography_1` and `geography_2` are empty.
- |
-
- Gets the length of a STRING or BYTES value.
- |
-
LOWER
+**Constraints**
- |
-
- Formats alphabetic characters in a STRING value as
- lowercase.
- - Formats ASCII characters in a BYTES value as
- lowercase.
- |
-
LPAD
+**Return type**
- |
-
- Prepends a STRING or BYTES value with a pattern.
- |
-
LTRIM
+### `ST_EXTENT`
- |
-
- Identical to the TRIM function, but only removes leading
- characters.
- |
-
NORMALIZE
+**Description**
- |
-
- Case-sensitively normalizes the characters in a STRING value.
- |
-
NORMALIZE_AND_CASEFOLD
+Caveats:
- |
-
- Case-insensitively normalizes the characters in a STRING value.
- |
-
OCTET_LENGTH
+**Return type**
- |
-
- Alias for BYTE_LENGTH .
- |
-
REGEXP_CONTAINS
+Bounding box parts:
- |
- - Checks if a value is a partial match for a regular expression. - | -
REGEXP_EXTRACT
+**Example**
- |
- - Produces a substring that matches a regular expression. - | -
REGEXP_EXTRACT_ALL
+/*----------------------------------------------*
+ | box |
+ +----------------------------------------------+
+ | {xmin:172, ymin:46, xmax:243, ymax:70} |
+ *----------------------------------------------*/
+```
- |
- - Produces an array of all substrings that match a - regular expression. - | -
REGEXP_INSTR
+[st-boundingbox]: #st_boundingbox
- |
- - Finds the position of a regular expression match in a value, optionally - starting the search at a given offset or occurrence. - | -
REGEXP_MATCH
+```sql
+ST_EXTERIORRING(polygon_geography)
+```
- |
- - (Deprecated) Checks if a value is a full match for a regular expression. - | -
REGEXP_REPLACE
+Returns a linestring geography that corresponds to the outermost ring of a
+polygon geography.
- |
-
- Produces a STRING value where all substrings that match a
- regular expression are replaced with a specified value.
- |
-
REPEAT
+Use the `SAFE` prefix to return `NULL` for invalid input instead of an error.
- |
-
- Produces a STRING or BYTES value that consists of
- an original value, repeated.
- |
-
REPLACE
++ Linestring `GEOGRAPHY`
++ Empty `GEOGRAPHY`
- |
-
- Replaces all occurrences of a pattern with another pattern in a
- STRING or BYTES value.
- |
-
REVERSE
+```sql
+WITH geo as
+ (SELECT ST_GEOGFROMTEXT('POLYGON((0 0, 1 4, 2 2, 0 0))') AS g UNION ALL
+ SELECT ST_GEOGFROMTEXT('''POLYGON((1 1, 1 10, 5 10, 5 1, 1 1),
+ (2 2, 3 4, 2 4, 2 2))''') as g)
+SELECT ST_EXTERIORRING(g) AS ring FROM geo;
- |
-
- Reverses a STRING or BYTES value.
- |
-
RIGHT
+### `ST_GEOGFROM`
- |
-
- Gets the specified rightmost portion from a STRING or
- BYTES value.
- |
-
RPAD
+**Description**
- |
-
- Appends a STRING or BYTES value with a pattern.
- |
-
RTRIM
+If `expression` represents a `STRING` value, it must be a valid
+`GEOGRAPHY` representation in one of the following formats:
- |
-
- Identical to the TRIM function, but only removes trailing
- characters.
- |
-
SAFE_CONVERT_BYTES_TO_STRING
+If `expression` represents a `BYTES` value, it must be a valid `GEOGRAPHY`
+binary expression in WKB format. To learn more about this format and the
+requirements to use it, see [ST_GEOGFROMWKB][st-geogfromwkb].
- |
-
- Converts a BYTES value to a STRING value and
- replace any invalid UTF-8 characters with the Unicode replacement character,
- U+FFFD .
- |
-
SOUNDEX
+**Return type**
- |
-
- Gets the Soundex codes for words in a STRING value.
- |
-
SPLIT
+**Examples**
- |
-
- Splits a STRING or BYTES value, using a delimiter.
- |
-
STARTS_WITH
+```sql
+SELECT ST_GEOGFROM('POLYGON((0 0, 0 2, 2 2, 2 0, 0 0))') AS WKT_format
- |
-
- Checks if a STRING or BYTES value is a
- prefix of another value.
- |
-
STRPOS
+This takes a WKB-formatted hexadecimal-encoded string and returns a
+`GEOGRAPHY` point:
- |
- - Finds the position of the first occurrence of a subvalue inside another - value. - | -
SUBSTR
+/*----------------*
+ | WKB_format |
+ +----------------+
+ | POINT(2 4) |
+ *----------------*/
+```
- |
-
- Gets a portion of a STRING or BYTES value.
- |
-
SUBSTRING
+```sql
+SELECT ST_GEOGFROM('010100000000000000000000400000000000001040')-AS WKB_format
- |
- Alias for SUBSTR |
-
TO_BASE32
+This takes a GeoJSON-formatted string and returns a `GEOGRAPHY` polygon:
- |
-
- Converts a BYTES value to a
- base32-encoded STRING value.
- |
-
TO_BASE64
+/*-----------------------------------------*
+ | GEOJSON_format |
+ +-----------------------------------------+
+ | POLYGON((2 0, 2 2, 1 2, 0 2, 0 0, 2 0)) |
+ *-----------------------------------------*/
+```
- |
-
- Converts a BYTES value to a
- base64-encoded STRING value.
- |
-
TO_CODE_POINTS
+[st-geogfromwkb]: #st_geogfromwkb
- |
-
- Converts a STRING or BYTES value into an array of
- extended ASCII code points.
- |
-
TO_HEX
+### `ST_GEOGFROMGEOJSON`
- |
-
- Converts a BYTES value to a
- hexadecimal STRING value.
- |
-
TRANSLATE
+**Description**
- |
- - Within a value, replaces each source character with the corresponding - target character. - | -
TRIM
+`ST_GEOGFROMGEOJSON` accepts input that is [RFC 7946][geojson-spec-link]
+compliant.
- |
-
- Removes the specified leading and trailing Unicode code points or bytes
- from a STRING or BYTES value.
- |
-
UNICODE
+A ZetaSQL `GEOGRAPHY` has spherical
+geodesic edges, whereas a GeoJSON `Geometry` object explicitly has planar edges.
+To convert between these two types of edges, ZetaSQL adds additional
+points to the line where necessary so that the resulting sequence of edges
+remains within 10 meters of the original edge.
- |
- - Gets the Unicode code point for the first character in a value. - | -
UPPER
+**Constraints**
- |
-
- Formats alphabetic characters in a STRING value as
- uppercase.
- - Formats ASCII characters in a BYTES value as
- uppercase.
- |
-
Description | -Statement | -Result | -
---|---|---|
Simple integer | -FORMAT('%d', 10) | -10 | -
Integer with left blank padding | -FORMAT('|%10d|', 11) | -| 11| | -
Integer with left zero padding | -FORMAT('+%010d+', 12) | -+0000000012+ | -
Integer with commas | -FORMAT("%'d", 123456789) | -123,456,789 | -
STRING | -FORMAT('-%s-', 'abcd efg') | --abcd efg- | -
DOUBLE | -FORMAT('%f %E', 1.1, 2.2) | -1.100000 2.200000E+00 | -
DATE | -FORMAT('%t', date '2015-09-01') | -2015-09-01 | -
TIMESTAMP | -FORMAT('%t', timestamp '2015-09-01 12:34:56 -America/Los_Angeles') | -2015‑09‑01 19:34:56+00 | -
Specifier | -Description | -Examples | -Types | -
d or i |
- Decimal integer | -392 | -
+Returns the total length in meters of the lines in the input
+`GEOGRAPHY`.
-INT32 INT64 UINT32 UINT64 - |
-
u |
- Unsigned integer | -7235 | -
+The optional `use_spheroid` parameter determines how this function measures
+distance. If `use_spheroid` is `FALSE`, the function measures distance on the
+surface of a perfect sphere.
-UINT32 UINT64 - |
-
o |
-
- Octal
- - Note: If an INT64 value is negative, an error is produced.
- |
- 610 | -
+**Return type**
-INT32 INT64 UINT32 UINT64 - |
-
x |
-
- Hexadecimal integer
- - Note: If an INT64 value is negative, an error is produced.
- |
- 7fa | -
+`DOUBLE`
-INT32 INT64 UINT32 UINT64 - |
-
X |
-
- Hexadecimal integer (uppercase)
- - Note: If an INT64 value is negative, an error is produced.
- |
- 7FA | -
+[wgs84-link]: https://en.wikipedia.org/wiki/World_Geodetic_System
-INT32 INT64 UINT32 UINT64 +### `ST_LINEINTERPOLATEPOINT` - |
-
f |
- Decimal notation, in [-](integer part).(fractional part) for finite - values, and in lowercase for non-finite values | -392.650000 - inf - nan |
-
+```sql
+ST_LINEINTERPOLATEPOINT(linestring_geography, fraction)
+```
-NUMERIC BIGNUMERIC FLOAT DOUBLE - |
-
F |
- Decimal notation, in [-](integer part).(fractional part) for finite - values, and in uppercase for non-finite values | -392.650000 - INF - NAN |
-
+**Description**
-NUMERIC BIGNUMERIC FLOAT DOUBLE - |
-
e |
- Scientific notation (mantissa/exponent), lowercase | -3.926500e+02 - inf - nan |
-
+Gets a point at a specific fraction in a linestring GEOGRAPHY
+value.
-NUMERIC BIGNUMERIC FLOAT DOUBLE - |
-
E |
- Scientific notation (mantissa/exponent), uppercase | -3.926500E+02 - INF - NAN |
-
+**Definitions**
-NUMERIC BIGNUMERIC FLOAT DOUBLE - |
-
g |
- Either decimal notation or scientific notation, depending on the input - value's exponent and the specified precision. Lowercase. - See %g and %G behavior for details. | -392.65 - 3.9265e+07 - inf - nan |
-
++ `linestring_geography`: A linestring `GEOGRAPHY` on which the target point
+ is located.
++ `fraction`: A `DOUBLE` value that represents a fraction
+ along the linestring `GEOGRAPHY` where the target point is located.
+ This should be an inclusive value between `0` (start of the
+ linestring) and `1` (end of the linestring).
-NUMERIC BIGNUMERIC FLOAT DOUBLE - |
-
G |
- - Either decimal notation or scientific notation, depending on the input - value's exponent and the specified precision. Uppercase. - See %g and %G behavior for details. - | -
- 392.65 - 3.9265E+07 - INF - NAN - |
-
+**Details**
-NUMERIC BIGNUMERIC FLOAT DOUBLE - |
-
p |
- - - Produces a one-line printable string representing a protocol buffer - or JSON. - - See %p and %P behavior. - | -
-
-year: 2019 month: 10- - - {"month":10,"year":2019}- - |
-
+**Return Type**
-JSON PROTO - |
-
P |
- - - Produces a multi-line printable string representing a protocol buffer - or JSON. - - See %p and %P behavior. - | -
-
--year: 2019 -month: 10 -- - - -{ - "month": 10, - "year": 2019 -} -- - |
-
+**Example**
-JSON PROTO - |
-
s |
- String of characters | -sample | -
+```sql
+WITH fractions AS (
+ SELECT 0 AS fraction UNION ALL
+ SELECT 0.5 UNION ALL
+ SELECT 1 UNION ALL
+ SELECT NULL
+ )
+SELECT
+ fraction,
+ ST_LINEINTERPOLATEPOINT(ST_GEOGFROMTEXT('LINESTRING(1 1, 5 5)'), fraction)
+ AS point
+FROM fractions
-STRING - |
-
t |
-
- Returns a printable string representing the value. Often looks
- similar to casting the argument to STRING .
- See %t and %T behavior.
- |
-
- sample - 2014‑01‑01 - |
- Any type | -
T |
- - Produces a string that is a valid ZetaSQL constant with a - similar type to the value's type (maybe wider, or maybe string). - See %t and %T behavior. - | -
- 'sample' - b'bytes sample' - 1234 - 2.3 - date '2014‑01‑01' - |
- Any type | -
% |
- '%%' produces a single '%' | -% | -n/a | -
Flags | -Description | -
- |
- Left-justify within the given field width; Right justification is the -default (see width sub-specifier) | -
+ |
- Forces to precede the result with a plus or minus sign (+
-or - ) even for positive numbers. By default, only negative numbers
-are preceded with a - sign |
-
<space> | -If no sign is going to be written, a blank space is inserted before the -value | -
# |
-
|
-
0 |
- - Left-pads the number with zeroes (0) instead of spaces when padding is - specified (see width sub-specifier) | -
' |
-
- Formats integers using the appropriating grouping character. - For example: -
This flag is only relevant for decimal, hex, and octal values. - |
-
Width | -Description | -
<number> | -- Minimum number of characters to be printed. If the value to be printed - is shorter than this number, the result is padded with blank spaces. - The value is not truncated even if the result is larger - | -
* |
- - The width is not specified in the format string, but as an additional - integer value argument preceding the argument that has to be formatted - | -
Precision | -Description | -
. <number> |
-
-
|
-
.* |
- - The precision is not specified in the format string, but as an - additional integer value argument preceding the argument that has to be - formatted - | -
Type | -%p | -%P | -
PROTO | -
- PROTO input: --message ReleaseDate { - required int32 year = 1 [default=2019]; - required int32 month = 2 [default=10]; -}- Produces a one-line printable string representing a protocol buffer: -year: 2019 month: 10- |
-
- PROTO input: --message ReleaseDate { - required int32 year = 1 [default=2019]; - required int32 month = 2 [default=10]; -}- Produces a multi-line printable string representing a protocol buffer: --year: 2019 -month: 10 -- |
-
JSON | -
- JSON input: --JSON ' -{ - "month": 10, - "year": 2019 -} -'- Produces a one-line printable string representing JSON: -{"month":10,"year":2019}- |
-
- JSON input: --JSON ' -{ - "month": 10, - "year": 2019 -} -'- Produces a multi-line printable string representing JSON: --{ - "month": 10, - "year": 2019 -} -- |
-
Type | -%t | -%T | -
NULL of any type |
- NULL | -NULL | -
-
-INT32 INT64 UINT32 UINT64 - |
- 123 | -123 | -
NUMERIC | -123.0 (always with .0) - | NUMERIC "123.0" | -
FLOAT, DOUBLE | +`end_fraction` must be greater than or equal to `start_fraction`. -
- 123.0 (always with .0) - 123e+10 inf -inf NaN
- |
-
- 123.0 (always with .0) - 123e+10 - CAST("inf" AS <type>) - CAST("-inf" AS <type>) - CAST("nan" AS <type>) - |
-
STRING | -unquoted string value | -quoted string literal | -
BYTES | -
- unquoted escaped bytes - e.g. abc\x01\x02 - |
-
- quoted bytes literal - e.g. b"abc\x01\x02" - |
-
BOOL | -boolean value | -boolean value | -
ENUM | -EnumName | -"EnumName" | -
DATE | -2011-02-03 | -DATE "2011-02-03" | -
TIMESTAMP | -2011-02-03 04:05:06+00 | -TIMESTAMP "2011-02-03 04:05:06+00" | -
INTERVAL | -1-2 3 4:5:6.789 | -INTERVAL "1-2 3 4:5:6.789" YEAR TO SECOND | -
PROTO | -- one-line printable string representing a protocol buffer. - | -- quoted string literal with one-line printable string representing a - protocol buffer. - | -
ARRAY | -[value, value, ...] - where values are formatted with %t |
- [value, value, ...] - where values are formatted with %T |
-
STRUCT | -(value, value, ...) - where fields are formatted with %t |
- (value, value, ...) - where fields are formatted with %T - - Special cases: - Zero fields: STRUCT() - One field: STRUCT(value) |
-
JSON | -
- one-line printable string representing JSON. - {"name":"apple","stock":3}- |
-
- one-line printable string representing a JSON literal. - JSON '{"name":"apple","stock":3}'- |
-
Name | +Summary | +
---|---|
FARM_FINGERPRINT
-### `REGEXP_EXTRACT`
+ |
+
+ Computes the fingerprint of a STRING or
+ BYTES value, using the FarmHash Fingerprint64 algorithm.
+ |
+
MD5
-**Description**
+ |
+
+ Computes the hash of a STRING or
+ BYTES value, using the MD5 algorithm.
+ |
+
SHA1
-If the regular expression contains a capturing group (`(...)`), and there is a
-match for that capturing group, that match is returned. If there
-are multiple matches for a capturing group, the first match is returned.
+ |
+
+ Computes the hash of a STRING or
+ BYTES value, using the SHA-1 algorithm.
+ |
+
SHA256
-+ The regular expression is invalid
-+ The regular expression has more than one capturing group
+ |
+
+ Computes the hash of a STRING or
+ BYTES value, using the SHA-256 algorithm.
+ |
+
SHA512
+
+ |
+
+ Computes the hash of a STRING or
+ BYTES value, using the SHA-512 algorithm.
+ |
+
Name | +Summary | +
---|---|
HLL_COUNT.EXTRACT
+
+ |
+ + Extracts a cardinality estimate of an HLL++ sketch. + | +
HLL_COUNT.INIT
+
+ |
+ + Aggregates values of the same underlying type into a new HLL++ sketch. + | +
HLL_COUNT.MERGE
+
+ |
+ + Merges HLL++ sketches of the same underlying type into a new sketch, and + then gets the cardinality of the new sketch. + | +
HLL_COUNT.MERGE_PARTIAL
+
+ |
+ + Merges HLL++ sketches of the same underlying type into a new sketch. + | +
Name | +Summary | +
---|---|
EXTRACT
-If `length` is 0, an empty `STRING` or `BYTES` value will be
-returned. If `length` is negative, an error will be returned. If `length`
-exceeds the number of characters or bytes from `value`, the original `value`
-will be returned.
+ |
+
+ Extracts part of an INTERVAL value.
+ |
+
JUSTIFY_DAYS
-`STRING` or `BYTES`
+ |
+
+ Normalizes the day part of an INTERVAL value.
+ |
+
JUSTIFY_HOURS
-```sql
-SELECT t, len, pattern, FORMAT('%T', RPAD(t, len, pattern)) AS RPAD FROM UNNEST([
- STRUCT('abc' AS t, 8 AS len, 'def' AS pattern),
- ('abc', 5, '-'),
- ('例å', 5, 'ä¸æ–‡')
-]);
+ |
+
+ Normalizes the time part of an INTERVAL value.
+ |
+
JUSTIFY_INTERVAL
-```sql
-SELECT FORMAT('%T', t) AS t, len, FORMAT('%T', RPAD(t, len)) AS RPAD FROM UNNEST([
- STRUCT(b'abc' AS t, 5 AS len),
- (b'abc', 2),
- (b'\xab\xcd\xef', 4)
-]);
+ |
+
+ Normalizes the day and time parts of an INTERVAL value.
+ |
+
MAKE_INTERVAL
-```sql
-SELECT
- FORMAT('%T', t) AS t,
- len,
- FORMAT('%T', pattern) AS pattern,
- FORMAT('%T', RPAD(t, len, pattern)) AS RPAD
-FROM UNNEST([
- STRUCT(b'abc' AS t, 8 AS len, b'def' AS pattern),
- (b'abc', 5, b'-'),
- (b'\xab\xcd\xef', 5, b'\x00')
-]);
+ |
+
+ Constructs an INTERVAL value.
+ |
+
Category | +Functions | +Description | +
+ + Standard extractors + + | +
+
+ JSON_QUERY + JSON_VALUE + + + JSON_QUERY_ARRAY + + + JSON_VALUE_ARRAY + + |
+ + Functions that extract JSON data. + | +
+ + Legacy extractors + + | +
+
+ JSON_EXTRACT + JSON_EXTRACT_SCALAR + + + + JSON_EXTRACT_STRING_ARRAY + + |
+
+ Functions that extract JSON data. + + While these functions are supported by ZetaSQL, we recommend + using the standard extractor functions. + + |
+
Lax converters | +
+
+ LAX_BOOL + + + LAX_DOUBLE + + + LAX_INT64 + + + LAX_STRING + + |
+ + Functions that flexibly convert a JSON value to a scalar SQL value + without returning errors. + | +
Converters | +
+
+ BOOL + + + DOUBLE + + + INT64 + + + STRING + + |
+ + Functions that convert a JSON value to a scalar SQL value. + | +
Other converters | +
+
+ PARSE_JSON + + + TO_JSON + + + TO_JSON_STRING + + |
+ + Other conversion functions from or to JSON. + | +
Constructors | +
+ JSON_ARRAY + JSON_OBJECT + |
+ + Functions that create JSON. + | +
Mutators | +
+
+ JSON_ARRAY_APPEND + + + JSON_ARRAY_INSERT + + + JSON_REMOVE + + + JSON_SET + + + JSON_STRIP_NULLS + + |
+ + Functions that mutate existing JSON. + | +
Accessors | +
+
+ JSON_TYPE + + |
+ + Functions that provide access to JSON properties. + | +
Name | +Summary | +
---|---|
BOOL
-SELECT
- SUBSTR(item, 2) as example
-FROM items;
+ |
+
+ Converts a JSON boolean to a SQL BOOL value.
+ |
+
+
+ DOUBLE
-```sql
-WITH items AS
- (SELECT 'apple' as item
- UNION ALL
- SELECT 'banana' as item
- UNION ALL
- SELECT 'orange' as item)
+
+ |
+
+ Converts a JSON number to a SQL
+ DOUBLE value.
+ |
+
INT64
-/*---------*
- | example |
- +---------+
- | pp |
- | an |
- | ra |
- *---------*/
-```
+ |
+
+ Converts a JSON number to a SQL INT64 value.
+ |
+
JSON_ARRAY
-SELECT
- SUBSTR(item, -2) as example
-FROM items;
+ |
+ Creates a JSON array. | +
JSON_ARRAY_APPEND
-```sql
-WITH items AS
- (SELECT 'apple' as item
- UNION ALL
- SELECT 'banana' as item
- UNION ALL
- SELECT 'orange' as item)
+ |
+ Appends JSON data to the end of a JSON array. | +
JSON_ARRAY_INSERT
-/*---------*
- | example |
- +---------+
- | apple |
- | banana |
- | orange |
- *---------*/
-```
+ |
+ Inserts JSON data into a JSON array. | +
JSON_EXTRACT
-SELECT
- SUBSTR(item, 123) as example
-FROM items;
+ |
+
+ (Deprecated)
+ Extracts a JSON value and converts it to a SQL
+ JSON-formatted STRING
+ or
+ JSON
+
+ value.
+ |
+
JSON_EXTRACT_SCALAR
-```sql
-WITH items AS
- (SELECT 'apple' as item
- UNION ALL
- SELECT 'banana' as item
- UNION ALL
- SELECT 'orange' as item)
+ |
+
+ (Deprecated)
+ Extracts a JSON scalar value and converts it to a SQL
+ STRING value.
+ |
+
JSON_OBJECT
-/*---------*
- | example |
- +---------+
- | |
- | |
- | |
- *---------*/
-```
+ |
+ Creates a JSON object. | +
JSON_QUERY
-```sql
-SUBSTRING(value, position[, length])
-```
+ |
+
+ Extracts a JSON value and converts it to a SQL
+ JSON-formatted STRING
+ or
+ JSON
+
+ value.
+ |
+
JSON_QUERY_ARRAY
-[substr]: #substr
+ |
+
+ Extracts a JSON array and converts it to
+ a SQL ARRAY<JSON-formatted STRING>
+ or
+ ARRAY<JSON>
+
+ value.
+ |
+
JSON_REMOVE
-```sql
-TO_BASE32(bytes_expr)
-```
+ |
+ Produces JSON with the specified JSON data removed. | +
JSON_SET
-Converts a sequence of `BYTES` into a base32-encoded `STRING`. To convert a
-base32-encoded `STRING` into `BYTES`, use [FROM_BASE32][string-link-to-from-base32].
+ |
+ Inserts or replaces JSON data. | +
JSON_STRIP_NULLS
-`STRING`
+ |
+ Removes JSON nulls from JSON objects and JSON arrays. | +
JSON_TYPE
-```sql
-SELECT TO_BASE32(b'abcde\xFF') AS base32_string;
+ |
+
+ Gets the JSON type of the outermost JSON value and converts the name of
+ this type to a SQL STRING value.
+ |
+
JSON_VALUE
-[string-link-to-from-base32]: #from_base32
+ |
+
+ Extracts a JSON scalar value and converts it to a SQL
+ STRING value.
+ |
+
JSON_VALUE_ARRAY
-```sql
-TO_BASE64(bytes_expr)
-```
+ |
+
+ Extracts a JSON array of scalar values and converts it to a SQL
+ ARRAY<STRING> value.
+ |
+
LAX_BOOL
-Converts a sequence of `BYTES` into a base64-encoded `STRING`. To convert a
-base64-encoded `STRING` into `BYTES`, use [FROM_BASE64][string-link-to-from-base64].
+ |
+
+ Attempts to convert a JSON value to a SQL BOOL value.
+ |
+
+
+ LAX_DOUBLE
-**Return type**
+
+ |
+
+ Attempts to convert a JSON value to a
+ SQL DOUBLE value.
+ |
+
LAX_INT64
-**Example**
+ |
+
+ Attempts to convert a JSON value to a SQL INT64 value.
+ |
+
LAX_STRING
-/*---------------*
- | base64_string |
- +---------------+
- | /+A= |
- *---------------*/
-```
+ |
+
+ Attempts to convert a JSON value to a SQL STRING value.
+ |
+
PARSE_JSON
-```sql
-SELECT REPLACE(REPLACE(TO_BASE64(b'\377\340'), '+', '-'), '/', '_') as websafe_base64;
+ |
+
+ Converts a JSON-formatted STRING value to a
+ JSON value.
+ |
+
STRING
-[string-link-to-from-base64]: #from_base64
+ |
+
+ Converts a JSON string to a SQL STRING value.
+ |
+
TO_JSON
-### `TO_CODE_POINTS`
+ |
+ + Converts a SQL value to a JSON value. + | +
TO_JSON_STRING
+
+ |
+
+ Converts a SQL value to a JSON-formatted STRING value.
+ |
+
Category | -Functions | -Description | -
- - Standard extractors - - | -
-
- JSON_QUERY - JSON_VALUE - - - JSON_QUERY_ARRAY - - - JSON_VALUE_ARRAY - - |
- - Functions that extract JSON data. - | -
- - Legacy extractors - - | -
-
- JSON_EXTRACT - JSON_EXTRACT_SCALAR - - - - JSON_EXTRACT_STRING_ARRAY - - |
-
- Functions that extract JSON data. - - While these functions are supported by ZetaSQL, we recommend - using the standard extractor functions. - - |
-
Lax converters | -
-
- LAX_BOOL - - - LAX_DOUBLE - - - LAX_INT64 - - - LAX_STRING - - |
- - Functions that flexibly convert a JSON value to a scalar SQL value - without returning errors. - | -
Converters | -
-
- BOOL - - - DOUBLE - - - INT64 - - - STRING - - |
- - Functions that convert a JSON value to a scalar SQL value. - | -
Other converters | -
-
- PARSE_JSON - - - TO_JSON - - - TO_JSON_STRING - - |
- - Other conversion functions from or to JSON. - | -
Constructors | -
- JSON_ARRAY - JSON_OBJECT - |
- - Functions that create JSON. - | -
Mutators | -
-
- JSON_ARRAY_APPEND - - - JSON_ARRAY_INSERT - - - JSON_REMOVE - - - JSON_SET - - - JSON_STRIP_NULLS - - |
- - Functions that mutate existing JSON. - | -
Accessors | -
-
- JSON_TYPE - - |
- - Functions that provide access to JSON properties. - | -
Name | -Summary | -
---|---|
BOOL
+json_path_value_pair:
+ json_path, value
+```
- |
-
- Converts a JSON boolean to a SQL BOOL value.
- |
-
-
- DOUBLE
+Arguments:
-
- |
-
- Converts a JSON number to a SQL
- DOUBLE value.
- |
-
INT64
+ ```
+ JSON '["a", "b", "c"]'
+ ```
++ `json_path_value_pair`: A value and the [JSONPath][JSONPath-format] for
+ that value. This includes:
- |
-
- Converts a JSON number to a SQL INT64 value.
- |
-
JSON_ARRAY
+ + `value`: A [JSON encoding-supported][json-encodings] value to
+ append.
++ `append_each_element`: An optional, mandatory named argument.
- |
- Creates a JSON array. | -
JSON_ARRAY_APPEND
+ + If `FALSE,` and `value` is a SQL array, appends
+ the array as one element.
- |
- Appends JSON data to the end of a JSON array. | -
JSON_ARRAY_INSERT
++ Path value pairs are evaluated left to right. The JSON produced by
+ evaluating one pair becomes the JSON against which the next pair
+ is evaluated.
++ The operation is ignored if the path points to a JSON non-array value that
+ is not a JSON null.
++ If `json_path` points to a JSON null, the JSON null is replaced by a
+ JSON array that contains `value`.
++ If the path exists but has an incompatible type at any given path token,
+ the path value pair operation is ignored.
++ The function applies all path value pair append operations even if an
+ individual path value pair operation is invalid. For invalid operations,
+ the operation is ignored and the function continues to process the rest of
+ the path value pairs.
++ If any `json_path` is an invalid [JSONPath][JSONPath-format], an error is
+ produced.
++ If `json_expr` is SQL `NULL`, the function returns SQL `NULL`.
++ If `append_each_element` is SQL `NULL`, the function returns `json_expr`.
++ If `json_path` is SQL `NULL`, the `json_path_value_pair` operation is
+ ignored.
- |
- Inserts JSON data into a JSON array. | -
JSON_EXTRACT
+`JSON`
- |
-
- (Deprecated)
- Extracts a JSON value and converts it to a SQL
- JSON-formatted STRING
- or
- JSON
-
- value.
- |
-
JSON_EXTRACT_SCALAR
+In the following example, path `$` is matched and appends `1`.
- |
-
- (Deprecated)
- Extracts a JSON scalar value and converts it to a SQL
- STRING value.
- |
-
JSON_OBJECT
+/*-----------------*
+ | json_data |
+ +-----------------+
+ | ["a","b","c",1] |
+ *-----------------*/
+```
- |
- Creates a JSON object. | -
JSON_QUERY
+```sql
+SELECT JSON_ARRAY_APPEND(JSON '["a", "b", "c"]', '$', [1, 2]) AS json_data
- |
-
- Extracts a JSON value and converts it to a SQL
- JSON-formatted STRING
- or
- JSON
-
- value.
- |
-
JSON_QUERY_ARRAY
+In the following example, `append_each_element` is `FALSE`, so
+`[1, 2]` is appended as one element.
- |
-
- Extracts a JSON array and converts it to
- a SQL ARRAY<JSON-formatted STRING>
- or
- ARRAY<JSON>
-
- value.
- |
-
JSON_REMOVE
+/*---------------------*
+ | json_data |
+ +---------------------+
+ | ["a","b","c",[1,2]] |
+ *---------------------*/
+```
- |
- Produces JSON with the specified JSON data removed. | -
JSON_SET
+```sql
+SELECT JSON_ARRAY_APPEND(
+ JSON '["a", ["b"], "c"]',
+ '$[1]', [1, 2],
+ '$[1][1]', [3, 4],
+ append_each_element=>FALSE) AS json_data
- |
- Inserts or replaces JSON data. | -
JSON_STRIP_NULLS
+In the following example, the first path `$[1]` appends `[1, 2]` as single
+elements, and then the second path `$[1][1]` is not a valid path to an array,
+so the second operation is ignored.
- |
- Removes JSON nulls from JSON objects and JSON arrays. | -
JSON_TYPE
+/*---------------------*
+ | json_data |
+ +---------------------+
+ | ["a",["b",1,2],"c"] |
+ *---------------------*/
+```
- |
-
- Gets the JSON type of the outermost JSON value and converts the name of
- this type to a SQL STRING value.
- |
-
JSON_VALUE
+```sql
+SELECT JSON_ARRAY_APPEND(JSON '{"a": [1]}', '$.a', 2) AS json_data
- |
-
- Extracts a JSON scalar value and converts it to a SQL
- STRING value.
- |
-
JSON_VALUE_ARRAY
+In the following example, a value is appended into a JSON null.
- |
-
- Extracts a JSON array of scalar values and converts it to a SQL
- ARRAY<STRING> value.
- |
-
LAX_BOOL
+/*------------*
+ | json_data |
+ +------------+
+ | {"a":[10]} |
+ *------------*/
+```
- |
-
- Attempts to convert a JSON value to a SQL BOOL value.
- |
-
-
- LAX_DOUBLE
+```sql
+SELECT JSON_ARRAY_APPEND(JSON '{"a": 1}', '$.a', 2) AS json_data
-
- |
-
- Attempts to convert a JSON value to a
- SQL DOUBLE value.
- |
-
LAX_INT64
+In the following example, path `$.b` does not exist, so the operation is
+ignored.
- |
-
- Attempts to convert a JSON value to a SQL INT64 value.
- |
-
LAX_STRING
+/*-----------*
+ | json_data |
+ +-----------+
+ | {"a":1} |
+ *-----------*/
+```
- |
-
- Attempts to convert a JSON value to a SQL STRING value.
- |
-
PARSE_JSON
+```sql
+JSON_ARRAY_INSERT(
+ json_expr,
+ json_path_value_pair[, ...]
+ [, insert_each_element=>{ TRUE | FALSE }]
+)
- |
-
- Converts a JSON-formatted STRING value to a
- JSON value.
- |
-
STRING
+Produces a new JSON value that is created by inserting JSON data into
+a JSON array.
- |
-
- Converts a JSON string to a SQL STRING value.
- |
-
TO_JSON
++ `json_expr`: JSON. For example:
- |
- - Converts a SQL value to a JSON value. - | -
TO_JSON_STRING
+ + `json_path`: Insert `value` at this [JSONPath][JSONPath-format]
+ in `json_expr`.
- |
-
- Converts a SQL value to a JSON-formatted STRING value.
- |
-
BIGNUMERIC
value, and then safe casts the result as a
+ If the JSON string represents a JSON number, parses it as
+ a BIGNUMERIC
value, and then safe casts the result as a
DOUBLE
value.
If the JSON string can't be converted, returns NULL
.
BIGNUMERIC
value, and then safe casts the results as an
+ If the JSON string represents a JSON number, parses it as
+ a BIGNUMERIC
value, and then safe casts the results as an
INT64
value.
If the JSON string can't be converted, returns NULL
.
STRING value.
+ Returns the JSON string as a STRING
value.
STRING value.
+ Returns the JSON number as a STRING
value.
ARRAY
-
-ARRAY_AVG
-
-NULL
values in an array.
- ARRAY_CONCAT
-
-ARRAY_FILTER
-
-ARRAY_FIRST
-
-ARRAY_INCLUDES
-
-ARRAY_INCLUDES_ALL
+ KLL_QUANTILES.EXTRACT_INT64
INT64
-initialized KLL sketch.
ARRAY_INCLUDES_ANY
+ KLL_QUANTILES.EXTRACT_UINT64
UINT64
-initialized KLL sketch.
ARRAY_IS_DISTINCT
+ KLL_QUANTILES.EXTRACT_DOUBLE
DOUBLE
-initialized KLL sketch.
ARRAY_LAST
+ KLL_QUANTILES.EXTRACT_POINT_INT64
INT64
-initialized KLL sketch.
ARRAY_LENGTH
+ KLL_QUANTILES.EXTRACT_POINT_UINT64
UINT64
-initialized KLL sketch.
ARRAY_MAX
+ KLL_QUANTILES.EXTRACT_POINT_DOUBLE
NULL
value in an array.
+ Gets a specific quantile from a
+ DOUBLE
-initialized KLL sketch.
ARRAY_MIN
+ KLL_QUANTILES.INIT_INT64
NULL
value in an array.
+ Aggregates values into an
+ INT64
-initialized KLL sketch.
ARRAY_REVERSE
+ KLL_QUANTILES.INIT_UINT64
UINT64
-initialized KLL sketch.
ARRAY_SLICE
+ KLL_QUANTILES.INIT_DOUBLE
DOUBLE
-initialized KLL sketch.
ARRAY_SUM
+ KLL_QUANTILES.MERGE_INT64
NULL
values in an array.
+ Merges INT64
-initialized KLL sketches into a new sketch, and
+ then gets the quantiles from the new sketch.
ARRAY_TO_STRING
+ KLL_QUANTILES.MERGE_UINT64
STRING
value.
+ Merges UINT64
-initialized KLL sketches into a new sketch, and
+ then gets the quantiles from the new sketch.
ARRAY_TRANSFORM
+ KLL_QUANTILES.MERGE_DOUBLE
DOUBLE
-initialized KLL sketches
+ into a new sketch, and then gets the quantiles from the new sketch.
FLATTEN
+ KLL_QUANTILES.MERGE_PARTIAL
GENERATE_ARRAY
+ KLL_QUANTILES.MERGE_POINT_INT64
INT64
-initialized KLL sketches into a new sketch, and
+ then gets a specific quantile from the new sketch.
GENERATE_DATE_ARRAY
+ KLL_QUANTILES.MERGE_POINT_UINT64
UINT64
-initialized KLL sketches into a new sketch, and
+ then gets a specific quantile from the new sketch.
GENERATE_TIMESTAMP_ARRAY
+ KLL_QUANTILES.MERGE_POINT_DOUBLE
DOUBLE
-initialized KLL sketches
+ into a new sketch, and then gets a specific quantile from the new sketch.
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE | INTERVAL |
-
---|---|---|---|---|---|---|---|---|---|
OUTPUT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | INTERVAL |
‑inf
.
-`BOOL`
+**Supported Argument Types**
-**Example**
++ `input`: `DOUBLE`
++ `precision`: `INT64`
++ `input_weight`: `INT64`
-In the following example, the query first checks to see if any elements that are
-greater than 3 exist in an array (`e > 3`). Then the query checks to see if any
-any elements that are greater than 0 exist in an array (`e > 0`).
+**Return Type**
-```sql
-SELECT
- ARRAY_INCLUDES([1, 2, 3], e -> e > 3) AS a1,
- ARRAY_INCLUDES([1, 2, 3], e -> e > 0) AS a2;
+KLL sketch as `BYTES`
-/*-------+------*
- | a1 | a2 |
- +-------+------+
- | false | true |
- *-------+------*/
-```
+[kll-sketches]: https://github.com/google/zetasql/blob/master/docs/sketches.md#sketches_kll
-[lambda-definition]: https://github.com/google/zetasql/blob/master/docs/functions-reference.md#lambdas
+[sort-order]: https://github.com/google/zetasql/blob/master/docs/data-types.md#comparison_operator_examples
-### `ARRAY_INCLUDES_ALL`
+### `KLL_QUANTILES.MERGE_INT64`
```sql
-ARRAY_INCLUDES_ALL(array_to_search, search_values)
+KLL_QUANTILES.MERGE_INT64(sketch, number)
```
**Description**
-Takes an array to search and an array of search values. Returns `TRUE` if all
-search values are in the array to search, otherwise returns `FALSE`.
+Takes KLL sketches as `BYTES` and merges them into
+a new sketch, then returns the quantiles that divide the input into
+`number` equal-sized groups, along with the minimum and maximum values of the
+input. The output is an `ARRAY` containing the exact minimum value from
+the input data that you used to initialize the sketches, each
+approximate quantile, and the exact maximum value from the initial input data.
+This is an aggregate function.
-+ `array_to_search`: The array to search.
-+ `search_values`: The array that contains the elements to search for.
+If the merged sketches were initialized with different precisions, the precision
+is downgraded to the lowest precision involved in the merge — except if the
+aggregations are small enough to still capture the input exactly — then the
+mergee's precision is maintained.
-Returns `NULL` if `array_to_search` or `search_values` is
-`NULL`.
+Returns an error if the underlying type of one or more input sketches is not
+compatible with type `INT64`.
-**Return type**
+Returns an error if the input is not a valid KLL quantiles sketch.
-`BOOL`
+**Supported Argument Types**
+
++ `sketch`: `BYTES` KLL sketch initialized on `INT64` data type
++ `number`: `INT64`
+
+**Return Type**
+
+`ARRAY‑inf
.
-`BOOL`
+**Supported Argument Types**
-**Examples**
++ `sketch`: `BYTES` KLL sketch initialized on
+ `DOUBLE` data type
++ `number`: `INT64`
-```sql
-WITH example AS (
- SELECT [1, 2, 3] AS arr UNION ALL
- SELECT [1, 1, 1] AS arr UNION ALL
- SELECT [1, 2, NULL] AS arr UNION ALL
- SELECT [1, 1, NULL] AS arr UNION ALL
- SELECT [1, NULL, NULL] AS arr UNION ALL
- SELECT [] AS arr UNION ALL
- SELECT CAST(NULL AS ARRAY‑inf
.
-`ARRAY`
+**Supported Argument Types**
-**Examples**
++ `sketch`: `BYTES` KLL sketch initialized on
+ `DOUBLE` data type
++ `phi`: `DOUBLE` between 0 and 1
-```sql
-WITH example AS (
- SELECT [1, 2, 3] AS arr UNION ALL
- SELECT [4, 5] AS arr UNION ALL
- SELECT [] AS arr
-)
-SELECT
- arr,
- ARRAY_REVERSE(arr) AS reverse_arr
-FROM example;
+**Return Type**
-/*-----------+-------------*
- | arr | reverse_arr |
- +-----------+-------------+
- | [1, 2, 3] | [3, 2, 1] |
- | [4, 5] | [5, 4] |
- | [] | [] |
- *-----------+-------------*/
-```
+`DOUBLE`
-### `ARRAY_SLICE`
+[sort-order]: https://github.com/google/zetasql/blob/master/docs/data-types.md#comparison_operator_examples
-```sql
-ARRAY_SLICE(array_to_slice, start_offset, end_offset)
-```
+[kll-sketches]: https://github.com/google/zetasql/blob/master/docs/sketches.md#sketches_kll
-**Description**
+[approx-functions-reference]: #approximate_aggregate_functions
-Returns an array containing zero or more consecutive elements from the
-input array.
+## Mathematical functions
-+ `array_to_slice`: The array that contains the elements you want to slice.
-+ `start_offset`: The inclusive starting offset.
-+ `end_offset`: The inclusive ending offset.
+ZetaSQL supports mathematical functions.
+All mathematical functions have the following behaviors:
-An offset can be positive or negative. A positive offset starts from the
-beginning of the input array and is 0-based. A negative offset starts from
-the end of the input array. Out-of-bounds offsets are supported. Here are some
-examples:
++ They return `NULL` if any of the input parameters is `NULL`.
++ They return `NaN` if any of the arguments is `NaN`.
- Input offset | -Final offset in array | -Notes | +Category | +Functions |
---|---|---|---|---|
0 | -['a', 'b', 'c', 'd'] | -The final offset is 0 . |
+ Trigonometric | +
+ ACOS
+ ACOSH
+ ASIN
+ ASINH
+ ATAN
+ ATAN2
+ ATANH
+ COS
+ COSH
+ COT
+ COTH
+ CSC
+ CSCH
+ SEC
+ SECH
+ SIN
+ SINH
+ TAN
+ TANH
+ |
+
+ Exponential and + logarithmic + |
+
+ EXP
+ LN
+ LOG
+ LOG10
+ |
|||
3 | -['a', 'b', 'c', 'd'] | -The final offset is 3 . |
+
+ Rounding and + truncation + |
+
+ CEIL
+ CEILING
+ FLOOR
+ ROUND
+ TRUNC
+ |
5 | -['a', 'b', 'c', 'd'] |
- Because the input offset is out of bounds,
- the final offset is 3 (array length - 1 ).
+ Power and+ root + |
+
+ CBRT
+ POW
+ POWER
+ SQRT
|
|
-1 | -['a', 'b', 'c', 'd'] | +Sign |
- Because a negative offset is used, the offset starts at the end of the
- array. The final offset is 3
- (array length - 1 ).
+ ABS
+ SIGN
|
|
-2 | -['a', 'b', 'c', 'd'] |
- Because a negative offset is used, the offset starts at the end of the
- array. The final offset is 2
- (array length - 2 ).
+ Distance
+ |
+
+ COSINE_DISTANCE
+ EUCLIDEAN_DISTANCE
|
|
-4 | -['a', 'b', 'c', 'd'] |
- Because a negative offset is used, the offset starts at the end of the
- array. The final offset is 0
- (array length - 4 ).
+ Comparison
+ |
+
+ GREATEST
+ LEAST
|
|
-5 | -['a', 'b', 'c', 'd'] | +Random number generator |
- Because the offset is negative and out of bounds, the final offset is
- 0 (array length - array length ).
+ RAND
+ |
+ |
Arithmetic and error handling | +
+ DIV
+ IEEE_DIVIDE
+ IS_INF
+ IS_NAN
+ MOD
+ SAFE_ADD
+ SAFE_DIVIDE
+ SAFE_MULTIPLY
+ SAFE_NEGATE
+ SAFE_SUBTRACT
+ |
+ |||
Bucket | +
+ RANGE_BUCKET
+ |
+ |||
Numerical constants | +
+ PI
+ PI_BIGNUMERIC
+ PI_NUMERIC
|
Name | +Summary | +||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ABS
-**Examples**
+ |
+
+ Computes the absolute value of X .
+ |
+||||||||||||||||||||||
ACOS
-/*-----------*
- | result |
- +-----------+
- | [b, c, d] |
- *-----------*/
-```
+ |
+
+ Computes the inverse cosine of X .
+ |
+||||||||||||||||||||||
ACOSH
-/*-----------*
- | result |
- +-----------+
- | [] |
- *-----------*/
-```
+ |
+
+ Computes the inverse hyperbolic cosine of X .
+ |
+||||||||||||||||||||||
ASIN
-/*--------*
- | result |
- +--------+
- | [b, c] |
- *--------*/
-```
+ |
+
+ Computes the inverse sine of X .
+ |
+||||||||||||||||||||||
ASINH
-/*-----------*
- | result |
- +-----------+
- | [] |
- *-----------*/
-```
+ |
+
+ Computes the inverse hyperbolic sine of X .
+ |
+||||||||||||||||||||||
ATAN
-/*-----------*
- | result |
- +-----------+
- | [c, d, e] |
- *-----------*/
-```
+ |
+
+ Computes the inverse tangent of X .
+ |
+||||||||||||||||||||||
ATAN2
-/*--------*
- | result |
- +--------+
- | [d] |
- *--------*/
-```
+ |
+
+ Computes the inverse tangent of X/Y , using the signs of
+ X and Y to determine the quadrant.
+ |
+||||||||||||||||||||||
ATANH
-/*--------*
- | result |
- +--------+
- | [c] |
- *--------*/
-```
+ |
+
+ Computes the inverse hyperbolic tangent of X .
+ |
+||||||||||||||||||||||
CBRT
-/*--------------*
- | result |
- +--------------+
- | [b, c, d, e] |
- *--------------*/
-```
+ |
+
+ Computes the cube root of X .
+ |
+||||||||||||||||||||||
CEIL
-/*-----------*
- | result |
- +-----------+
- | [] |
- *-----------*/
-```
+ |
+
+ Gets the smallest integral value that is not less than X .
+ |
+||||||||||||||||||||||
CEILING
-/*-----------------*
- | result |
- +-----------------+
- | [a, b, c, d, e] |
- *-----------------*/
-```
+ |
+
+ Synonym of CEIL .
+ |
+||||||||||||||||||||||
COS
-/*--------*
- | result |
- +--------+
- | [a] |
- *--------*/
-```
+ |
+
+ Computes the cosine of X .
+ |
+||||||||||||||||||||||
COSH
-/*--------*
- | result |
- +--------+
- | [] |
- *--------*/
-```
+ |
+
+ Computes the hyperbolic cosine of X .
+ |
+||||||||||||||||||||||
COSINE_DISTANCE
-/*-----------*
- | result |
- +-----------+
- | NULL |
- *-----------*/
-```
+ |
+ Computes the cosine distance between two vectors. | +||||||||||||||||||||||
COT
-/*--------------*
- | result |
- +--------------+
- | [b, NULL, d] |
- *--------------*/
-```
+ |
+
+ Computes the cotangent of X .
+ |
+||||||||||||||||||||||
COTH
-```sql
-ARRAY_SUM(input_array)
-```
+ |
+
+ Computes the hyperbolic cotangent of X .
+ |
+||||||||||||||||||||||
CSC
-Returns the sum of non-`NULL` values in an array.
+ |
+
+ Computes the cosecant of X .
+ |
+||||||||||||||||||||||
CSCH
-+ If the array is `NULL`, empty, or contains only `NULL`s, returns
- `NULL`.
-+ If the array contains `NaN`, returns `NaN`.
-+ If the array contains `[+|-]Infinity`, returns either `[+|-]Infinity`
- or `NaN`.
-+ If there is numeric overflow, produces an error.
-+ If a [floating-point type][floating-point-types] is returned, the result is
- [non-deterministic][non-deterministic], which means you might receive a
- different result each time you use this function.
+ |
+
+ Computes the hyperbolic cosecant of X .
+ |
+||||||||||||||||||||||
DIV
-[non-deterministic]: https://github.com/google/zetasql/blob/master/docs/data-types.md#floating-point-semantics
+ |
+
+ Divides integer X by integer Y .
+ |
+||||||||||||||||||||||
EXP
-In the input array, `ARRAY |
+
+ Computes e to the power of X .
+ |
+||||||||||||||||||||||
EUCLIDEAN_DISTANCE
-**Return type**
+ |
+ Computes the Euclidean distance between two vectors. | +||||||||||||||||||||||
FLOOR
-
| |||||||||||||||||||||||
IEEE_DIVIDE
-**Examples**
+ |
+
+ Divides X by Y , but does not generate errors for
+ division by zero or overflow.
+ |
+||||||||||||||||||||||
IS_INF
-/*-----*
- | sum |
- +-----+
- | 25 |
- *-----*/
-```
+ |
+
+ Checks if X is positive or negative infinity.
+ |
+||||||||||||||||||||||
IS_NAN
-```sql
-ARRAY_TO_STRING(array_expression, delimiter[, null_text])
-```
+ |
+
+ Checks if X is a NaN value.
+ |
+||||||||||||||||||||||
LEAST
-Returns a concatenation of the elements in `array_expression`
-as a `STRING`. The value for `array_expression`
-can either be an array of `STRING` or
-`BYTES` data types.
+ |
+
+ Gets the least value among X1,...,XN .
+ |
+||||||||||||||||||||||
LN
-If the `null_text` parameter is not used, the function omits the `NULL` value
-and its preceding delimiter.
+ |
+
+ Computes the natural logarithm of X .
+ |
+||||||||||||||||||||||
LOG
-`STRING`
+ |
+
+ Computes the natural logarithm of X or the logarithm of
+ X to base Y .
+ |
+||||||||||||||||||||||
LOG10
-```sql
-WITH items AS
- (SELECT ['coffee', 'tea', 'milk' ] as list
- UNION ALL
- SELECT ['cake', 'pie', NULL] as list)
+ |
+
+ Computes the natural logarithm of X to base 10.
+ |
+||||||||||||||||||||||
MOD
-/*--------------------------------*
- | text |
- +--------------------------------+
- | coffee--tea--milk |
- | cake--pie |
- *--------------------------------*/
-```
+ |
+
+ Gets the remainder of the division of X by Y .
+ |
+||||||||||||||||||||||
PI
-SELECT ARRAY_TO_STRING(list, '--', 'MISSING') AS text
-FROM items;
+ |
+
+ Produces the mathematical constant π as a
+ DOUBLE value.
+ |
+||||||||||||||||||||||
PI_BIGNUMERIC
-### `ARRAY_TRANSFORM`
+ |
+
+ Produces the mathematical constant π as a BIGNUMERIC value.
+ |
+||||||||||||||||||||||
PI_NUMERIC
-lambda_expression:
- {
- element_alias -> transform_expression
- | (element_alias, index_alias) -> transform_expression
- }
-```
-
-**Description**
-
-Takes an array, transforms the elements, and returns the results in a new array.
-The output array always has the same length as the input array.
-
-+ `array_expression`: The array to transform.
-+ `lambda_expression`: Each element in `array_expression` is evaluated against
- the [lambda expression][lambda-definition]. The evaluation results are
- returned in a new array.
-+ `element_alias`: An alias that represents an array element.
-+ `index_alias`: An alias that represents the zero-based offset of the array
- element.
-+ `transform_expression`: The expression used to transform the array elements.
-
-Returns `NULL` if the `array_expression` is `NULL`.
+ |
+
+ Produces the mathematical constant π as a NUMERIC value.
+ |
+||||||||||||||||||||||
POW
-`ARRAY`
+ |
+
+ Produces the value of X raised to the power of Y .
+ |
+||||||||||||||||||||||
POWER
-```sql
-SELECT
- ARRAY_TRANSFORM([1, 2, 3], e -> e + 1) AS a1,
- ARRAY_TRANSFORM([1, 2, 3], (e, i) -> e + i) AS a2;
+ |
+
+ Synonym of POW .
+ |
+||||||||||||||||||||||
RAND
-[lambda-definition]: https://github.com/google/zetasql/blob/master/docs/functions-reference.md#lambdas
+ |
+
+ Generates a pseudo-random value of type
+ DOUBLE in the range of
+ [0, 1) .
+ |
+||||||||||||||||||||||
RANGE_BUCKET
-```sql
-FLATTEN(array_elements_field_access_expression)
-```
+ |
+ + Scans through a sorted array and returns the 0-based position + of a point's upper bound. + | +||||||||||||||||||||||
ROUND
-Takes a nested array and flattens a specific part of it into a single, flat
-array with the
-[array elements field access operator][array-el-field-operator].
-Returns `NULL` if the input value is `NULL`.
-If `NULL` array elements are
-encountered, they are added to the resulting array.
+ |
+
+ Rounds X to the nearest integer or rounds X
+ to N decimal places after the decimal point.
+ |
+||||||||||||||||||||||
SAFE_ADD
-**Return type**
+ |
+
+ Equivalent to the addition operator (X + Y ), but returns
+ NULL if overflow occurs.
+ |
+||||||||||||||||||||||
SAFE_DIVIDE
-**Examples**
+ |
+
+ Equivalent to the division operator (X / Y ), but returns
+ NULL if an error occurs.
+ |
+||||||||||||||||||||||
SAFE_MULTIPLY
-```sql
-WITH t AS (
- SELECT
- [
- STRUCT([STRUCT([1,2,3] AS quantity), STRUCT([4,5,6] AS quantity)] AS sales),
- STRUCT([STRUCT([7,8] AS quantity), STRUCT([] AS quantity)] AS sales)
- ] AS v
-)
-SELECT FLATTEN(v.sales.quantity) AS all_values
-FROM t;
+ |
+
+ Equivalent to the multiplication operator (X * Y ),
+ but returns NULL if overflow occurs.
+ |
+||||||||||||||||||||||
SAFE_NEGATE
-In the following example, `OFFSET` gets the second value in each array and
-concatenates them.
+ |
+
+ Equivalent to the unary minus operator (-X ), but returns
+ NULL if overflow occurs.
+ |
+||||||||||||||||||||||
SAFE_SUBTRACT
-/*---------------*
- | second_values |
- +---------------+
- | [2, 5, 8, 11] |
- *---------------*/
-```
+ |
+
+ Equivalent to the subtraction operator (X - Y ), but
+ returns NULL if overflow occurs.
+ |
+||||||||||||||||||||||
SEC
-```sql
-WITH t AS (
- SELECT
- [
- STRUCT(1 AS price, 2 AS quantity),
- STRUCT(10 AS price, 20 AS quantity)
- ] AS v
-)
-SELECT FLATTEN(v.price) AS all_prices
-FROM t;
+ |
+
+ Computes the secant of X .
+ |
+||||||||||||||||||||||
SECH
-For more examples, including how to use protocol buffers with `FLATTEN`, see the
-[array elements field access operator][array-el-field-operator].
+ |
+
+ Computes the hyperbolic secant of X .
+ |
+||||||||||||||||||||||
SIGN
-[array-el-field-operator]: #array_el_field_operator
+ |
+ + Produces -1 , 0, or +1 for negative, zero, and positive arguments + respectively. + | +||||||||||||||||||||||
SIN
-```sql
-GENERATE_ARRAY(start_expression, end_expression[, step_expression])
-```
+ |
+
+ Computes the sine of X .
+ |
+||||||||||||||||||||||
SINH
-Returns an array of values. The `start_expression` and `end_expression`
-parameters determine the inclusive start and end of the array.
+ |
+
+ Computes the hyperbolic sine of X .
+ |
+||||||||||||||||||||||
SQRT
-+ `INT64`
-+ `UINT64`
-+ `NUMERIC`
-+ `BIGNUMERIC`
-+ `DOUBLE`
+ |
+
+ Computes the square root of X .
+ |
+||||||||||||||||||||||
TAN
-This function returns an error if `step_expression` is set to 0, or if any
-input is `NaN`.
+ |
+
+ Computes the tangent of X .
+ |
+||||||||||||||||||||||
TANH
-**Return Data Type**
+ |
+
+ Computes the hyperbolic tangent of X .
+ |
+||||||||||||||||||||||
TRUNC
-**Examples**
+ |
+
+ Rounds a number like ROUND(X) or ROUND(X, N) ,
+ but always rounds towards zero and never overflows.
+ |
+
X | +ABS(X) | +
---|---|
25 | +25 | +
-25 | +25 | +
+inf |
+ +inf |
+
-inf |
+ +inf |
+
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+
---|---|---|---|---|---|---|---|---|
OUTPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
X | +ACOS(X) | +
---|---|
+inf |
+ NaN |
+
-inf |
+ NaN |
+
NaN |
+ NaN |
+
X < -1 | +Error | +
X > 1 | +Error | +
X | +ACOSH(X) | +
---|---|
+inf |
+ +inf |
+
-inf |
+ NaN |
+
NaN |
+ NaN |
+
X < 1 | +Error | +
X | +ASIN(X) | +
---|---|
+inf |
+ NaN |
+
-inf |
+ NaN |
+
NaN |
+ NaN |
+
X < -1 | +Error | +
X > 1 | +Error | +
X | +ASINH(X) | +
---|---|
+inf |
+ +inf |
+
-inf |
+ -inf |
+
NaN |
+ NaN |
+
X | +ATAN(X) | +
---|---|
+inf |
+ π/2 | +
-inf |
+ -π/2 | +
NaN |
+ NaN |
+
X | +Y | +ATAN2(X, Y) | +
---|---|---|
NaN |
+ Any value | +NaN |
+
Any value | +NaN |
+ NaN |
+
0.0 | +0.0 | +0.0 | +
Positive Finite value | +-inf |
+ π | +
Negative Finite value | +-inf |
+ -π | +
Finite value | ++inf |
+ 0.0 | +
+inf |
+ Finite value | +π/2 | +
-inf |
+ Finite value | +-π/2 | +
+inf |
+ -inf |
+ ¾π | +
-inf |
+ -inf |
+ -¾π | +
+inf |
+ +inf |
+ π/4 | +
-inf |
+ +inf |
+ -π/4 | +
X | +ATANH(X) | +
---|---|
+inf |
+ NaN |
+
-inf |
+ NaN |
+
NaN |
+ NaN |
+
X < -1 | +Error | +
X > 1 | +Error | +
X | +CBRT(X) | +
---|---|
+inf |
+ inf |
+
-inf |
+ -inf |
+
NaN |
+ NaN |
+
0 |
+ 0 |
+
NULL |
+ NULL |
+
X | +CEIL(X) | +
---|---|
2.0 | +2.0 | +
2.3 | +3.0 | +
2.8 | +3.0 | +
2.5 | +3.0 | +
-2.3 | +-2.0 | +
-2.8 | +-2.0 | +
-2.5 | +-2.0 | +
0 | +0 | +
+inf |
+ +inf |
+
-inf |
+ -inf |
+
NaN |
+ NaN |
+
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+
---|---|---|---|---|---|---|---|---|
OUTPUT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
Name | -Summary | +X | +COS(X) |
---|---|---|---|
CURRENT_DATE
-
- |
-
- Returns the current date as a DATE value.
- |
-||
DATE
-
- |
-
- Constructs a DATE value.
- |
-||
DATE_ADD
+
+ | |||
+inf |
+ NaN |
+ ||
-inf |
+ NaN |
+ ||
NaN |
+ NaN |
+
DATE
value.
- DATE_DIFF
+```
+COSH(X)
+```
-DATE
values.
- DATE_FROM_UNIX_DATE
+Computes the hyperbolic cosine of X where X is specified in radians.
+Generates an error if overflow occurs.
-INT64
expression as the number of days
- since 1970-01-01.
- X | +COSH(X) | +
---|---|
+inf |
+ +inf |
+
-inf |
+ +inf |
+
NaN |
+ NaN |
+
DATE_SUB
+### `COSINE_DISTANCE`
-DATE
value.
- DATE_TRUNC
+**Description**
-DATE
value.
- EXTRACT
+**Definitions**
-DATE
value.
- FORMAT_DATE
+**Details**
-DATE
value according to a specified format string.
- LAST_DAY
+ `T` can represent the following and must be the same for both
+ vectors:
-DATE
value.
- PARSE_DATE
+ + `FLOAT`
+ + `DOUBLE`
-STRING
value to a DATE
value.
- UNIX_DATE
+ In the following example vector, there are four dimensions. The magnitude
+ is `10.0` for dimension `0`, `55.0` for dimension `1`, `40.0` for
+ dimension `2`, and `34.0` for dimension `3`:
-DATE
value to the number of days since 1970-01-01.
- X | +COT(X) | +
---|---|
+inf |
+ NaN |
+
-inf |
+ NaN |
+
NaN |
+ NaN |
+
0 |
+ Error |
+
NULL |
+ NULL |
+
X | +COTH(X) | +
---|---|
+inf |
+ 1 |
+
-inf |
+ -1 |
+
NaN |
+ NaN |
+
0 |
+ Error |
+
NULL |
+ NULL |
+
X | +CSC(X) | +
---|---|
+inf |
+ NaN |
+
-inf |
+ NaN |
+
NaN |
+ NaN |
+
0 |
+ Error |
+
NULL |
+ NULL |
+
X | +CSCH(X) | +
---|---|
+inf |
+ 0 |
+
-inf |
+ 0 |
+
NaN |
+ NaN |
+
0 |
+ Error |
+
NULL |
+ NULL |
+
X | +Y | +DIV(X, Y) | +
---|---|---|
20 | +4 | +5 | +
12 | +-7 | +-1 | +
20 | +3 | +6 | +
0 | +20 | +0 | +
20 | +0 | +Error | +
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC |
+
---|---|---|---|---|---|---|
INT32 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC |
INT64 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC |
UINT32 | INT64 | INT64 | UINT64 | UINT64 | NUMERIC | BIGNUMERIC |
UINT64 | ERROR | ERROR | UINT64 | UINT64 | NUMERIC | BIGNUMERIC |
NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | BIGNUMERIC |
BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC |
X | +EXP(X) | +
---|---|
0.0 | +1.0 | +
+inf |
+ +inf |
+
-inf |
+ 0.0 | +
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+
---|---|---|---|---|---|---|---|---|
OUTPUT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
X | +FLOOR(X) | +
---|---|
2.0 | +2.0 | +
2.3 | +2.0 | +
2.8 | +2.0 | +
2.5 | +2.0 | +
-2.3 | +-3.0 | +
-2.8 | +-3.0 | +
-2.5 | +-3.0 | +
0 | +0 | +
+inf |
+ +inf |
+
-inf |
+ -inf |
+
NaN |
+ NaN |
+
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+
---|---|---|---|---|---|---|---|---|
OUTPUT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
X1,...,XN | +GREATEST(X1,...,XN) | +
---|---|
3,5,1 | +5 | +
X | +Y | +IEEE_DIVIDE(X, Y) | +
---|---|---|
20.0 | +4.0 | +5.0 | +
0.0 | +25.0 | +0.0 | +
25.0 | +0.0 | ++inf |
+
-25.0 | +0.0 | +-inf |
+
0.0 | +0.0 | +NaN |
+
0.0 | +NaN |
+ NaN |
+
NaN |
+ 0.0 | +NaN |
+
+inf |
+ +inf |
+ NaN |
+
-inf |
+ -inf |
+ NaN |
+
X | +IS_INF(X) | +
---|---|
+inf |
+ TRUE |
+
-inf |
+ TRUE |
+
25 | +FALSE |
+
X | +IS_NAN(X) | +
---|---|
NaN |
+ TRUE |
+
25 | +FALSE |
+
X1,...,XN | +LEAST(X1,...,XN) | +
---|---|
3,5,1 | +1 | +
X | +LN(X) | +
---|---|
1.0 | +0.0 | +
+inf |
+ +inf |
+
X < 0 |
+ Error | +
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+
---|---|---|---|---|---|---|---|---|
OUTPUT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
Name | -Summary | +X | +Y | +LOG(X, Y) |
---|---|---|---|---|
100.0 | +10.0 | +2.0 | +||
-inf |
+ Any value | +NaN |
+ ||
Any value | ++inf |
+ NaN |
+ ||
+inf |
+ 0.0 < Y < 1.0 | +-inf |
+ ||
+inf |
+ Y > 1.0 | ++inf |
+ ||
X <= 0 | +Any value | +Error | +||
Any value | +Y <= 0 | +Error | +||
Any value | +1.0 | +Error | +
CURRENT_DATETIME
-
-DATETIME
value.
- DATETIME
+**Return Data Type**
-DATETIME
value.
- DATETIME_ADD
-
- |
-
- Adds a specified time interval to a DATETIME value.
- |
+INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
---|---|---|---|---|---|---|---|---|---|---|
INT32 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
INT64 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
UINT32 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
UINT64 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
FLOAT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | ||
DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | ||
DATETIME_DIFF
-
- |
-
- Gets the number of intervals between two DATETIME values.
- |
-
DATETIME_SUB
+### `LOG10`
-DATETIME
value.
- DATETIME_TRUNC
+**Description**
-DATETIME
value.
- EXTRACT
-
-DATETIME
value.
- FORMAT_DATETIME
-
-DATETIME
value according to a specified
- format string.
- X | +LOG10(X) | +
---|---|
100.0 | +2.0 | +
-inf |
+ NaN |
+
+inf |
+ +inf |
+
X <= 0 | +Error | +
LAST_DAY
+**Return Data Type**
-DATETIME
value.
- PARSE_DATETIME
-
- |
-
- Converts a STRING value to a DATETIME value.
- |
+INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
---|---|---|---|---|---|---|---|---|---|---|
OUTPUT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
X | +Y | +MOD(X, Y) | +
---|---|---|
25 | +12 | +1 | +
25 | +0 | +Error | +
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC |
+
---|---|---|---|---|---|---|
INT32 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC |
INT64 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC |
UINT32 | INT64 | INT64 | UINT64 | UINT64 | NUMERIC | BIGNUMERIC |
UINT64 | ERROR | ERROR | UINT64 | UINT64 | NUMERIC | BIGNUMERIC |
NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | BIGNUMERIC |
BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC |
X | +Y | +POW(X, Y) | +
---|---|---|
2.0 | +3.0 | +8.0 | +
1.0 | +Any value including NaN |
+ 1.0 | +
Any value including NaN |
+ 0 | +1.0 | +
-1.0 | ++inf |
+ 1.0 | +
-1.0 | +-inf |
+ 1.0 | +
ABS(X) < 1 | +-inf |
+ +inf |
+
ABS(X) > 1 | +-inf |
+ 0.0 | +
ABS(X) < 1 | ++inf |
+ 0.0 | +
ABS(X) > 1 | ++inf |
+ +inf |
+
-inf |
+ Y < 0 | +0.0 | +
-inf |
+ Y > 0 | +-inf if Y is an odd integer, +inf otherwise |
+
+inf |
+ Y < 0 | +0 | +
+inf |
+ Y > 0 | ++inf |
+
Finite value < 0 | +Non-integer | +Error | +
0 | +Finite value < 0 | +Error | +
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+
---|---|---|---|---|---|---|---|---|
INT32 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
INT64 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
UINT32 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
UINT64 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
FLOAT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE |
DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE |
Expression | +Return Value | +
---|---|
ROUND(2.0) |
+ 2.0 | +
ROUND(2.3) |
+ 2.0 | +
ROUND(2.8) |
+ 3.0 | +
ROUND(2.5) |
+ 3.0 | +
ROUND(-2.3) |
+ -2.0 | +
ROUND(-2.8) |
+ -3.0 | +
ROUND(-2.5) |
+ -3.0 | +
ROUND(0) |
+ 0 | +
ROUND(+inf) |
+ +inf |
+
ROUND(-inf) |
+ -inf |
+
ROUND(NaN) |
+ NaN |
+
ROUND(123.7, -1) |
+ 120.0 | +
ROUND(1.235, 2) |
+ 1.24 | +
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+
---|---|---|---|---|---|---|---|---|
OUTPUT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
X | +Y | +SAFE_ADD(X, Y) | +
---|---|---|
5 | +4 | +9 | +
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+
---|---|---|---|---|---|---|---|---|
INT32 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
INT64 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
UINT32 | INT64 | INT64 | UINT64 | UINT64 | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
UINT64 | ERROR | ERROR | UINT64 | UINT64 | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
FLOAT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE |
DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE |
X | +Y | +SAFE_DIVIDE(X, Y) | +
---|---|---|
20 | +4 | +5 | +
0 | +20 | +0 |
+
20 | +0 | +NULL |
+
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+
---|---|---|---|---|---|---|---|---|
INT32 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
INT64 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
UINT32 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
UINT64 | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
FLOAT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE |
DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE |
X | +Y | +SAFE_MULTIPLY(X, Y) | +
---|---|---|
20 | +4 | +80 | +
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+
---|---|---|---|---|---|---|---|---|
INT32 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
INT64 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
UINT32 | INT64 | INT64 | UINT64 | UINT64 | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
UINT64 | ERROR | ERROR | UINT64 | UINT64 | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
FLOAT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE |
DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE |
X | +SAFE_NEGATE(X) | +
---|---|
+1 | +-1 | +
-1 | ++1 | +
0 | +0 | +
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+
---|---|---|---|---|---|---|---|---|
OUTPUT | INT32 | INT64 | ERROR | ERROR | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
Name | -Summary | +X | +Y | +SAFE_SUBTRACT(X, Y) |
---|---|---|---|---|
5 | +4 | +1 | +
CURRENT_TIME
-
-TIME
value.
- EXTRACT
+**Return Data Type**
-TIME
value.
- FORMAT_TIME
-
- |
-
- Formats a TIME value according to the specified format string.
- |
+INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
---|---|---|---|---|---|---|---|---|---|---|
INT32 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
INT64 | INT64 | INT64 | INT64 | ERROR | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
UINT32 | INT64 | INT64 | INT64 | INT64 | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
UINT64 | ERROR | ERROR | INT64 | INT64 | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | DOUBLE | DOUBLE | ||
FLOAT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | ||
DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | DOUBLE | ||
PARSE_TIME
-
- |
-
- Converts a STRING value to a TIME value.
- |
-
TIME
+### `SEC`
-TIME
value.
- TIME_ADD
+**Description**
-TIME
value.
- TIME_DIFF
+X | +SEC(X) | +
---|---|
+inf |
+ NaN |
+
-inf |
+ NaN |
+
NaN |
+ NaN |
+
NULL |
+ NULL |
+
TIME
values.
- TIME_SUB
+`DOUBLE`
-TIME
value.
- TIME_TRUNC
+```sql
+SELECT SEC(100) AS a, SEC(-1) AS b;
-TIME
value.
- X | +SECH(X) | +
---|---|
+inf |
+ 0 |
+
-inf |
+ 0 |
+
NaN |
+ NaN |
+
NULL |
+ NULL |
+
X | +SIGN(X) | +
---|---|
25 | ++1 | +
0 | +0 | +
-25 | +-1 | +
NaN | +NaN | +
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+
---|---|---|---|---|---|---|---|---|
OUTPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
X | +SIN(X) | +
---|---|
+inf |
+ NaN |
+
-inf |
+ NaN |
+
NaN |
+ NaN |
+
X | +SINH(X) | +
---|---|
+inf |
+ +inf |
+
-inf |
+ -inf |
+
NaN |
+ NaN |
+
X | +SQRT(X) | +
---|---|
25.0 |
+ 5.0 |
+
+inf |
+ +inf |
+
X < 0 |
+ Error | +
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+
---|---|---|---|---|---|---|---|---|
OUTPUT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
X | +TAN(X) | +
---|---|
+inf |
+ NaN |
+
-inf |
+ NaN |
+
NaN |
+ NaN |
+
X | +TANH(X) | +
---|---|
+inf |
+ 1.0 | +
-inf |
+ -1.0 | +
NaN |
+ NaN |
+
X | +TRUNC(X) | +
---|---|
2.0 | +2.0 | +
2.3 | +2.0 | +
2.8 | +2.0 | +
2.5 | +2.0 | +
-2.3 | +-2.0 | +
-2.8 | +-2.0 | +
-2.5 | +-2.0 | +
0 | +0 | +
+inf |
+ +inf |
+
-inf |
+ -inf |
+
NaN |
+ NaN |
+
INPUT | INT32 | INT64 | UINT32 | UINT64 | NUMERIC | BIGNUMERIC | FLOAT | DOUBLE |
+
---|---|---|---|---|---|---|---|---|
OUTPUT | DOUBLE | DOUBLE | DOUBLE | DOUBLE | NUMERIC | BIGNUMERIC | DOUBLE | DOUBLE |
CURRENT_TIMESTAMP
+ FIRST_VALUE
TIMESTAMP
object.
+ Gets a value for the first row in the current window frame.
EXTRACT
+ LAG
TIMESTAMP
value.
+ Gets a value for a preceding row.
FORMAT_TIMESTAMP
+ LAST_VALUE
TIMESTAMP
value according to the specified
- format string.
+ Gets a value for the last row in the current window frame.
PARSE_TIMESTAMP
+ LEAD
STRING
value to a TIMESTAMP
value.
+ Gets a value for a subsequent row.
STRING
+ NTH_VALUE
TIMESTAMP
value to a STRING
value.
+ Gets a value for the Nth row of the current window frame.
TIMESTAMP
+ PERCENTILE_CONT
TIMESTAMP
value.
+ Computes the specified percentile for a value, using
+ linear interpolation.
TIMESTAMP_ADD
+ PERCENTILE_DISC
TIMESTAMP
value.
+ Computes the specified percentile for a discrete value.
TIMESTAMP_DIFF
-
-TIMESTAMP
values.
- TIMESTAMP_FROM_UNIX_MICROS
+### `FIRST_VALUE`
-TIMESTAMP_MICROS
, except that additionally, a
- TIMESTAMP
value can be passed in.
- TIMESTAMP_FROM_UNIX_MILLIS
+over_clause:
+ { named_window | ( [ window_specification ] ) }
-TIMESTAMP_MILLIS
, except that additionally, a
- TIMESTAMP
value can be passed in.
- TIMESTAMP_FROM_UNIX_SECONDS
+```
-TIMESTAMP_SECONDS
, except that additionally, a
- TIMESTAMP
value can be passed in.
- TIMESTAMP_MICROS
+Returns the value of the `value_expression` for the first row in the current
+window frame.
-TIMESTAMP.
-
TIMESTAMP_MILLIS
+This function includes `NULL` values in the calculation unless `IGNORE NULLS` is
+present. If `IGNORE NULLS` is present, the function excludes `NULL` values from
+the calculation.
-TIMESTAMP.
-
TIMESTAMP_SECONDS
+
-TIMESTAMP.
-
TIMESTAMP_SUB
+
-TIMESTAMP
value.
- TIMESTAMP_TRUNC
+`value_expression` can be any data type that an expression can return.
-TIMESTAMP
value.
- UNIX_MICROS
+Same type as `value_expression`.
-TIMESTAMP
value to the number of microseconds since
- 1970-01-01 00:00:00 UTC.
- UNIX_MILLIS
+The following example computes the fastest time for each division.
-TIMESTAMP
value to the number of milliseconds
- since 1970-01-01 00:00:00 UTC.
- UNIX_SECONDS
+/*-----------------+-------------+----------+--------------+------------------*
+ | name | finish_time | division | fastest_time | delta_in_seconds |
+ +-----------------+-------------+----------+--------------+------------------+
+ | Carly Forte | 03:08:58 | F25-29 | 03:08:58 | 0 |
+ | Sophia Liu | 02:51:45 | F30-34 | 02:51:45 | 0 |
+ | Nikki Leith | 02:59:01 | F30-34 | 02:51:45 | 436 |
+ | Jen Edwards | 03:06:36 | F30-34 | 02:51:45 | 891 |
+ | Meghan Lederer | 03:07:41 | F30-34 | 02:51:45 | 956 |
+ | Lauren Reasoner | 03:10:14 | F30-34 | 02:51:45 | 1109 |
+ | Lisa Stelzner | 02:54:11 | F35-39 | 02:54:11 | 0 |
+ | Lauren Matthews | 03:01:17 | F35-39 | 02:54:11 | 426 |
+ | Desiree Berry | 03:05:42 | F35-39 | 02:54:11 | 691 |
+ | Suzy Slane | 03:06:24 | F35-39 | 02:54:11 | 733 |
+ *-----------------+-------------+----------+--------------+------------------*/
+```
-TIMESTAMP
value to the number of seconds since
- 1970-01-01 00:00:00 UTC.
- DATETIME
-+ TIME
+To learn more about the `OVER` clause and how to use it, see
+[Window function calls][window-function-calls].
-Returned values truncate lower order time periods. For example, when extracting
-seconds, `EXTRACT` truncates the millisecond and microsecond values.
+
-**Return Data Type**
+[window-function-calls]: https://github.com/google/zetasql/blob/master/docs/window-function-calls.md
-`INT64`, except in the following cases:
+
-+ If `part` is `DATE`, the function returns a `DATE` object.
+**Supported Argument Types**
-**Examples**
+`value_expression` can be any data type that an expression can return.
-In the following example, `EXTRACT` returns a value corresponding to the `DAY`
-time part.
+**Return Data Type**
-```sql
-WITH Input AS (SELECT TIMESTAMP("2008-12-25 05:30:00+00") AS timestamp_value)
-SELECT
- EXTRACT(DAY FROM timestamp_value AT TIME ZONE "UTC") AS the_day_utc,
- EXTRACT(DAY FROM timestamp_value AT TIME ZONE "America/Los_Angeles") AS the_day_california
-FROM Input
+Same type as `value_expression`.
-/*-------------+--------------------*
- | the_day_utc | the_day_california |
- +-------------+--------------------+
- | 25 | 24 |
- *-------------+--------------------*/
-```
+**Examples**
-In the following example, `EXTRACT` returns values corresponding to different
-time parts from a column of type `TIMESTAMP`.
+The following example computes the slowest time for each division.
```sql
-WITH Timestamps AS (
- SELECT TIMESTAMP("2005-01-03 12:34:56+00") AS timestamp_value UNION ALL
- SELECT TIMESTAMP("2007-12-31 12:00:00+00") UNION ALL
- SELECT TIMESTAMP("2009-01-01 12:00:00+00") UNION ALL
- SELECT TIMESTAMP("2009-12-31 12:00:00+00") UNION ALL
- SELECT TIMESTAMP("2017-01-02 12:00:00+00") UNION ALL
- SELECT TIMESTAMP("2017-05-26 12:00:00+00")
-)
-SELECT
- timestamp_value,
- EXTRACT(ISOYEAR FROM timestamp_value) AS isoyear,
- EXTRACT(ISOWEEK FROM timestamp_value) AS isoweek,
- EXTRACT(YEAR FROM timestamp_value) AS year,
- EXTRACT(WEEK FROM timestamp_value) AS week
-FROM Timestamps
-ORDER BY timestamp_value;
+WITH finishers AS
+ (SELECT 'Sophia Liu' as name,
+ TIMESTAMP '2016-10-18 2:51:45' as finish_time,
+ 'F30-34' as division
+ UNION ALL SELECT 'Lisa Stelzner', TIMESTAMP '2016-10-18 2:54:11', 'F35-39'
+ UNION ALL SELECT 'Nikki Leith', TIMESTAMP '2016-10-18 2:59:01', 'F30-34'
+ UNION ALL SELECT 'Lauren Matthews', TIMESTAMP '2016-10-18 3:01:17', 'F35-39'
+ UNION ALL SELECT 'Desiree Berry', TIMESTAMP '2016-10-18 3:05:42', 'F35-39'
+ UNION ALL SELECT 'Suzy Slane', TIMESTAMP '2016-10-18 3:06:24', 'F35-39'
+ UNION ALL SELECT 'Jen Edwards', TIMESTAMP '2016-10-18 3:06:36', 'F30-34'
+ UNION ALL SELECT 'Meghan Lederer', TIMESTAMP '2016-10-18 3:07:41', 'F30-34'
+ UNION ALL SELECT 'Carly Forte', TIMESTAMP '2016-10-18 3:08:58', 'F25-29'
+ UNION ALL SELECT 'Lauren Reasoner', TIMESTAMP '2016-10-18 3:10:14', 'F30-34')
+SELECT name,
+ FORMAT_TIMESTAMP('%X', finish_time) AS finish_time,
+ division,
+ FORMAT_TIMESTAMP('%X', slowest_time) AS slowest_time,
+ TIMESTAMP_DIFF(slowest_time, finish_time, SECOND) AS delta_in_seconds
+FROM (
+ SELECT name,
+ finish_time,
+ division,
+ LAST_VALUE(finish_time)
+ OVER (PARTITION BY division ORDER BY finish_time ASC
+ ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS slowest_time
+ FROM finishers);
--- Display of results may differ, depending upon the environment and time zone where this query was executed.
-/*---------------------------------------------+---------+---------+------+------*
- | timestamp_value | isoyear | isoweek | year | week |
- +---------------------------------------------+---------+---------+------+------+
- | 2005-01-03 04:34:56.000 America/Los_Angeles | 2005 | 1 | 2005 | 1 |
- | 2007-12-31 04:00:00.000 America/Los_Angeles | 2008 | 1 | 2007 | 52 |
- | 2009-01-01 04:00:00.000 America/Los_Angeles | 2009 | 1 | 2009 | 0 |
- | 2009-12-31 04:00:00.000 America/Los_Angeles | 2009 | 53 | 2009 | 52 |
- | 2017-01-02 04:00:00.000 America/Los_Angeles | 2017 | 1 | 2017 | 1 |
- | 2017-05-26 05:00:00.000 America/Los_Angeles | 2017 | 21 | 2017 | 21 |
- *---------------------------------------------+---------+---------+------+------*/
+/*-----------------+-------------+----------+--------------+------------------*
+ | name | finish_time | division | slowest_time | delta_in_seconds |
+ +-----------------+-------------+----------+--------------+------------------+
+ | Carly Forte | 03:08:58 | F25-29 | 03:08:58 | 0 |
+ | Sophia Liu | 02:51:45 | F30-34 | 03:10:14 | 1109 |
+ | Nikki Leith | 02:59:01 | F30-34 | 03:10:14 | 673 |
+ | Jen Edwards | 03:06:36 | F30-34 | 03:10:14 | 218 |
+ | Meghan Lederer | 03:07:41 | F30-34 | 03:10:14 | 153 |
+ | Lauren Reasoner | 03:10:14 | F30-34 | 03:10:14 | 0 |
+ | Lisa Stelzner | 02:54:11 | F35-39 | 03:06:24 | 733 |
+ | Lauren Matthews | 03:01:17 | F35-39 | 03:06:24 | 307 |
+ | Desiree Berry | 03:05:42 | F35-39 | 03:06:24 | 42 |
+ | Suzy Slane | 03:06:24 | F35-39 | 03:06:24 | 0 |
+ *-----------------+-------------+----------+--------------+------------------*/
```
-In the following example, `timestamp_expression` falls on a Monday. `EXTRACT`
-calculates the first column using weeks that begin on Sunday, and it calculates
-the second column using weeks that begin on Monday.
+### `LEAD`
```sql
-WITH table AS (SELECT TIMESTAMP("2017-11-06 00:00:00+00") AS timestamp_value)
-SELECT
- timestamp_value,
- EXTRACT(WEEK(SUNDAY) FROM timestamp_value) AS week_sunday,
- EXTRACT(WEEK(MONDAY) FROM timestamp_value) AS week_monday
-FROM table;
+LEAD (value_expression[, offset [, default_expression]])
+OVER over_clause
+
+over_clause:
+ { named_window | ( [ window_specification ] ) }
+
+window_specification:
+ [ named_window ]
+ [ PARTITION BY partition_expression [, ...] ]
+ ORDER BY expression [ { ASC | DESC } ] [, ...]
--- Display of results may differ, depending upon the environment and time zone where this query was executed.
-/*---------------------------------------------+-------------+---------------*
- | timestamp_value | week_sunday | week_monday |
- +---------------------------------------------+-------------+---------------+
- | 2017-11-05 16:00:00.000 America/Los_Angeles | 45 | 44 |
- *---------------------------------------------+-------------+---------------*/
```
-[ISO-8601]: https://en.wikipedia.org/wiki/ISO_8601
+**Description**
-[ISO-8601-week]: https://en.wikipedia.org/wiki/ISO_week_date
+Returns the value of the `value_expression` on a subsequent row. Changing the
+`offset` value changes which subsequent row is returned; the default value is
+`1`, indicating the next row in the window frame. An error occurs if `offset` is
+NULL or a negative value.
-[timestamp-link-to-timezone-definitions]: #timezone_definitions
+The optional `default_expression` is used if there isn't a row in the window
+frame at the specified offset. This expression must be a constant expression and
+its type must be implicitly coercible to the type of `value_expression`. If left
+unspecified, `default_expression` defaults to NULL.
-### `FORMAT_TIMESTAMP`
+To learn more about the `OVER` clause and how to use it, see
+[Window function calls][window-function-calls].
-```sql
-FORMAT_TIMESTAMP(format_string, timestamp[, time_zone])
-```
+
-**Description**
+[window-function-calls]: https://github.com/google/zetasql/blob/master/docs/window-function-calls.md
-Formats a timestamp according to the specified `format_string`.
+
-See [Format elements for date and time parts][timestamp-format-elements]
-for a list of format elements that this function supports.
+**Supported Argument Types**
+
++ `value_expression` can be any data type that can be returned from an
+ expression.
++ `offset` must be a non-negative integer literal or parameter.
++ `default_expression` must be compatible with the value expression type.
**Return Data Type**
-`STRING`
+Same type as `value_expression`.
-**Example**
+**Examples**
+
+The following example illustrates a basic use of the `LEAD` function.
```sql
-SELECT FORMAT_TIMESTAMP("%c", TIMESTAMP "2050-12-25 15:30:55+00", "UTC")
- AS formatted;
+WITH finishers AS
+ (SELECT 'Sophia Liu' as name,
+ TIMESTAMP '2016-10-18 2:51:45' as finish_time,
+ 'F30-34' as division
+ UNION ALL SELECT 'Lisa Stelzner', TIMESTAMP '2016-10-18 2:54:11', 'F35-39'
+ UNION ALL SELECT 'Nikki Leith', TIMESTAMP '2016-10-18 2:59:01', 'F30-34'
+ UNION ALL SELECT 'Lauren Matthews', TIMESTAMP '2016-10-18 3:01:17', 'F35-39'
+ UNION ALL SELECT 'Desiree Berry', TIMESTAMP '2016-10-18 3:05:42', 'F35-39'
+ UNION ALL SELECT 'Suzy Slane', TIMESTAMP '2016-10-18 3:06:24', 'F35-39'
+ UNION ALL SELECT 'Jen Edwards', TIMESTAMP '2016-10-18 3:06:36', 'F30-34'
+ UNION ALL SELECT 'Meghan Lederer', TIMESTAMP '2016-10-18 3:07:41', 'F30-34'
+ UNION ALL SELECT 'Carly Forte', TIMESTAMP '2016-10-18 3:08:58', 'F25-29'
+ UNION ALL SELECT 'Lauren Reasoner', TIMESTAMP '2016-10-18 3:10:14', 'F30-34')
+SELECT name,
+ finish_time,
+ division,
+ LEAD(name)
+ OVER (PARTITION BY division ORDER BY finish_time ASC) AS followed_by
+FROM finishers;
-/*--------------------------*
- | formatted |
- +--------------------------+
- | Sun Dec 25 15:30:55 2050 |
- *--------------------------*/
+/*-----------------+-------------+----------+-----------------*
+ | name | finish_time | division | followed_by |
+ +-----------------+-------------+----------+-----------------+
+ | Carly Forte | 03:08:58 | F25-29 | NULL |
+ | Sophia Liu | 02:51:45 | F30-34 | Nikki Leith |
+ | Nikki Leith | 02:59:01 | F30-34 | Jen Edwards |
+ | Jen Edwards | 03:06:36 | F30-34 | Meghan Lederer |
+ | Meghan Lederer | 03:07:41 | F30-34 | Lauren Reasoner |
+ | Lauren Reasoner | 03:10:14 | F30-34 | NULL |
+ | Lisa Stelzner | 02:54:11 | F35-39 | Lauren Matthews |
+ | Lauren Matthews | 03:01:17 | F35-39 | Desiree Berry |
+ | Desiree Berry | 03:05:42 | F35-39 | Suzy Slane |
+ | Suzy Slane | 03:06:24 | F35-39 | NULL |
+ *-----------------+-------------+----------+-----------------*/
```
+This next example uses the optional `offset` parameter.
+
```sql
-SELECT FORMAT_TIMESTAMP("%b-%d-%Y", TIMESTAMP "2050-12-25 15:30:55+00")
- AS formatted;
+WITH finishers AS
+ (SELECT 'Sophia Liu' as name,
+ TIMESTAMP '2016-10-18 2:51:45' as finish_time,
+ 'F30-34' as division
+ UNION ALL SELECT 'Lisa Stelzner', TIMESTAMP '2016-10-18 2:54:11', 'F35-39'
+ UNION ALL SELECT 'Nikki Leith', TIMESTAMP '2016-10-18 2:59:01', 'F30-34'
+ UNION ALL SELECT 'Lauren Matthews', TIMESTAMP '2016-10-18 3:01:17', 'F35-39'
+ UNION ALL SELECT 'Desiree Berry', TIMESTAMP '2016-10-18 3:05:42', 'F35-39'
+ UNION ALL SELECT 'Suzy Slane', TIMESTAMP '2016-10-18 3:06:24', 'F35-39'
+ UNION ALL SELECT 'Jen Edwards', TIMESTAMP '2016-10-18 3:06:36', 'F30-34'
+ UNION ALL SELECT 'Meghan Lederer', TIMESTAMP '2016-10-18 3:07:41', 'F30-34'
+ UNION ALL SELECT 'Carly Forte', TIMESTAMP '2016-10-18 3:08:58', 'F25-29'
+ UNION ALL SELECT 'Lauren Reasoner', TIMESTAMP '2016-10-18 3:10:14', 'F30-34')
+SELECT name,
+ finish_time,
+ division,
+ LEAD(name, 2)
+ OVER (PARTITION BY division ORDER BY finish_time ASC) AS two_runners_back
+FROM finishers;
-/*-------------*
- | formatted |
- +-------------+
- | Dec-25-2050 |
- *-------------*/
+/*-----------------+-------------+----------+------------------*
+ | name | finish_time | division | two_runners_back |
+ +-----------------+-------------+----------+------------------+
+ | Carly Forte | 03:08:58 | F25-29 | NULL |
+ | Sophia Liu | 02:51:45 | F30-34 | Jen Edwards |
+ | Nikki Leith | 02:59:01 | F30-34 | Meghan Lederer |
+ | Jen Edwards | 03:06:36 | F30-34 | Lauren Reasoner |
+ | Meghan Lederer | 03:07:41 | F30-34 | NULL |
+ | Lauren Reasoner | 03:10:14 | F30-34 | NULL |
+ | Lisa Stelzner | 02:54:11 | F35-39 | Desiree Berry |
+ | Lauren Matthews | 03:01:17 | F35-39 | Suzy Slane |
+ | Desiree Berry | 03:05:42 | F35-39 | NULL |
+ | Suzy Slane | 03:06:24 | F35-39 | NULL |
+ *-----------------+-------------+----------+------------------*/
```
+The following example replaces NULL values with a default value.
+
```sql
-SELECT FORMAT_TIMESTAMP("%b %Y", TIMESTAMP "2050-12-25 15:30:55+00")
- AS formatted;
+WITH finishers AS
+ (SELECT 'Sophia Liu' as name,
+ TIMESTAMP '2016-10-18 2:51:45' as finish_time,
+ 'F30-34' as division
+ UNION ALL SELECT 'Lisa Stelzner', TIMESTAMP '2016-10-18 2:54:11', 'F35-39'
+ UNION ALL SELECT 'Nikki Leith', TIMESTAMP '2016-10-18 2:59:01', 'F30-34'
+ UNION ALL SELECT 'Lauren Matthews', TIMESTAMP '2016-10-18 3:01:17', 'F35-39'
+ UNION ALL SELECT 'Desiree Berry', TIMESTAMP '2016-10-18 3:05:42', 'F35-39'
+ UNION ALL SELECT 'Suzy Slane', TIMESTAMP '2016-10-18 3:06:24', 'F35-39'
+ UNION ALL SELECT 'Jen Edwards', TIMESTAMP '2016-10-18 3:06:36', 'F30-34'
+ UNION ALL SELECT 'Meghan Lederer', TIMESTAMP '2016-10-18 3:07:41', 'F30-34'
+ UNION ALL SELECT 'Carly Forte', TIMESTAMP '2016-10-18 3:08:58', 'F25-29'
+ UNION ALL SELECT 'Lauren Reasoner', TIMESTAMP '2016-10-18 3:10:14', 'F30-34')
+SELECT name,
+ finish_time,
+ division,
+ LEAD(name, 2, 'Nobody')
+ OVER (PARTITION BY division ORDER BY finish_time ASC) AS two_runners_back
+FROM finishers;
-/*-------------*
- | formatted |
- +-------------+
- | Dec 2050 |
- *-------------*/
+/*-----------------+-------------+----------+------------------*
+ | name | finish_time | division | two_runners_back |
+ +-----------------+-------------+----------+------------------+
+ | Carly Forte | 03:08:58 | F25-29 | Nobody |
+ | Sophia Liu | 02:51:45 | F30-34 | Jen Edwards |
+ | Nikki Leith | 02:59:01 | F30-34 | Meghan Lederer |
+ | Jen Edwards | 03:06:36 | F30-34 | Lauren Reasoner |
+ | Meghan Lederer | 03:07:41 | F30-34 | Nobody |
+ | Lauren Reasoner | 03:10:14 | F30-34 | Nobody |
+ | Lisa Stelzner | 02:54:11 | F35-39 | Desiree Berry |
+ | Lauren Matthews | 03:01:17 | F35-39 | Suzy Slane |
+ | Desiree Berry | 03:05:42 | F35-39 | Nobody |
+ | Suzy Slane | 03:06:24 | F35-39 | Nobody |
+ *-----------------+-------------+----------+------------------*/
```
-```sql
-SELECT FORMAT_TIMESTAMP("%Y-%m-%dT%H:%M:%SZ", TIMESTAMP "2050-12-25 15:30:55", "UTC")
- AS formatted;
+### `NTH_VALUE`
-/*+---------------------*
- | formatted |
- +----------------------+
- | 2050-12-25T15:30:55Z |
- *----------------------*/
-```
+```sql
+NTH_VALUE (value_expression, constant_integer_expression [{RESPECT | IGNORE} NULLS])
+OVER over_clause
-[timestamp-format-elements]: https://github.com/google/zetasql/blob/master/docs/format-elements.md#format_elements_date_time
+over_clause:
+ { named_window | ( [ window_specification ] ) }
-### `PARSE_TIMESTAMP`
+window_specification:
+ [ named_window ]
+ [ PARTITION BY partition_expression [, ...] ]
+ ORDER BY expression [ { ASC | DESC } ] [, ...]
+ [ window_frame_clause ]
-```sql
-PARSE_TIMESTAMP(format_string, timestamp_string[, time_zone])
```
**Description**
-Converts a [string representation of a timestamp][timestamp-format] to a
-`TIMESTAMP` object.
+Returns the value of `value_expression` at the Nth row of the current window
+frame, where Nth is defined by `constant_integer_expression`. Returns NULL if
+there is no such row.
-`format_string` contains the [format elements][timestamp-format-elements]
-that define how `timestamp_string` is formatted. Each element in
-`timestamp_string` must have a corresponding element in `format_string`. The
-location of each element in `format_string` must match the location of
-each element in `timestamp_string`.
+This function includes `NULL` values in the calculation unless `IGNORE NULLS` is
+present. If `IGNORE NULLS` is present, the function excludes `NULL` values from
+the calculation.
-```sql
--- This works because elements on both sides match.
-SELECT PARSE_TIMESTAMP("%a %b %e %I:%M:%S %Y", "Thu Dec 25 07:30:00 2008")
+To learn more about the `OVER` clause and how to use it, see
+[Window function calls][window-function-calls].
--- This produces an error because the year element is in different locations.
-SELECT PARSE_TIMESTAMP("%a %b %e %Y %I:%M:%S", "Thu Dec 25 07:30:00 2008")
+
--- This produces an error because one of the year elements is missing.
-SELECT PARSE_TIMESTAMP("%a %b %e %I:%M:%S", "Thu Dec 25 07:30:00 2008")
+[window-function-calls]: https://github.com/google/zetasql/blob/master/docs/window-function-calls.md
--- This works because %c can find all matching elements in timestamp_string.
-SELECT PARSE_TIMESTAMP("%c", "Thu Dec 25 07:30:00 2008")
-```
+
-When using `PARSE_TIMESTAMP`, keep the following in mind:
+**Supported Argument Types**
-+ **Unspecified fields.** Any unspecified field is initialized from `1970-01-01
- 00:00:00.0`. This initialization value uses the time zone specified by the
- function's time zone argument, if present. If not, the initialization value
- uses the default time zone, which is implementation defined. For instance, if the year
- is unspecified then it defaults to `1970`, and so on.
-+ **Case insensitivity.** Names, such as `Monday`, `February`, and so on, are
- case insensitive.
-+ **Whitespace.** One or more consecutive white spaces in the format string
- matches zero or more consecutive white spaces in the timestamp string. In
- addition, leading and trailing white spaces in the timestamp string are always
- allowed, even if they are not in the format string.
-+ **Format precedence.** When two (or more) format elements have overlapping
- information (for example both `%F` and `%Y` affect the year), the last one
- generally overrides any earlier ones, with some exceptions (see the
- descriptions of `%s`, `%C`, and `%y`).
-+ **Format divergence.** `%p` can be used with `am`, `AM`, `pm`, and `PM`.
++ `value_expression` can be any data type that can be returned from an
+ expression.
++ `constant_integer_expression` can be any constant expression that returns an
+ integer.
**Return Data Type**
-`TIMESTAMP`
+Same type as `value_expression`.
-**Example**
+**Examples**
```sql
-SELECT PARSE_TIMESTAMP("%c", "Thu Dec 25 07:30:00 2008") AS parsed;
+WITH finishers AS
+ (SELECT 'Sophia Liu' as name,
+ TIMESTAMP '2016-10-18 2:51:45' as finish_time,
+ 'F30-34' as division
+ UNION ALL SELECT 'Lisa Stelzner', TIMESTAMP '2016-10-18 2:54:11', 'F35-39'
+ UNION ALL SELECT 'Nikki Leith', TIMESTAMP '2016-10-18 2:59:01', 'F30-34'
+ UNION ALL SELECT 'Lauren Matthews', TIMESTAMP '2016-10-18 3:01:17', 'F35-39'
+ UNION ALL SELECT 'Desiree Berry', TIMESTAMP '2016-10-18 3:05:42', 'F35-39'
+ UNION ALL SELECT 'Suzy Slane', TIMESTAMP '2016-10-18 3:06:24', 'F35-39'
+ UNION ALL SELECT 'Jen Edwards', TIMESTAMP '2016-10-18 3:06:36', 'F30-34'
+ UNION ALL SELECT 'Meghan Lederer', TIMESTAMP '2016-10-18 3:07:41', 'F30-34'
+ UNION ALL SELECT 'Carly Forte', TIMESTAMP '2016-10-18 3:08:58', 'F25-29'
+ UNION ALL SELECT 'Lauren Reasoner', TIMESTAMP '2016-10-18 3:10:14', 'F30-34')
+SELECT name,
+ FORMAT_TIMESTAMP('%X', finish_time) AS finish_time,
+ division,
+ FORMAT_TIMESTAMP('%X', fastest_time) AS fastest_time,
+ FORMAT_TIMESTAMP('%X', second_fastest) AS second_fastest
+FROM (
+ SELECT name,
+ finish_time,
+ division,finishers,
+ FIRST_VALUE(finish_time)
+ OVER w1 AS fastest_time,
+ NTH_VALUE(finish_time, 2)
+ OVER w1 as second_fastest
+ FROM finishers
+ WINDOW w1 AS (
+ PARTITION BY division ORDER BY finish_time ASC
+ ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING));
--- Display of results may differ, depending upon the environment and time zone where this query was executed.
-/*---------------------------------------------*
- | parsed |
- +---------------------------------------------+
- | 2008-12-25 07:30:00.000 America/Los_Angeles |
- *---------------------------------------------*/
+/*-----------------+-------------+----------+--------------+----------------*
+ | name | finish_time | division | fastest_time | second_fastest |
+ +-----------------+-------------+----------+--------------+----------------+
+ | Carly Forte | 03:08:58 | F25-29 | 03:08:58 | NULL |
+ | Sophia Liu | 02:51:45 | F30-34 | 02:51:45 | 02:59:01 |
+ | Nikki Leith | 02:59:01 | F30-34 | 02:51:45 | 02:59:01 |
+ | Jen Edwards | 03:06:36 | F30-34 | 02:51:45 | 02:59:01 |
+ | Meghan Lederer | 03:07:41 | F30-34 | 02:51:45 | 02:59:01 |
+ | Lauren Reasoner | 03:10:14 | F30-34 | 02:51:45 | 02:59:01 |
+ | Lisa Stelzner | 02:54:11 | F35-39 | 02:54:11 | 03:01:17 |
+ | Lauren Matthews | 03:01:17 | F35-39 | 02:54:11 | 03:01:17 |
+ | Desiree Berry | 03:05:42 | F35-39 | 02:54:11 | 03:01:17 |
+ | Suzy Slane | 03:06:24 | F35-39 | 02:54:11 | 03:01:17 |
+ *-----------------+-------------+----------+--------------+----------------*/
```
-[timestamp-format]: #format_timestamp
+### `PERCENTILE_CONT`
-[timestamp-format-elements]: https://github.com/google/zetasql/blob/master/docs/format-elements.md#format_elements_date_time
+```sql
+PERCENTILE_CONT (value_expression, percentile [{RESPECT | IGNORE} NULLS])
+OVER over_clause
-### `STRING`
+over_clause:
+ { named_window | ( [ window_specification ] ) }
+
+window_specification:
+ [ named_window ]
+ [ PARTITION BY partition_expression [, ...] ]
-```sql
-STRING(timestamp_expression[, time_zone])
```
**Description**
-Converts a timestamp to a string. Supports an optional
-parameter to specify a time zone. See
-[Time zone definitions][timestamp-link-to-timezone-definitions] for information
-on how to specify a time zone.
+Computes the specified percentile value for the value_expression, with linear
+interpolation.
-**Return Data Type**
+This function ignores NULL
+values if
+`RESPECT NULLS` is absent. If `RESPECT NULLS` is present:
-`STRING`
++ Interpolation between two `NULL` values returns `NULL`.
++ Interpolation between a `NULL` value and a non-`NULL` value returns the
+ non-`NULL` value.
-**Example**
+To learn more about the `OVER` clause and how to use it, see
+[Window function calls][window-function-calls].
-```sql
-SELECT STRING(TIMESTAMP "2008-12-25 15:30:00+00", "UTC") AS string;
+
-/*-------------------------------*
- | string |
- +-------------------------------+
- | 2008-12-25 15:30:00+00 |
- *-------------------------------*/
-```
+[window-function-calls]: https://github.com/google/zetasql/blob/master/docs/window-function-calls.md
-[timestamp-link-to-timezone-definitions]: #timezone_definitions
+
-### `TIMESTAMP`
+`PERCENTILE_CONT` can be used with differential privacy. To learn more, see
+[Differentially private aggregate functions][dp-functions].
-```sql
-TIMESTAMP(string_expression[, time_zone])
-TIMESTAMP(date_expression[, time_zone])
-TIMESTAMP(datetime_expression[, time_zone])
-```
+**Supported Argument Types**
-**Description**
++ `value_expression` and `percentile` must have one of the following types:
+ + `NUMERIC`
+ + `BIGNUMERIC`
+ + `DOUBLE`
++ `percentile` must be a literal in the range `[0, 1]`.
-+ `string_expression[, time_zone]`: Converts a string to a
- timestamp. `string_expression` must include a
- timestamp literal.
- If `string_expression` includes a time zone in the timestamp literal, do
- not include an explicit `time_zone`
- argument.
-+ `date_expression[, time_zone]`: Converts a date to a timestamp.
- The value returned is the earliest timestamp that falls within
- the given date.
-+ `datetime_expression[, time_zone]`: Converts a
- datetime to a timestamp.
+**Return Data Type**
-This function supports an optional
-parameter to [specify a time zone][timestamp-link-to-timezone-definitions]. If
-no time zone is specified, the default time zone, which is implementation defined,
-is used.
+The return data type is determined by the argument types with the following
+table.
+INPUT | NUMERIC | BIGNUMERIC | DOUBLE |
+
---|---|---|---|
NUMERIC | NUMERIC | BIGNUMERIC | DOUBLE |
BIGNUMERIC | BIGNUMERIC | BIGNUMERIC | DOUBLE |
DOUBLE | DOUBLE | DOUBLE | DOUBLE |
Name | +Summary | +
---|---|
NET.FORMAT_IP
-/*---------------*
- | negative_diff |
- +---------------+
- | -61 |
- *---------------+
-```
+ |
+
+ (Deprecated) Converts an
+ IPv4 address from an INT64 value to a
+ STRING value.
+ |
+
NET.FORMAT_PACKED_IP
-```sql
-SELECT TIMESTAMP_DIFF("2001-02-01 01:00:00", "2001-02-01 00:00:01", HOUR) AS diff;
+ |
+
+ (Deprecated) Converts an
+ IPv4 or IPv6 address from a BYTES value to a
+ STRING value.
+ |
+
NET.HOST
-### `TIMESTAMP_FROM_UNIX_MICROS`
+ |
+ + Gets the hostname from a URL. + | +
NET.IP_FROM_STRING
-```sql
-TIMESTAMP_FROM_UNIX_MICROS(timestamp_expression)
-```
+ |
+
+ Converts an IPv4 or IPv6 address from a STRING value to
+ a BYTES value in network byte order.
+ |
+
NET.IP_IN_NET
-Interprets `int64_expression` as the number of microseconds since
-1970-01-01 00:00:00 UTC and returns a timestamp. If a timestamp is passed in,
-the same timestamp is returned.
+ |
+ + Checks if an IP address is in a subnet. + | +
NET.IP_NET_MASK
-`TIMESTAMP`
+ |
+ + Gets a network mask. + | +
NET.IP_TO_STRING
-```sql
-SELECT TIMESTAMP_FROM_UNIX_MICROS(1230219000000000) AS timestamp_value;
+ |
+
+ Converts an IPv4 or IPv6 address from a BYTES value in
+ network byte order to a STRING value.
+ |
+
NET.IP_TRUNC
-### `TIMESTAMP_FROM_UNIX_MILLIS`
+ |
+
+ Converts a BYTES IPv4 or IPv6 address in
+ network byte order to a BYTES subnet address.
+ |
+
NET.IPV4_FROM_INT64
-```sql
-TIMESTAMP_FROM_UNIX_MILLIS(timestamp_expression)
-```
+ |
+
+ Converts an IPv4 address from an INT64 value to a
+ BYTES value in network byte order.
+ |
+
NET.IPV4_TO_INT64
-Interprets `int64_expression` as the number of milliseconds since
-1970-01-01 00:00:00 UTC and returns a timestamp. If a timestamp is passed in,
-the same timestamp is returned.
+ |
+
+ Converts an IPv4 address from a BYTES value in network
+ byte order to an INT64 value.
+ |
+
NET.MAKE_NET
-`TIMESTAMP`
+ |
+ + Takes a IPv4 or IPv6 address and the prefix length, and produces a + CIDR subnet. + | +
NET.PARSE_IP
-```sql
-SELECT TIMESTAMP_FROM_UNIX_MILLIS(1230219000000) AS timestamp_value;
+ |
+
+ (Deprecated) Converts an
+ IPv4 address from a STRING value to an
+ INT64 value.
+ |
+
NET.PARSE_PACKED_IP
-### `TIMESTAMP_FROM_UNIX_SECONDS`
+ |
+
+ (Deprecated) Converts an
+ IPv4 or IPv6 address from a STRING value to a
+ BYTES value.
+ |
+
NET.PUBLIC_SUFFIX
-```sql
-TIMESTAMP_FROM_UNIX_SECONDS(timestamp_expression)
-```
+ |
+ + Gets the public suffix from a URL. + | +
NET.REG_DOMAIN
-Interprets `int64_expression` as the number of seconds since
-1970-01-01 00:00:00 UTC and returns a timestamp. If a timestamp is passed in,
-the same timestamp is returned.
+ |
+ + Gets the registered or registrable domain from a URL. + | +
NET.SAFE_IP_FROM_STRING
-`TIMESTAMP`
+ |
+
+ Similar to the NET.IP_FROM_STRING , but returns
+ NULL instead of producing an error if the input is invalid.
+ |
+
Name | -Summary | -
---|---|
EXTRACT
+This function supports the following formats for `address`:
- |
-
- Extracts part of an INTERVAL value.
- |
-
JUSTIFY_DAYS
+If this function receives a `NULL` input, it returns `NULL`. If the input is
+considered invalid, an `OUT_OF_RANGE` error occurs.
- |
-
- Normalizes the day part of an INTERVAL value.
- |
-
JUSTIFY_HOURS
+STRING
- |
-
- Normalizes the time part of an INTERVAL value.
- |
-
JUSTIFY_INTERVAL
+### `NET.PARSE_IP` (DEPRECATED)
+
- |
-
- Normalizes the day and time parts of an INTERVAL value.
- |
-
MAKE_INTERVAL
+**Description**
- |
-
- Constructs an INTERVAL value.
- |
-
Category | -Functions | -Description | -
Constructors | -
- ST_GEOGPOINT - ST_MAKELINE - ST_MAKEPOLYGON - ST_MAKEPOLYGONORIENTED
- |
- - Functions that build new - geography values from coordinates - or existing geographies. - | -
Parsers | -
- ST_GEOGFROM - ST_GEOGFROMGEOJSON - ST_GEOGFROMKML - ST_GEOGFROMTEXT - ST_GEOGFROMWKB - ST_GEOGPOINTFROMGEOHASH - |
- - Functions that create geographies - from an external format such as - WKT and - GeoJSON. - | -
Formatters | -
- ST_ASBINARY - ST_ASGEOJSON - ST_ASKML - ST_ASTEXT - ST_GEOHASH
- |
- - Functions that export geographies - to an external format such as WKT. - | -
Transformations | -
- ST_ACCUM (Aggregate)- ST_BOUNDARY - ST_BUFFER - ST_BUFFERWITHTOLERANCE - ST_CENTROID - ST_CENTROID_AGG (Aggregate)- ST_CLOSESTPOINT - ST_CONVEXHULL - ST_DIFFERENCE - ST_EXTERIORRING - ST_INTERIORRINGS - ST_INTERSECTION - ST_LINESUBSTRING - ST_SIMPLIFY - ST_SNAPTOGRID - ST_UNION - ST_UNION_AGG (Aggregate)- |
- - Functions that generate a new - geography based on input. - | -
Accessors | -
- ST_DIMENSION - ST_DUMP - ST_DUMPPOINTS - ST_ENDPOINT - ST_GEOMETRYTYPE - ST_ISCLOSED - ST_ISCOLLECTION - ST_ISEMPTY - ST_ISRING - ST_NPOINTS - ST_NUMGEOMETRIES - ST_NUMPOINTS - ST_POINTN - ST_STARTPOINT - ST_X - ST_Y - |
- - Functions that provide access to - properties of a geography without - side-effects. - | -
Predicates | -
- ST_CONTAINS - ST_COVEREDBY - ST_COVERS - ST_DISJOINT - ST_DWITHIN - ST_EQUALS - ST_INTERSECTS - ST_INTERSECTSBOX - ST_TOUCHES - ST_WITHIN - |
-
- Functions that return TRUE or
- FALSE for some spatial
- relationship between two
- geographies or some property of
- a geography. These functions
- are commonly used in filter
- clauses.
- |
-
Measures | -
- ST_ANGLE - ST_AREA - ST_AZIMUTH - ST_BOUNDINGBOX - ST_DISTANCE - ST_EXTENT (Aggregate)- ST_HAUSDORFFDISTANCE - ST_LINELOCATEPOINT - ST_LENGTH - ST_MAXDISTANCE - ST_PERIMETER - |
- - Functions that compute measurements - of one or more geographies. - | -
Clustering | -
- ST_CLUSTERDBSCAN
- |
- - Functions that perform clustering on geographies. - | -
ST_ACCUM
+ CUME_DIST
GEOGRAPHY
values into an array of
- GEOGRAPHY
elements.
+ Gets the cumulative distribution (relative position (0,1]) of each row
+ within a window.
ST_ANGLE
+ DENSE_RANK
GEOGRAPHY
values, which represent two
- intersecting lines, and returns the angle between these lines.
+ Gets the dense rank (1-based, no gaps) of each row within a window.
ST_AREA
+ NTILE
GEOGRAPHY
value.
+ Gets the quantile bucket number (1-based) of each row within a window.
ST_ASBINARY
+ PERCENT_RANK
GEOGRAPHY
value to a
- BYTES
WKB geography value.
+ Gets the percentile rank (from 0 to 1) of each row within a window.
ST_ASGEOJSON
+ RANK
GEOGRAPHY
value to a STRING
- GeoJSON geography value.
+ Gets the rank (1-based) of each row within a window.
ST_ASKML
+ ROW_NUMBER
GEOGRAPHY
value to a STRING
- KML geometry value.
+ Gets the sequential row number (1-based) of each row within a window.
ST_ASTEXT
-
-GEOGRAPHY
value to a
- STRING
WKT geography value.
- ST_AZIMUTH
+### `CUME_DIST`
-GEOGRAPHY
values.
- ST_BOUNDARY
+over_clause:
+ { named_window | ( [ window_specification ] ) }
-GEOGRAPHY
value.
- ST_BOUNDINGBOX
+```
-GEOGRAPHY
value.
- ST_BUFFER
+Return the relative rank of a row defined as NP/NR. NP is defined to be the
+number of rows that either precede or are peers with the current row. NR is the
+number of rows in the partition.
-GEOGRAPHY
value, using a specific
- number of segments.
- ST_BUFFERWITHTOLERANCE
+
-GEOGRAPHY
value, using tolerance.
- ST_CENTROID
+
-GEOGRAPHY
value.
- ST_CLOSESTPOINT
+`DOUBLE`
-GEOGRAPHY
value which is closest to any
- point in a second GEOGRAPHY
value.
- ST_CLUSTERDBSCAN
+```sql
+WITH finishers AS
+ (SELECT 'Sophia Liu' as name,
+ TIMESTAMP '2016-10-18 2:51:45' as finish_time,
+ 'F30-34' as division
+ UNION ALL SELECT 'Lisa Stelzner', TIMESTAMP '2016-10-18 2:54:11', 'F35-39'
+ UNION ALL SELECT 'Nikki Leith', TIMESTAMP '2016-10-18 2:59:01', 'F30-34'
+ UNION ALL SELECT 'Lauren Matthews', TIMESTAMP '2016-10-18 3:01:17', 'F35-39'
+ UNION ALL SELECT 'Desiree Berry', TIMESTAMP '2016-10-18 3:05:42', 'F35-39'
+ UNION ALL SELECT 'Suzy Slane', TIMESTAMP '2016-10-18 3:06:24', 'F35-39'
+ UNION ALL SELECT 'Jen Edwards', TIMESTAMP '2016-10-18 3:06:36', 'F30-34'
+ UNION ALL SELECT 'Meghan Lederer', TIMESTAMP '2016-10-18 2:59:01', 'F30-34')
+SELECT name,
+ finish_time,
+ division,
+ CUME_DIST() OVER (PARTITION BY division ORDER BY finish_time ASC) AS finish_rank
+FROM finishers;
-GEOGRAPHY
values and
- produces a 0-based cluster number for this row.
- ST_CONTAINS
-
-GEOGRAPHY
value contains another
- GEOGRAPHY
value.
- ST_CONVEXHULL
+### `DENSE_RANK`
-GEOGRAPHY
value.
- ST_COVEREDBY
+over_clause:
+ { named_window | ( [ window_specification ] ) }
-GEOGRAPHY
value are on the boundary
- or interior of another GEOGRAPHY
value.
- ST_COVERS
+```
-GEOGRAPHY
value are on the boundary
- or interior of another GEOGRAPHY
value.
- ST_DIFFERENCE
+Returns the ordinal (1-based) rank of each row within the window partition.
+All peer rows receive the same rank value, and the subsequent rank value is
+incremented by one.
-GEOGRAPHY
values.
- ST_DIMENSION
+
-GEOGRAPHY
value.
- ST_DISJOINT
+
-GEOGRAPHY
values are disjoint (do not intersect).
- ST_DISTANCE
+`INT64`
-GEOGRAPHY
- values.
- ST_DUMP
+```sql
+WITH Numbers AS
+ (SELECT 1 as x
+ UNION ALL SELECT 2
+ UNION ALL SELECT 2
+ UNION ALL SELECT 5
+ UNION ALL SELECT 8
+ UNION ALL SELECT 10
+ UNION ALL SELECT 10
+)
+SELECT x,
+ DENSE_RANK() OVER (ORDER BY x ASC) AS dense_rank
+FROM Numbers
-GEOGRAPHY
components in a
- GEOGRAPHY
value.
- ST_DUMPPOINTS
+```sql
+WITH finishers AS
+ (SELECT 'Sophia Liu' as name,
+ TIMESTAMP '2016-10-18 2:51:45' as finish_time,
+ 'F30-34' as division
+ UNION ALL SELECT 'Lisa Stelzner', TIMESTAMP '2016-10-18 2:54:11', 'F35-39'
+ UNION ALL SELECT 'Nikki Leith', TIMESTAMP '2016-10-18 2:59:01', 'F30-34'
+ UNION ALL SELECT 'Lauren Matthews', TIMESTAMP '2016-10-18 3:01:17', 'F35-39'
+ UNION ALL SELECT 'Desiree Berry', TIMESTAMP '2016-10-18 3:05:42', 'F35-39'
+ UNION ALL SELECT 'Suzy Slane', TIMESTAMP '2016-10-18 3:06:24', 'F35-39'
+ UNION ALL SELECT 'Jen Edwards', TIMESTAMP '2016-10-18 3:06:36', 'F30-34'
+ UNION ALL SELECT 'Meghan Lederer', TIMESTAMP '2016-10-18 2:59:01', 'F30-34')
+SELECT name,
+ finish_time,
+ division,
+ DENSE_RANK() OVER (PARTITION BY division ORDER BY finish_time ASC) AS finish_rank
+FROM finishers;
-GEOGRAPHY
points with all points, line
- vertices, and polygon vertices in a GEOGRAPHY
value.
- ST_DWITHIN
+### `NTILE`
-GEOGRAPHY
values are within a given
- distance.
- ST_ENDPOINT
+over_clause:
+ { named_window | ( [ window_specification ] ) }
-GEOGRAPHY
value.
- ST_EQUALS
+```
-GEOGRAPHY
values represent the same
- GEOGRAPHY
value.
- ST_EXTENT
+This function divides the rows into `constant_integer_expression`
+buckets based on row ordering and returns the 1-based bucket number that is
+assigned to each row. The number of rows in the buckets can differ by at most 1.
+The remainder values (the remainder of number of rows divided by buckets) are
+distributed one for each bucket, starting with bucket 1. If
+`constant_integer_expression` evaluates to NULL, 0 or negative, an
+error is provided.
-GEOGRAPHY
values.
- ST_EXTERIORRING
+
-GEOGRAPHY
value that corresponds to the
- outermost ring of a polygon GEOGRAPHY
value.
- ST_GEOGFROM
+
-STRING
or BYTES
value
- into a GEOGRAPHY
value.
- ST_GEOGFROMGEOJSON
+`INT64`
-STRING
GeoJSON geometry value into a
- GEOGRAPHY
value.
- ST_GEOGFROMKML
+```sql
+WITH finishers AS
+ (SELECT 'Sophia Liu' as name,
+ TIMESTAMP '2016-10-18 2:51:45' as finish_time,
+ 'F30-34' as division
+ UNION ALL SELECT 'Lisa Stelzner', TIMESTAMP '2016-10-18 2:54:11', 'F35-39'
+ UNION ALL SELECT 'Nikki Leith', TIMESTAMP '2016-10-18 2:59:01', 'F30-34'
+ UNION ALL SELECT 'Lauren Matthews', TIMESTAMP '2016-10-18 3:01:17', 'F35-39'
+ UNION ALL SELECT 'Desiree Berry', TIMESTAMP '2016-10-18 3:05:42', 'F35-39'
+ UNION ALL SELECT 'Suzy Slane', TIMESTAMP '2016-10-18 3:06:24', 'F35-39'
+ UNION ALL SELECT 'Jen Edwards', TIMESTAMP '2016-10-18 3:06:36', 'F30-34'
+ UNION ALL SELECT 'Meghan Lederer', TIMESTAMP '2016-10-18 2:59:01', 'F30-34')
+SELECT name,
+ finish_time,
+ division,
+ NTILE(3) OVER (PARTITION BY division ORDER BY finish_time ASC) AS finish_rank
+FROM finishers;
-STRING
KML geometry value into a
- GEOGRAPHY
value.
- ST_GEOGFROMTEXT
+### `PERCENT_RANK`
-STRING
WKT geometry value into a
- GEOGRAPHY
value.
- ST_GEOGFROMWKB
+over_clause:
+ { named_window | ( [ window_specification ] ) }
-BYTES
or hexadecimal-text STRING
WKT
- geometry value into a GEOGRAPHY
value.
- ST_GEOGPOINT
+```
-GEOGRAPHY
value for a given longitude and
- latitude.
- ST_GEOGPOINTFROMGEOHASH
+Return the percentile rank of a row defined as (RK-1)/(NR-1), where RK is
+the `RANK` of the row and NR is the number of rows in the partition.
+Returns 0 if NR=1.
-GEOGRAPHY
value that is in the middle of a
- bounding box defined in a STRING
GeoHash value.
- ST_GEOHASH
+
-GEOGRAPHY
value to a STRING
- GeoHash value.
- ST_GEOMETRYTYPE
+
-GEOGRAPHY
value.
- ST_HAUSDORFFDISTANCE
+`DOUBLE`
-ST_INTERIORRINGS
+```sql
+WITH finishers AS
+ (SELECT 'Sophia Liu' as name,
+ TIMESTAMP '2016-10-18 2:51:45' as finish_time,
+ 'F30-34' as division
+ UNION ALL SELECT 'Lisa Stelzner', TIMESTAMP '2016-10-18 2:54:11', 'F35-39'
+ UNION ALL SELECT 'Nikki Leith', TIMESTAMP '2016-10-18 2:59:01', 'F30-34'
+ UNION ALL SELECT 'Lauren Matthews', TIMESTAMP '2016-10-18 3:01:17', 'F35-39'
+ UNION ALL SELECT 'Desiree Berry', TIMESTAMP '2016-10-18 3:05:42', 'F35-39'
+ UNION ALL SELECT 'Suzy Slane', TIMESTAMP '2016-10-18 3:06:24', 'F35-39'
+ UNION ALL SELECT 'Jen Edwards', TIMESTAMP '2016-10-18 3:06:36', 'F30-34'
+ UNION ALL SELECT 'Meghan Lederer', TIMESTAMP '2016-10-18 2:59:01', 'F30-34')
+SELECT name,
+ finish_time,
+ division,
+ PERCENT_RANK() OVER (PARTITION BY division ORDER BY finish_time ASC) AS finish_rank
+FROM finishers;
-GEOGRAPHY
value.
- ST_INTERSECTION
+### `RANK`
-GEOGRAPHY
values.
- ST_INTERSECTS
+over_clause:
+ { named_window | ( [ window_specification ] ) }
-GEOGRAPHY
- values.
- ST_INTERSECTSBOX
+```
-GEOGRAPHY
value intersects a rectangle.
- ST_ISCLOSED
+Returns the ordinal (1-based) rank of each row within the ordered partition.
+All peer rows receive the same rank value. The next row or set of peer rows
+receives a rank value which increments by the number of peers with the previous
+rank value, instead of `DENSE_RANK`, which always increments by 1.
-GEOGRAPHY
value are closed.
- ST_ISCOLLECTION
+
-GEOGRAPHY
value.
- ST_ISEMPTY
+
-GEOGRAPHY
value is empty.
- ST_ISRING
+`INT64`
-GEOGRAPHY
value is a closed, simple
- linestring.
- ST_LENGTH
+```sql
+WITH Numbers AS
+ (SELECT 1 as x
+ UNION ALL SELECT 2
+ UNION ALL SELECT 2
+ UNION ALL SELECT 5
+ UNION ALL SELECT 8
+ UNION ALL SELECT 10
+ UNION ALL SELECT 10
+)
+SELECT x,
+ RANK() OVER (ORDER BY x ASC) AS rank
+FROM Numbers
-GEOGRAPHY
value.
- ST_LINELOCATEPOINT
+```sql
+WITH finishers AS
+ (SELECT 'Sophia Liu' as name,
+ TIMESTAMP '2016-10-18 2:51:45' as finish_time,
+ 'F30-34' as division
+ UNION ALL SELECT 'Lisa Stelzner', TIMESTAMP '2016-10-18 2:54:11', 'F35-39'
+ UNION ALL SELECT 'Nikki Leith', TIMESTAMP '2016-10-18 2:59:01', 'F30-34'
+ UNION ALL SELECT 'Lauren Matthews', TIMESTAMP '2016-10-18 3:01:17', 'F35-39'
+ UNION ALL SELECT 'Desiree Berry', TIMESTAMP '2016-10-18 3:05:42', 'F35-39'
+ UNION ALL SELECT 'Suzy Slane', TIMESTAMP '2016-10-18 3:06:24', 'F35-39'
+ UNION ALL SELECT 'Jen Edwards', TIMESTAMP '2016-10-18 3:06:36', 'F30-34'
+ UNION ALL SELECT 'Meghan Lederer', TIMESTAMP '2016-10-18 2:59:01', 'F30-34')
+SELECT name,
+ finish_time,
+ division,
+ RANK() OVER (PARTITION BY division ORDER BY finish_time ASC) AS finish_rank
+FROM finishers;
-GEOGRAPHY
value between the
- start point and a point GEOGRAPHY
value.
- ST_LINESUBSTRING
+### `ROW_NUMBER`
-ST_MAKELINE
+over_clause:
+ { named_window | ( [ window_specification ] ) }
-GEOGRAPHY
value by concatenating the point
- and linestring vertices of GEOGRAPHY
values.
- ST_MAKEPOLYGON
+```
-GEOGRAPHY
value by combining
- a polygon shell with polygon holes.
- ST_MAKEPOLYGONORIENTED
+Does not require the `ORDER BY` clause. Returns the sequential
+row ordinal (1-based) of each row for each ordered partition. If the
+`ORDER BY` clause is unspecified then the result is
+non-deterministic.
-GEOGRAPHY
value, using an array of
- linestring GEOGRAPHY
values. The vertex ordering of each
- linestring determines the orientation of each polygon ring.
- ST_MAXDISTANCE
+
-GEOGRAPHY
values.
- ST_NPOINTS
+
-ST_NUMPOINTS
.
- ST_NUMGEOMETRIES
+`INT64`
-GEOGRAPHY
value.
- ST_NUMPOINTS
+```sql
+WITH Numbers AS
+ (SELECT 1 as x
+ UNION ALL SELECT 2
+ UNION ALL SELECT 2
+ UNION ALL SELECT 5
+ UNION ALL SELECT 8
+ UNION ALL SELECT 10
+ UNION ALL SELECT 10
+)
+SELECT x,
+ ROW_NUMBER() OVER (ORDER BY x) AS row_num
+FROM Numbers
-GEOGRAPHY
value.
- ST_PERIMETER
+```sql
+WITH finishers AS
+ (SELECT 'Sophia Liu' as name,
+ TIMESTAMP '2016-10-18 2:51:45' as finish_time,
+ 'F30-34' as division
+ UNION ALL SELECT 'Lisa Stelzner', TIMESTAMP '2016-10-18 2:54:11', 'F35-39'
+ UNION ALL SELECT 'Nikki Leith', TIMESTAMP '2016-10-18 2:59:01', 'F30-34'
+ UNION ALL SELECT 'Lauren Matthews', TIMESTAMP '2016-10-18 3:01:17', 'F35-39'
+ UNION ALL SELECT 'Desiree Berry', TIMESTAMP '2016-10-18 3:05:42', 'F35-39'
+ UNION ALL SELECT 'Suzy Slane', TIMESTAMP '2016-10-18 3:06:24', 'F35-39'
+ UNION ALL SELECT 'Jen Edwards', TIMESTAMP '2016-10-18 3:06:36', 'F30-34'
+ UNION ALL SELECT 'Meghan Lederer', TIMESTAMP '2016-10-18 2:59:01', 'F30-34')
+SELECT name,
+ finish_time,
+ division,
+ ROW_NUMBER() OVER (PARTITION BY division ORDER BY finish_time ASC) AS finish_rank
+FROM finishers;
-GEOGRAPHY
value.
- ST_POINTN
+
-GEOGRAPHY
- value.
- ST_SIMPLIFY
+
-GEOGRAPHY
value into a simplified
- GEOGRAPHY
value, using tolerance.
- Name | +Summary | +|
---|---|---|
ST_SNAPTOGRID
+ | CONTAINS_KEY
|
- Produces a GEOGRAPHY value, where each vertex has
- been snapped to a longitude/latitude grid.
+ Checks if a protocol buffer map field contains a given key.
|
ST_STARTPOINT
+ | EXTRACT
|
- Gets the first point of a linestring GEOGRAPHY value.
+ Extracts a value or metadata from a protocol buffer.
|
ST_TOUCHES
+ | FILTER_FIELDS
|
- Checks if two GEOGRAPHY values intersect and their interiors
- have no elements in common.
+ Removed unwanted fields from a protocol buffer.
|
ST_UNION
+ | FROM_PROTO
|
- Gets the point set union of multiple GEOGRAPHY values.
+ Converts a protocol buffer value into ZetaSQL value.
|
ST_UNION_AGG
+ | MODIFY_MAP
|
- Aggregates over GEOGRAPHY values and gets their
- point set union.
+ Modifies a protocol buffer map field.
|
ST_WITHIN
+ | PROTO_DEFAULT_IF_NULL
|
- Checks if one GEOGRAPHY value contains another
- GEOGRAPHY value.
+ Produces the default protocol buffer field value if the
+ protocol buffer field is NULL . Otherwise, returns the
+ protocol buffer field value.
|
ST_X
+ | REPLACE_FIELDS
|
- Gets the longitude from a point GEOGRAPHY value.
+ Replaces the values in one or more protocol buffer fields.
|
ST_Y
+ | TO_PROTO
|
- Gets the latitude from a point GEOGRAPHY value.
+ Converts a ZetaSQL value into a protocol buffer value.
|
expression type |
+ Return type | +
---|---|
+
|
+ INT32 | +
+
|
+ UINT32 | +
+
|
+ INT64 | +
+
|
+ UINT64 | +
+
|
+ FLOAT | +
+
|
+ DOUBLE | +
+
|
+ BOOL | +
+
|
+ STRING | +
+
|
+ BYTES | +
+
|
+ DATE | +
+
|
+ TIME | +
+
|
+ TIMESTAMP | +
expression type |
+ Return type | +
---|---|
+
|
+ google.protobuf.Int32Value | +
+
|
+ google.protobuf.UInt32Value | +
+
|
+ google.protobuf.Int64Value | +
+
|
+ google.protobuf.UInt64Value | +
+
|
+ google.protobuf.FloatValue | +
+
|
+ google.protobuf.DoubleValue | +
+
|
+ google.protobuf.BoolValue | +
+
|
+ google.protobuf.StringValue | +
+
|
+ google.protobuf.BytesValue | +
+
|
+ google.type.Date | +
+
|
+ google.type.TimeOfDay | +
+
|
+ google.protobuf.Timestamp | +
Name | +Summary | +
---|---|
GENERATE_RANGE_ARRAY
+
+ |
+ Splits a range into an array of subranges. | +
RANGE
+
+ |
+
+ Constructs a range of DATE , DATETIME ,
+ or TIMESTAMP values.
+ |
+
RANGE_CONTAINS
+
+ |
+
+ Signature 1: Checks if one range is in another range.
+ + Signature 2: Checks if a value is in a range. + |
+
RANGE_END
+
+ |
+ Gets the upper bound of a range. | +
RANGE_INTERSECT
+
+ |
+ Gets a segment of two ranges that intersect. | +
RANGE_OVERLAPS
+
+ |
+ Checks if two ranges overlap. | +
RANGE_SESSIONIZE
+
+ |
+ Produces a table of sessionized ranges. | +
RANGE_START
+
+ |
+ Gets the lower bound of a range. | +
Name | +Summary | +
---|---|
SESSION_USER
+
+ |
+ + Get the email address or principal identifier of the user that is running + the query. + | +
Name | +Summary | +
---|---|
CORR
+
+ |
+ + Computes the Pearson coefficient of correlation of a set of number pairs. + | +
COVAR_POP
+
+ |
+ + Computes the population covariance of a set of number pairs. + | +
COVAR_SAMP
+
+ |
+ + Computes the sample covariance of a set of number pairs. + | +
STDDEV
+
+ |
+
+ An alias of the STDDEV_SAMP function.
+ |
+
STDDEV_POP
+
+ |
+ + Computes the population (biased) standard deviation of the values. + | +
STDDEV_SAMP
+
+ |
+ + Computes the sample (unbiased) standard deviation of the values. + | +
VAR_POP
+
+ |
+ + Computes the population (biased) variance of the values. + | +
VAR_SAMP
+
+ |
+ + Computes the sample (unbiased) variance of the values. + | +
VARIANCE
+
+ |
+
+ An alias of VAR_SAMP .
+ |
+
Name | +Summary | +
---|---|
ASCII
+
+ |
+
+ Gets the ASCII code for the first character or byte in a STRING
+ or BYTES value.
+ |
+
BYTE_LENGTH
+
+ |
+
+ Gets the number of BYTES in a STRING or
+ BYTES value.
+ |
+
CHAR_LENGTH
+
+ |
+
+ Gets the number of characters in a STRING value.
+ |
+
CHARACTER_LENGTH
+
+ |
+
+ Synonym for CHAR_LENGTH .
+ |
+
CHR
+
+ |
+ + Converts a Unicode code point to a character. + | +
CODE_POINTS_TO_BYTES
+
+ |
+
+ Converts an array of extended ASCII code points to a
+ BYTES value.
+ |
+
CODE_POINTS_TO_STRING
+
+ |
+
+ Converts an array of extended ASCII code points to a
+ STRING value.
+ |
+
COLLATE
+
+ |
+
+ Combines a STRING value and a collation specification into a
+ collation specification-supported STRING value.
+ |
+
CONCAT
+
+ |
+
+ Concatenates one or more STRING or BYTES
+ values into a single result.
+ |
+
EDIT_DISTANCE
+
+ |
+
+ Computes the Levenshtein distance between two STRING
+ or BYTES values.
+ |
+
ENDS_WITH
+
+ |
+
+ Checks if a STRING or BYTES value is the suffix
+ of another value.
+ |
+
FORMAT
+
+ |
+
+ Formats data and produces the results as a STRING value.
+ |
+
FROM_BASE32
+
+ |
+
+ Converts a base32-encoded STRING value into a
+ BYTES value.
+ |
+
FROM_BASE64
+
+ |
+
+ Converts a base64-encoded STRING value into a
+ BYTES value.
+ |
+
FROM_HEX
+
+ |
+
+ Converts a hexadecimal-encoded STRING value into a
+ BYTES value.
+ |
+
INITCAP
+
+ |
+
+ Formats a STRING as proper case, which means that the first
+ character in each word is uppercase and all other characters are lowercase.
+ |
+
INSTR
+
+ |
+ + Finds the position of a subvalue inside another value, optionally starting + the search at a given offset or occurrence. + | +
LEFT
+
+ |
+
+ Gets the specified leftmost portion from a STRING or
+ BYTES value.
+ |
+
LENGTH
+
+ |
+
+ Gets the length of a STRING or BYTES value.
+ |
+
LOWER
+
+ |
+
+ Formats alphabetic characters in a STRING value as
+ lowercase.
+ + Formats ASCII characters in a BYTES value as
+ lowercase.
+ |
+
LPAD
+
+ |
+
+ Prepends a STRING or BYTES value with a pattern.
+ |
+
LTRIM
+
+ |
+
+ Identical to the TRIM function, but only removes leading
+ characters.
+ |
+
NORMALIZE
+
+ |
+
+ Case-sensitively normalizes the characters in a STRING value.
+ |
+
NORMALIZE_AND_CASEFOLD
+
+ |
+
+ Case-insensitively normalizes the characters in a STRING value.
+ |
+
OCTET_LENGTH
+
+ |
+
+ Alias for BYTE_LENGTH .
+ |
+
REGEXP_CONTAINS
+
+ |
+ + Checks if a value is a partial match for a regular expression. + | +
REGEXP_EXTRACT
+
+ |
+ + Produces a substring that matches a regular expression. + | +
REGEXP_EXTRACT_ALL
+
+ |
+ + Produces an array of all substrings that match a + regular expression. + | +
REGEXP_INSTR
+
+ |
+ + Finds the position of a regular expression match in a value, optionally + starting the search at a given offset or occurrence. + | +
REGEXP_MATCH
+
+ |
+ + (Deprecated) Checks if a value is a full match for a regular expression. + | +
REGEXP_REPLACE
+
+ |
+
+ Produces a STRING value where all substrings that match a
+ regular expression are replaced with a specified value.
+ |
+
REPEAT
+
+ |
+
+ Produces a STRING or BYTES value that consists of
+ an original value, repeated.
+ |
+
REPLACE
+
+ |
+
+ Replaces all occurrences of a pattern with another pattern in a
+ STRING or BYTES value.
+ |
+
REVERSE
+
+ |
+
+ Reverses a STRING or BYTES value.
+ |
+
RIGHT
+
+ |
+
+ Gets the specified rightmost portion from a STRING or
+ BYTES value.
+ |
+
RPAD
+
+ |
+
+ Appends a STRING or BYTES value with a pattern.
+ |
+
RTRIM
+
+ |
+
+ Identical to the TRIM function, but only removes trailing
+ characters.
+ |
+
SAFE_CONVERT_BYTES_TO_STRING
+
+ |
+
+ Converts a BYTES value to a STRING value and
+ replace any invalid UTF-8 characters with the Unicode replacement character,
+ U+FFFD .
+ |
+
SOUNDEX
+
+ |
+
+ Gets the Soundex codes for words in a STRING value.
+ |
+
SPLIT
+
+ |
+
+ Splits a STRING or BYTES value, using a delimiter.
+ |
+
STARTS_WITH
+
+ |
+
+ Checks if a STRING or BYTES value is a
+ prefix of another value.
+ |
+
STRPOS
+
+ |
+ + Finds the position of the first occurrence of a subvalue inside another + value. + | +
SUBSTR
+
+ |
+
+ Gets a portion of a STRING or BYTES value.
+ |
+
SUBSTRING
+
+ |
+ Alias for SUBSTR |
+
TO_BASE32
+
+ |
+
+ Converts a BYTES value to a
+ base32-encoded STRING value.
+ |
+
TO_BASE64
+
+ |
+
+ Converts a BYTES value to a
+ base64-encoded STRING value.
+ |
+
TO_CODE_POINTS
+
+ |
+
+ Converts a STRING or BYTES value into an array of
+ extended ASCII code points.
+ |
+
TO_HEX
+
+ |
+
+ Converts a BYTES value to a
+ hexadecimal STRING value.
+ |
+
TRANSLATE
+
+ |
+ + Within a value, replaces each source character with the corresponding + target character. + | +
TRIM
+
+ |
+
+ Removes the specified leading and trailing Unicode code points or bytes
+ from a STRING or BYTES value.
+ |
+
UNICODE
+
+ |
+ + Gets the Unicode code point for the first character in a value. + | +
UPPER
+
+ |
+
+ Formats alphabetic characters in a STRING value as
+ uppercase.
+ + Formats ASCII characters in a BYTES value as
+ uppercase.
+ |
+
Description | +Statement | +Result | +
---|---|---|
Simple integer | +FORMAT('%d', 10) | +10 | +
Integer with left blank padding | +FORMAT('|%10d|', 11) | +| 11| | +
Integer with left zero padding | +FORMAT('+%010d+', 12) | ++0000000012+ | +
Integer with commas | +FORMAT("%'d", 123456789) | +123,456,789 | +
STRING | +FORMAT('-%s-', 'abcd efg') | +-abcd efg- | +
DOUBLE | +FORMAT('%f %E', 1.1, 2.2) | +1.100000 2.200000E+00 | +
DATE | +FORMAT('%t', date '2015-09-01') | +2015-09-01 | +
TIMESTAMP | +FORMAT('%t', timestamp '2015-09-01 12:34:56 +America/Los_Angeles') | +2015‑09‑01 19:34:56+00 | +
Specifier | +Description | +Examples | +Types | +
d or i |
+ Decimal integer | +392 | +
+
+INT32 INT64 UINT32 UINT64 + |
+
u |
+ Unsigned integer | +7235 | +
+
+UINT32 UINT64 + |
+
o |
+
+ Octal
+ + Note: If an INT64 value is negative, an error is produced.
+ |
+ 610 | +
+
+INT32 INT64 UINT32 UINT64 + |
+
x |
+
+ Hexadecimal integer
+ + Note: If an INT64 value is negative, an error is produced.
+ |
+ 7fa | +
+
+INT32 INT64 UINT32 UINT64 + |
+
X |
+
+ Hexadecimal integer (uppercase)
+ + Note: If an INT64 value is negative, an error is produced.
+ |
+ 7FA | +
+
+INT32 INT64 UINT32 UINT64 + + |
+
f |
+ Decimal notation, in [-](integer part).(fractional part) for finite + values, and in lowercase for non-finite values | +392.650000 + inf + nan |
+
+
+NUMERIC BIGNUMERIC FLOAT DOUBLE + |
+
F |
+ Decimal notation, in [-](integer part).(fractional part) for finite + values, and in uppercase for non-finite values | +392.650000 + INF + NAN |
+
+
+NUMERIC BIGNUMERIC FLOAT DOUBLE + |
+
e |
+ Scientific notation (mantissa/exponent), lowercase | +3.926500e+02 + inf + nan |
+
+
+NUMERIC BIGNUMERIC FLOAT DOUBLE + |
+
E |
+ Scientific notation (mantissa/exponent), uppercase | +3.926500E+02 + INF + NAN |
+
+
+NUMERIC BIGNUMERIC FLOAT DOUBLE + |
+
g |
+ Either decimal notation or scientific notation, depending on the input + value's exponent and the specified precision. Lowercase. + See %g and %G behavior for details. | +392.65 + 3.9265e+07 + inf + nan |
+
+
+NUMERIC BIGNUMERIC FLOAT DOUBLE + |
+
G |
+ + Either decimal notation or scientific notation, depending on the input + value's exponent and the specified precision. Uppercase. + See %g and %G behavior for details. + | +
+ 392.65 + 3.9265E+07 + INF + NAN + |
+
+
+NUMERIC BIGNUMERIC FLOAT DOUBLE + |
+
p |
+ + + Produces a one-line printable string representing a protocol buffer + or JSON. + + See %p and %P behavior. + | +
+
+year: 2019 month: 10+ + + {"month":10,"year":2019}+ + |
+
+
+JSON PROTO + |
+
P |
+ + + Produces a multi-line printable string representing a protocol buffer + or JSON. + + See %p and %P behavior. + | +
+
++year: 2019 +month: 10 ++ + + +{ + "month": 10, + "year": 2019 +} ++ + |
+
+
+JSON PROTO + |
+
s |
+ String of characters | +sample | +
+
+STRING + |
+
t |
+
+ Returns a printable string representing the value. Often looks
+ similar to casting the argument to STRING .
+ See %t and %T behavior.
+ |
+
+ sample + 2014‑01‑01 + |
+ Any type | +
T |
+ + Produces a string that is a valid ZetaSQL constant with a + similar type to the value's type (maybe wider, or maybe string). + See %t and %T behavior. + | +
+ 'sample' + b'bytes sample' + 1234 + 2.3 + date '2014‑01‑01' + |
+ Any type | +
% |
+ '%%' produces a single '%' | +% | +n/a | +
Flags | +Description | +
- |
+ Left-justify within the given field width; Right justification is the +default (see width sub-specifier) | +
+ |
+ Forces to precede the result with a plus or minus sign (+
+or - ) even for positive numbers. By default, only negative numbers
+are preceded with a - sign |
+
<space> | +If no sign is going to be written, a blank space is inserted before the +value | +
# |
+
|
+
0 |
+ + Left-pads the number with zeroes (0) instead of spaces when padding is + specified (see width sub-specifier) | +
' |
+
+ Formats integers using the appropriating grouping character. + For example: +
This flag is only relevant for decimal, hex, and octal values. + |
+
Width | +Description | +
<number> | ++ Minimum number of characters to be printed. If the value to be printed + is shorter than this number, the result is padded with blank spaces. + The value is not truncated even if the result is larger + | +
* |
+ + The width is not specified in the format string, but as an additional + integer value argument preceding the argument that has to be formatted + | +
Precision | +Description | +
. <number> |
+
+
|
+
.* |
+ + The precision is not specified in the format string, but as an + additional integer value argument preceding the argument that has to be + formatted + | +
Type | +%p | +%P | +
PROTO | +
+ PROTO input: ++message ReleaseDate { + required int32 year = 1 [default=2019]; + required int32 month = 2 [default=10]; +}+ Produces a one-line printable string representing a protocol buffer: +year: 2019 month: 10+ |
+
+ PROTO input: ++message ReleaseDate { + required int32 year = 1 [default=2019]; + required int32 month = 2 [default=10]; +}+ Produces a multi-line printable string representing a protocol buffer: ++year: 2019 +month: 10 ++ |
+
JSON | +
+ JSON input: ++JSON ' +{ + "month": 10, + "year": 2019 +} +'+ Produces a one-line printable string representing JSON: +{"month":10,"year":2019}+ |
+
+ JSON input: ++JSON ' +{ + "month": 10, + "year": 2019 +} +'+ Produces a multi-line printable string representing JSON: ++{ + "month": 10, + "year": 2019 +} ++ |
+
Type | +%t | +%T | +
NULL of any type |
+ NULL | +NULL | +
+
+INT32 INT64 UINT32 UINT64 + |
+ 123 | +123 | +
NUMERIC | +123.0 (always with .0) + | NUMERIC "123.0" | +
FLOAT, DOUBLE | + +
+ 123.0 (always with .0) + 123e+10 inf -inf NaN
+ |
+
+ 123.0 (always with .0) + 123e+10 + CAST("inf" AS <type>) + CAST("-inf" AS <type>) + CAST("nan" AS <type>) + |
+
STRING | +unquoted string value | +quoted string literal | +
BYTES | +
+ unquoted escaped bytes + e.g., abc\x01\x02 + |
+
+ quoted bytes literal + e.g., b"abc\x01\x02" + |
+
BOOL | +boolean value | +boolean value | +
ENUM | +EnumName | +"EnumName" | +
DATE | +2011-02-03 | +DATE "2011-02-03" | +
TIMESTAMP | +2011-02-03 04:05:06+00 | +TIMESTAMP "2011-02-03 04:05:06+00" | +
INTERVAL | +1-2 3 4:5:6.789 | +INTERVAL "1-2 3 4:5:6.789" YEAR TO SECOND | +
PROTO | ++ one-line printable string representing a protocol buffer. + | ++ quoted string literal with one-line printable string representing a + protocol buffer. + | +
ARRAY | +[value, value, ...] + where values are formatted with %t |
+ [value, value, ...] + where values are formatted with %T |
+
STRUCT | +(value, value, ...) + where fields are formatted with %t |
+ (value, value, ...) + where fields are formatted with %T + + Special cases: + Zero fields: STRUCT() + One field: STRUCT(value) |
+
JSON | +
+ one-line printable string representing JSON. + {"name":"apple","stock":3}+ |
+
+ one-line printable string representing a JSON literal. + JSON '{"name":"apple","stock":3}'+ |
+
CONTAINS_KEY
+ CURRENT_TIME
TIME
value.
EXTRACT
+ EXTRACT
TIME
value.
FILTER_FIELDS
+ FORMAT_TIME
TIME
value according to the specified format string.
FROM_PROTO
+ PARSE_TIME
STRING
value to a TIME
value.
MODIFY_MAP
+ TIME
TIME
value.
PROTO_DEFAULT_IF_NULL
+ TIME_ADD
NULL
. Otherwise, returns the
- protocol buffer field value.
+ Adds a specified time interval to a TIME
value.
REPLACE_FIELDS
+ TIME_DIFF
TIME
values.
TO_PROTO
+ TIME_SUB
TIME
value.
+ TIME_TRUNC
+
+TIME
value.
expression type |
- Return type | -
---|---|
-
|
- INT32 | -
-
|
- UINT32 | -
-
|
- INT64 | -
-
|
- UINT64 | -
-
|
- FLOAT | -
-
|
- DOUBLE | -
-
|
- BOOL | -
-
|
- STRING | -
-
|
- BYTES | -
-
|
- DATE | -
-
|
- TIME | -
-
|
- TIMESTAMP | -
Name | +Summary | +
---|---|
DATE_BUCKET
-In this statement, table `library_books` contains a column named `book`,
-whose type is `Book`.
+ |
+ + Gets the lower bound of the date bucket that contains a date. + | +
DATETIME_BUCKET
-`Book` is a type that contains a field called `country`.
+ |
+ + Gets the lower bound of the datetime bucket that contains a datetime. + | +
TIMESTAMP_BUCKET
-This is the result if `book.country` evaluates to `Canada`.
+ |
+ + Gets the lower bound of the timestamp bucket that contains a timestamp. + | +
expression type |
- Return type | -
---|---|
-
|
- google.protobuf.Int32Value | -
-
|
- google.protobuf.UInt32Value | -
-
|
- google.protobuf.Int64Value | -
-
|
- google.protobuf.UInt64Value | -
-
|
- google.protobuf.FloatValue | -
-
|
- google.protobuf.DoubleValue | -
-
|
- google.protobuf.BoolValue | -
-
|
- google.protobuf.StringValue | -
-
|
- google.protobuf.BytesValue | -
-
|
- google.type.Date | -
-
|
- google.type.TimeOfDay | -
-
|
- google.protobuf.Timestamp | -
Name | -Summary | -
---|---|
SESSION_USER
++ `timestamp_in_bucket`: A `TIMESTAMP` value that you can use to look up a
+ timestamp bucket.
++ `bucket_width`: An `INTERVAL` value that represents the width of
+ a timestamp bucket. A [single interval][interval-single] with
+ [date and time parts][interval-parts] is supported.
++ `bucket_origin_timestamp`: A `TIMESTAMP` value that represents a point in
+ time. All buckets expand left and right from this point. If this argument
+ is not set, `1950-01-01 00:00:00` is used by default.
- |
- - Get the email address or principal identifier of the user that is running - the query. - | -
NET.FORMAT_IP
+ CURRENT_TIMESTAMP
INT64
value to a
- STRING
value.
+ Returns the current date and time as a TIMESTAMP
object.
NET.FORMAT_PACKED_IP
+ EXTRACT
BYTES
value to a
- STRING
value.
+ Extracts part of a TIMESTAMP
value.
NET.HOST
+ FORMAT_TIMESTAMP
TIMESTAMP
value according to the specified
+ format string.
NET.IP_FROM_STRING
+ PARSE_TIMESTAMP
STRING
value to
- a BYTES
value in network byte order.
+ Converts a STRING
value to a TIMESTAMP
value.
NET.IP_IN_NET
+ STRING
TIMESTAMP
value to a STRING
value.
NET.IP_NET_MASK
+ TIMESTAMP
TIMESTAMP
value.
NET.IP_TO_STRING
+ TIMESTAMP_ADD
BYTES
value in
- network byte order to a STRING
value.
+ Adds a specified time interval to a TIMESTAMP
value.
NET.IP_TRUNC
+ TIMESTAMP_DIFF
BYTES
IPv4 or IPv6 address in
- network byte order to a BYTES
subnet address.
+ Gets the number of intervals between two TIMESTAMP
values.
NET.IPV4_FROM_INT64
+ TIMESTAMP_FROM_UNIX_MICROS
INT64
value to a
- BYTES
value in network byte order.
+ Similar to TIMESTAMP_MICROS
, except that additionally, a
+ TIMESTAMP
value can be passed in.
NET.IPV4_TO_INT64
+ TIMESTAMP_FROM_UNIX_MILLIS
BYTES
value in network
- byte order to an INT64
value.
+ Similar to TIMESTAMP_MILLIS
, except that additionally, a
+ TIMESTAMP
value can be passed in.
NET.MAKE_NET
+ TIMESTAMP_FROM_UNIX_SECONDS
TIMESTAMP_SECONDS
, except that additionally, a
+ TIMESTAMP
value can be passed in.
NET.PARSE_IP
+ TIMESTAMP_MICROS
STRING
value to an
- INT64
value.
+ Converts the number of microseconds since
+ 1970-01-01 00:00:00 UTC to a TIMESTAMP.
NET.PARSE_PACKED_IP
+ TIMESTAMP_MILLIS
STRING
value to a
- BYTES
value.
+ Converts the number of milliseconds since
+ 1970-01-01 00:00:00 UTC to a TIMESTAMP.
NET.PUBLIC_SUFFIX
+ TIMESTAMP_SECONDS
TIMESTAMP.
NET.REG_DOMAIN
+ TIMESTAMP_SUB
TIMESTAMP
value.
NET.SAFE_IP_FROM_STRING
+ TIMESTAMP_TRUNC
NET.IP_FROM_STRING
, but returns
- NULL
instead of producing an error if the input is invalid.
+ Truncates a TIMESTAMP
value.
UNIX_MICROS
-**Description**
+TIMESTAMP
value to the number of microseconds since
+ 1970-01-01 00:00:00 UTC.
+ UNIX_MILLIS
-**Return Data Type**
+TIMESTAMP
value to the number of milliseconds
+ since 1970-01-01 00:00:00 UTC.
+ UNIX_SECONDS
-[net-link-to-ip-to-string]: #netip_to_string
+TIMESTAMP
value to the number of seconds since
+ 1970-01-01 00:00:00 UTC.
+ DATETIME
++ TIME
-If this function receives a `NULL` input, it returns `NULL`. If the input is
-considered invalid, an `OUT_OF_RANGE` error occurs.
+Returned values truncate lower order time periods. For example, when extracting
+seconds, `EXTRACT` truncates the millisecond and microsecond values.
**Return Data Type**
-BYTES
+`INT64`, except in the following cases:
-**Example**
++ If `part` is `DATE`, the function returns a `DATE` object.
+
+**Examples**
+
+In the following example, `EXTRACT` returns a value corresponding to the `DAY`
+time part.
```sql
+WITH Input AS (SELECT TIMESTAMP("2008-12-25 05:30:00+00") AS timestamp_value)
SELECT
- addr_str, FORMAT("%T", NET.IP_FROM_STRING(addr_str)) AS ip_from_string
-FROM UNNEST([
- '48.49.50.51',
- '::1',
- '3031:3233:3435:3637:3839:4041:4243:4445',
- '::ffff:192.0.2.128'
-]) AS addr_str;
+ EXTRACT(DAY FROM timestamp_value AT TIME ZONE "UTC") AS the_day_utc,
+ EXTRACT(DAY FROM timestamp_value AT TIME ZONE "America/Los_Angeles") AS the_day_california
+FROM Input
-/*---------------------------------------------------------------------------------------------------------------*
- | addr_str | ip_from_string |
- +---------------------------------------------------------------------------------------------------------------+
- | 48.49.50.51 | b"0123" |
- | ::1 | b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01" |
- | 3031:3233:3435:3637:3839:4041:4243:4445 | b"0123456789@ABCDE" |
- | ::ffff:192.0.2.128 | b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xc0\x00\x02\x80" |
- *---------------------------------------------------------------------------------------------------------------*/
+/*-------------+--------------------*
+ | the_day_utc | the_day_california |
+ +-------------+--------------------+
+ | 25 | 24 |
+ *-------------+--------------------*/
```
-[net-link-to-ipv6-rfc]: http://www.ietf.org/rfc/rfc2373.txt
-
-[net-link-to-cidr-notation]: https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing
+In the following example, `EXTRACT` returns values corresponding to different
+time parts from a column of type `TIMESTAMP`.
-### `NET.IP_IN_NET`
+```sql
+WITH Timestamps AS (
+ SELECT TIMESTAMP("2005-01-03 12:34:56+00") AS timestamp_value UNION ALL
+ SELECT TIMESTAMP("2007-12-31 12:00:00+00") UNION ALL
+ SELECT TIMESTAMP("2009-01-01 12:00:00+00") UNION ALL
+ SELECT TIMESTAMP("2009-12-31 12:00:00+00") UNION ALL
+ SELECT TIMESTAMP("2017-01-02 12:00:00+00") UNION ALL
+ SELECT TIMESTAMP("2017-05-26 12:00:00+00")
+)
+SELECT
+ timestamp_value,
+ EXTRACT(ISOYEAR FROM timestamp_value) AS isoyear,
+ EXTRACT(ISOWEEK FROM timestamp_value) AS isoweek,
+ EXTRACT(YEAR FROM timestamp_value) AS year,
+ EXTRACT(WEEK FROM timestamp_value) AS week
+FROM Timestamps
+ORDER BY timestamp_value;
+-- Display of results may differ, depending upon the environment and time zone where this query was executed.
+/*---------------------------------------------+---------+---------+------+------*
+ | timestamp_value | isoyear | isoweek | year | week |
+ +---------------------------------------------+---------+---------+------+------+
+ | 2005-01-03 04:34:56.000 America/Los_Angeles | 2005 | 1 | 2005 | 1 |
+ | 2007-12-31 04:00:00.000 America/Los_Angeles | 2008 | 1 | 2007 | 52 |
+ | 2009-01-01 04:00:00.000 America/Los_Angeles | 2009 | 1 | 2009 | 0 |
+ | 2009-12-31 04:00:00.000 America/Los_Angeles | 2009 | 53 | 2009 | 52 |
+ | 2017-01-02 04:00:00.000 America/Los_Angeles | 2017 | 1 | 2017 | 1 |
+ | 2017-05-26 05:00:00.000 America/Los_Angeles | 2017 | 21 | 2017 | 21 |
+ *---------------------------------------------+---------+---------+------+------*/
```
-NET.IP_IN_NET(address, subnet)
-```
-
-**Description**
-
-Takes an IP address and a subnet CIDR as STRING and returns true if the IP
-address is contained in the subnet.
-This function supports the following formats for `address` and `subnet`:
+In the following example, `timestamp_expression` falls on a Monday. `EXTRACT`
+calculates the first column using weeks that begin on Sunday, and it calculates
+the second column using weeks that begin on Monday.
-+ IPv4: Dotted-quad format. For example, `10.1.2.3`.
-+ IPv6: Colon-separated format. For example,
- `1234:5678:90ab:cdef:1234:5678:90ab:cdef`. For more examples, see the
- [IP Version 6 Addressing Architecture][net-link-to-ipv6-rfc].
-+ CIDR (IPv4): Dotted-quad format. For example, `10.1.2.0/24`
-+ CIDR (IPv6): Colon-separated format. For example, `1:2::/48`.
+```sql
+WITH table AS (SELECT TIMESTAMP("2017-11-06 00:00:00+00") AS timestamp_value)
+SELECT
+ timestamp_value,
+ EXTRACT(WEEK(SUNDAY) FROM timestamp_value) AS week_sunday,
+ EXTRACT(WEEK(MONDAY) FROM timestamp_value) AS week_monday
+FROM table;
-If this function receives a `NULL` input, it returns `NULL`. If the input is
-considered invalid, an `OUT_OF_RANGE` error occurs.
+-- Display of results may differ, depending upon the environment and time zone where this query was executed.
+/*---------------------------------------------+-------------+---------------*
+ | timestamp_value | week_sunday | week_monday |
+ +---------------------------------------------+-------------+---------------+
+ | 2017-11-05 16:00:00.000 America/Los_Angeles | 45 | 44 |
+ *---------------------------------------------+-------------+---------------*/
+```
-**Return Data Type**
+[ISO-8601]: https://en.wikipedia.org/wiki/ISO_8601
-BOOL
+[ISO-8601-week]: https://en.wikipedia.org/wiki/ISO_week_date
-[net-link-to-ipv6-rfc]: http://www.ietf.org/rfc/rfc2373.txt
+[timestamp-link-to-timezone-definitions]: #timezone_definitions
-### `NET.IP_NET_MASK`
+### `FORMAT_TIMESTAMP`
-```
-NET.IP_NET_MASK(num_output_bytes, prefix_length)
+```sql
+FORMAT_TIMESTAMP(format_string, timestamp[, time_zone])
```
**Description**
-Returns a network mask: a byte sequence with length equal to `num_output_bytes`,
-where the first `prefix_length` bits are set to 1 and the other bits are set to
-0. `num_output_bytes` and `prefix_length` are INT64.
-This function throws an error if `num_output_bytes` is not 4 (for IPv4) or 16
-(for IPv6). It also throws an error if `prefix_length` is negative or greater
-than `8 * num_output_bytes`.
+Formats a timestamp according to the specified `format_string`.
+
+See [Format elements for date and time parts][timestamp-format-elements]
+for a list of format elements that this function supports.
**Return Data Type**
-BYTES
+`STRING`
**Example**
```sql
-SELECT x, y, FORMAT("%T", NET.IP_NET_MASK(x, y)) AS ip_net_mask
-FROM UNNEST([
- STRUCT(4 as x, 0 as y),
- (4, 20),
- (4, 32),
- (16, 0),
- (16, 1),
- (16, 128)
-]);
+SELECT FORMAT_TIMESTAMP("%c", TIMESTAMP "2050-12-25 15:30:55+00", "UTC")
+ AS formatted;
-/*--------------------------------------------------------------------------------*
- | x | y | ip_net_mask |
- +--------------------------------------------------------------------------------+
- | 4 | 0 | b"\x00\x00\x00\x00" |
- | 4 | 20 | b"\xff\xff\xf0\x00" |
- | 4 | 32 | b"\xff\xff\xff\xff" |
- | 16 | 0 | b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" |
- | 16 | 1 | b"\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" |
- | 16 | 128 | b"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" |
- *--------------------------------------------------------------------------------*/
+/*--------------------------*
+ | formatted |
+ +--------------------------+
+ | Sun Dec 25 15:30:55 2050 |
+ *--------------------------*/
```
-### `NET.IP_TO_STRING`
+```sql
+SELECT FORMAT_TIMESTAMP("%b-%d-%Y", TIMESTAMP "2050-12-25 15:30:55+00")
+ AS formatted;
+/*-------------*
+ | formatted |
+ +-------------+
+ | Dec-25-2050 |
+ *-------------*/
```
-NET.IP_TO_STRING(addr_bin)
-```
-
-**Description**
-Converts an IPv4 or IPv6 address from binary (BYTES) format in network byte
-order to text (STRING) format.
-
-If the input is 4 bytes, this function returns an IPv4 address as a STRING. If
-the input is 16 bytes, it returns an IPv6 address as a STRING.
-
-If this function receives a `NULL` input, it returns `NULL`. If the input has
-a length different from 4 or 16, an `OUT_OF_RANGE` error occurs.
-
-**Return Data Type**
-STRING
+```sql
+SELECT FORMAT_TIMESTAMP("%b %Y", TIMESTAMP "2050-12-25 15:30:55+00")
+ AS formatted;
-**Example**
+/*-------------*
+ | formatted |
+ +-------------+
+ | Dec 2050 |
+ *-------------*/
+```
```sql
-SELECT FORMAT("%T", x) AS addr_bin, NET.IP_TO_STRING(x) AS ip_to_string
-FROM UNNEST([
- b"0123",
- b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
- b"0123456789@ABCDE",
- b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xc0\x00\x02\x80"
-]) AS x;
+SELECT FORMAT_TIMESTAMP("%Y-%m-%dT%H:%M:%SZ", TIMESTAMP "2050-12-25 15:30:55", "UTC")
+ AS formatted;
-/*---------------------------------------------------------------------------------------------------------------*
- | addr_bin | ip_to_string |
- +---------------------------------------------------------------------------------------------------------------+
- | b"0123" | 48.49.50.51 |
- | b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01" | ::1 |
- | b"0123456789@ABCDE" | 3031:3233:3435:3637:3839:4041:4243:4445 |
- | b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xc0\x00\x02\x80" | ::ffff:192.0.2.128 |
- *---------------------------------------------------------------------------------------------------------------*/
+/*+---------------------*
+ | formatted |
+ +----------------------+
+ | 2050-12-25T15:30:55Z |
+ *----------------------*/
```
-### `NET.IP_TRUNC`
+[timestamp-format-elements]: https://github.com/google/zetasql/blob/master/docs/format-elements.md#format_elements_date_time
-```
-NET.IP_TRUNC(addr_bin, prefix_length)
+### `PARSE_TIMESTAMP`
+
+```sql
+PARSE_TIMESTAMP(format_string, timestamp_string[, time_zone])
```
**Description**
-Takes `addr_bin`, an IPv4 or IPv6 address in binary (BYTES) format in network
-byte order, and returns a subnet address in the same format. The result has the
-same length as `addr_bin`, where the first `prefix_length` bits are equal to
-those in `addr_bin` and the remaining bits are 0.
-This function throws an error if `LENGTH(addr_bin)` is not 4 or 16, or if
-`prefix_len` is negative or greater than `LENGTH(addr_bin) * 8`.
-
-**Return Data Type**
-
-BYTES
+Converts a [string representation of a timestamp][timestamp-format] to a
+`TIMESTAMP` object.
-**Example**
+`format_string` contains the [format elements][timestamp-format-elements]
+that define how `timestamp_string` is formatted. Each element in
+`timestamp_string` must have a corresponding element in `format_string`. The
+location of each element in `format_string` must match the location of
+each element in `timestamp_string`.
```sql
-SELECT
- FORMAT("%T", x) as addr_bin, prefix_length,
- FORMAT("%T", NET.IP_TRUNC(x, prefix_length)) AS ip_trunc
-FROM UNNEST([
- STRUCT(b"\xAA\xBB\xCC\xDD" as x, 0 as prefix_length),
- (b"\xAA\xBB\xCC\xDD", 11), (b"\xAA\xBB\xCC\xDD", 12),
- (b"\xAA\xBB\xCC\xDD", 24), (b"\xAA\xBB\xCC\xDD", 32),
- (b'0123456789@ABCDE', 80)
-]);
+-- This works because elements on both sides match.
+SELECT PARSE_TIMESTAMP("%a %b %e %I:%M:%S %Y", "Thu Dec 25 07:30:00 2008")
-/*-----------------------------------------------------------------------------*
- | addr_bin | prefix_length | ip_trunc |
- +-----------------------------------------------------------------------------+
- | b"\xaa\xbb\xcc\xdd" | 0 | b"\x00\x00\x00\x00" |
- | b"\xaa\xbb\xcc\xdd" | 11 | b"\xaa\xa0\x00\x00" |
- | b"\xaa\xbb\xcc\xdd" | 12 | b"\xaa\xb0\x00\x00" |
- | b"\xaa\xbb\xcc\xdd" | 24 | b"\xaa\xbb\xcc\x00" |
- | b"\xaa\xbb\xcc\xdd" | 32 | b"\xaa\xbb\xcc\xdd" |
- | b"0123456789@ABCDE" | 80 | b"0123456789\x00\x00\x00\x00\x00\x00" |
- *-----------------------------------------------------------------------------*/
-```
+-- This produces an error because the year element is in different locations.
+SELECT PARSE_TIMESTAMP("%a %b %e %Y %I:%M:%S", "Thu Dec 25 07:30:00 2008")
-### `NET.IPV4_FROM_INT64`
+-- This produces an error because one of the year elements is missing.
+SELECT PARSE_TIMESTAMP("%a %b %e %I:%M:%S", "Thu Dec 25 07:30:00 2008")
+-- This works because %c can find all matching elements in timestamp_string.
+SELECT PARSE_TIMESTAMP("%c", "Thu Dec 25 07:30:00 2008")
```
-NET.IPV4_FROM_INT64(integer_value)
-```
-
-**Description**
-
-Converts an IPv4 address from integer format to binary (BYTES) format in network
-byte order. In the integer input, the least significant bit of the IP address is
-stored in the least significant bit of the integer, regardless of host or client
-architecture. For example, `1` means `0.0.0.1`, and `0x1FF` means `0.0.1.255`.
-This function checks that either all the most significant 32 bits are 0, or all
-the most significant 33 bits are 1 (sign-extended from a 32-bit integer).
-In other words, the input should be in the range `[-0x80000000, 0xFFFFFFFF]`;
-otherwise, this function throws an error.
+When using `PARSE_TIMESTAMP`, keep the following in mind:
-This function does not support IPv6.
++ **Unspecified fields.** Any unspecified field is initialized from `1970-01-01
+ 00:00:00.0`. This initialization value uses the time zone specified by the
+ function's time zone argument, if present. If not, the initialization value
+ uses the default time zone, which is implementation defined. For instance, if the year
+ is unspecified then it defaults to `1970`, and so on.
++ **Case insensitivity.** Names, such as `Monday`, `February`, and so on, are
+ case insensitive.
++ **Whitespace.** One or more consecutive white spaces in the format string
+ matches zero or more consecutive white spaces in the timestamp string. In
+ addition, leading and trailing white spaces in the timestamp string are always
+ allowed, even if they are not in the format string.
++ **Format precedence.** When two (or more) format elements have overlapping
+ information (for example both `%F` and `%Y` affect the year), the last one
+ generally overrides any earlier ones, with some exceptions (see the
+ descriptions of `%s`, `%C`, and `%y`).
++ **Format divergence.** `%p` can be used with `am`, `AM`, `pm`, and `PM`.
**Return Data Type**
-BYTES
+`TIMESTAMP`
**Example**
```sql
-SELECT x, x_hex, FORMAT("%T", NET.IPV4_FROM_INT64(x)) AS ipv4_from_int64
-FROM (
- SELECT CAST(x_hex AS INT64) x, x_hex
- FROM UNNEST(["0x0", "0xABCDEF", "0xFFFFFFFF", "-0x1", "-0x2"]) AS x_hex
-);
+SELECT PARSE_TIMESTAMP("%c", "Thu Dec 25 07:30:00 2008") AS parsed;
-/*-----------------------------------------------*
- | x | x_hex | ipv4_from_int64 |
- +-----------------------------------------------+
- | 0 | 0x0 | b"\x00\x00\x00\x00" |
- | 11259375 | 0xABCDEF | b"\x00\xab\xcd\xef" |
- | 4294967295 | 0xFFFFFFFF | b"\xff\xff\xff\xff" |
- | -1 | -0x1 | b"\xff\xff\xff\xff" |
- | -2 | -0x2 | b"\xff\xff\xff\xfe" |
- *-----------------------------------------------*/
+-- Display of results may differ, depending upon the environment and time zone where this query was executed.
+/*---------------------------------------------*
+ | parsed |
+ +---------------------------------------------+
+ | 2008-12-25 07:30:00.000 America/Los_Angeles |
+ *---------------------------------------------*/
```
-### `NET.IPV4_TO_INT64`
+[timestamp-format]: #format_timestamp
-```
-NET.IPV4_TO_INT64(addr_bin)
-```
+[timestamp-format-elements]: https://github.com/google/zetasql/blob/master/docs/format-elements.md#format_elements_date_time
-**Description**
+### `STRING`
-Converts an IPv4 address from binary (BYTES) format in network byte order to
-integer format. In the integer output, the least significant bit of the IP
-address is stored in the least significant bit of the integer, regardless of
-host or client architecture. For example, `1` means `0.0.0.1`, and `0x1FF` means
-`0.0.1.255`. The output is in the range `[0, 0xFFFFFFFF]`.
+```sql
+STRING(timestamp_expression[, time_zone])
+```
-If the input length is not 4, this function throws an error.
+**Description**
-This function does not support IPv6.
+Converts a timestamp to a string. Supports an optional
+parameter to specify a time zone. See
+[Time zone definitions][timestamp-link-to-timezone-definitions] for information
+on how to specify a time zone.
**Return Data Type**
-INT64
+`STRING`
**Example**
-```sql
-SELECT
- FORMAT("%T", x) AS addr_bin,
- FORMAT("0x%X", NET.IPV4_TO_INT64(x)) AS ipv4_to_int64
-FROM
-UNNEST([b"\x00\x00\x00\x00", b"\x00\xab\xcd\xef", b"\xff\xff\xff\xff"]) AS x;
+```sql
+SELECT STRING(TIMESTAMP "2008-12-25 15:30:00+00", "UTC") AS string;
-/*-------------------------------------*
- | addr_bin | ipv4_to_int64 |
- +-------------------------------------+
- | b"\x00\x00\x00\x00" | 0x0 |
- | b"\x00\xab\xcd\xef" | 0xABCDEF |
- | b"\xff\xff\xff\xff" | 0xFFFFFFFF |
- *-------------------------------------*/
+/*-------------------------------*
+ | string |
+ +-------------------------------+
+ | 2008-12-25 15:30:00+00 |
+ *-------------------------------*/
```
-### `NET.MAKE_NET`
+[timestamp-link-to-timezone-definitions]: #timezone_definitions
-```
-NET.MAKE_NET(address, prefix_length)
+### `TIMESTAMP`
+
+```sql
+TIMESTAMP(string_expression[, time_zone])
+TIMESTAMP(date_expression[, time_zone])
+TIMESTAMP(datetime_expression[, time_zone])
```
**Description**
-Takes an IPv4 or IPv6 address as STRING and an integer representing the prefix
-length (the number of leading 1-bits in the network mask). Returns a
-STRING representing the [CIDR subnet][net-link-to-cidr-notation] with the given prefix length.
-
-The value of `prefix_length` must be greater than or equal to 0. A smaller value
-means a bigger subnet, covering more IP addresses. The result CIDR subnet must
-be no smaller than `address`, meaning that the value of `prefix_length` must be
-less than or equal to the prefix length in `address`. See the effective upper
-bound below.
++ `string_expression[, time_zone]`: Converts a string to a
+ timestamp. `string_expression` must include a
+ timestamp literal.
+ If `string_expression` includes a time zone in the timestamp literal, do
+ not include an explicit `time_zone`
+ argument.
++ `date_expression[, time_zone]`: Converts a date to a timestamp.
+ The value returned is the earliest timestamp that falls within
+ the given date.
++ `datetime_expression[, time_zone]`: Converts a
+ datetime to a timestamp.
-This function supports the following formats for `address`:
+This function supports an optional
+parameter to [specify a time zone][timestamp-link-to-timezone-definitions]. If
+no time zone is specified, the default time zone, which is implementation defined,
+is used.
-+ IPv4: Dotted-quad format, such as `10.1.2.3`. The value of `prefix_length`
- must be less than or equal to 32.
-+ IPv6: Colon-separated format, such as
- `1234:5678:90ab:cdef:1234:5678:90ab:cdef`. The value of `prefix_length` must
- be less than or equal to 128.
-+ CIDR (IPv4): Dotted-quad format, such as `10.1.2.0/24`.
- The value of `prefix_length` must be less than or equal to the number after
- the slash in `address` (24 in the example), which must be less than or equal
- to 32.
-+ CIDR (IPv6): Colon-separated format, such as `1:2::/48`.
- The value of `prefix_length` must be less than or equal to the number after
- the slash in `address` (48 in the example), which must be less than or equal
- to 128.
+**Return Data Type**
-If this function receives a `NULL` input, it returns `NULL`. If the input is
-considered invalid, an `OUT_OF_RANGE` error occurs.
+`TIMESTAMP`
-**Return Data Type**
+**Examples**
-STRING
+```sql
+SELECT TIMESTAMP("2008-12-25 15:30:00+00") AS timestamp_str;
-[net-link-to-cidr-notation]: https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing
+-- Display of results may differ, depending upon the environment and time zone where this query was executed.
+/*---------------------------------------------*
+ | timestamp_str |
+ +---------------------------------------------+
+ | 2008-12-25 07:30:00.000 America/Los_Angeles |
+ *---------------------------------------------*/
+```
-### `NET.PARSE_IP` (DEPRECATED)
-
+```sql
+SELECT TIMESTAMP("2008-12-25 15:30:00", "America/Los_Angeles") AS timestamp_str;
+-- Display of results may differ, depending upon the environment and time zone where this query was executed.
+/*---------------------------------------------*
+ | timestamp_str |
+ +---------------------------------------------+
+ | 2008-12-25 15:30:00.000 America/Los_Angeles |
+ *---------------------------------------------*/
```
-NET.PARSE_IP(addr_str)
+
+```sql
+SELECT TIMESTAMP("2008-12-25 15:30:00 UTC") AS timestamp_str;
+
+-- Display of results may differ, depending upon the environment and time zone where this query was executed.
+/*---------------------------------------------*
+ | timestamp_str |
+ +---------------------------------------------+
+ | 2008-12-25 07:30:00.000 America/Los_Angeles |
+ *---------------------------------------------*/
```
-**Description**
+```sql
+SELECT TIMESTAMP(DATETIME "2008-12-25 15:30:00") AS timestamp_datetime;
-This function is deprecated. It is the same as
-[`NET.IPV4_TO_INT64`][net-link-to-ipv4-to-int64]`(`[`NET.IP_FROM_STRING`][net-link-to-ip-from-string]`(addr_str))`,
-except that this function truncates the input at the first `'\x00'` character,
-if any, while `NET.IP_FROM_STRING` treats `'\x00'` as invalid.
+-- Display of results may differ, depending upon the environment and time zone where this query was executed.
+/*---------------------------------------------*
+ | timestamp_datetime |
+ +---------------------------------------------+
+ | 2008-12-25 15:30:00.000 America/Los_Angeles |
+ *---------------------------------------------*/
+```
-**Return Data Type**
+```sql
+SELECT TIMESTAMP(DATE "2008-12-25") AS timestamp_date;
-INT64
+-- Display of results may differ, depending upon the environment and time zone where this query was executed.
+/*---------------------------------------------*
+ | timestamp_date |
+ +---------------------------------------------+
+ | 2008-12-25 00:00:00.000 America/Los_Angeles |
+ *---------------------------------------------*/
+```
-[net-link-to-ip-to-string]: #netip_to_string
+[timestamp-literals]: https://github.com/google/zetasql/blob/master/docs/lexical.md#timestamp_literals
-[net-link-to-ipv4-to-int64]: #netipv4_to_int64
+[timestamp-link-to-timezone-definitions]: #timezone_definitions
-### `NET.PARSE_PACKED_IP` (DEPRECATED)
-
+### `TIMESTAMP_ADD`
-```
-NET.PARSE_PACKED_IP(addr_str)
+```sql
+TIMESTAMP_ADD(timestamp_expression, INTERVAL int64_expression date_part)
```
**Description**
-This function is deprecated. It is the same as
-[`NET.IP_FROM_STRING`][net-link-to-ip-from-string], except that this function truncates
-the input at the first `'\x00'` character, if any, while `NET.IP_FROM_STRING`
-treats `'\x00'` as invalid.
+Adds `int64_expression` units of `date_part` to the timestamp, independent of
+any time zone.
-**Return Data Type**
+`TIMESTAMP_ADD` supports the following values for `date_part`:
-BYTES
++ `NANOSECOND`
+ (if the SQL engine supports it)
++ `MICROSECOND`
++ `MILLISECOND`
++ `SECOND`
++ `MINUTE`
++ `HOUR`. Equivalent to 60 `MINUTE` parts.
++ `DAY`. Equivalent to 24 `HOUR` parts.
-[net-link-to-ip-from-string]: #netip_from_string
+**Return Data Types**
-### `NET.PUBLIC_SUFFIX`
+`TIMESTAMP`
-```
-NET.PUBLIC_SUFFIX(url)
-```
+**Example**
-**Description**
+```sql
+SELECT
+ TIMESTAMP("2008-12-25 15:30:00+00") AS original,
+ TIMESTAMP_ADD(TIMESTAMP "2008-12-25 15:30:00+00", INTERVAL 10 MINUTE) AS later;
-Takes a URL as a `STRING` value and returns the public suffix (such as `com`,
-`org`, or `net`). A public suffix is an ICANN domain registered at
-[publicsuffix.org][net-link-to-public-suffix]. For best results, URL values
-should comply with the format as defined by
-[RFC 3986][net-link-to-rfc-3986-appendix-a]. If the URL value does not comply
-with RFC 3986 formatting, this function makes a best effort to parse the input
-and return a relevant result.
+-- Display of results may differ, depending upon the environment and time zone where this query was executed.
+/*---------------------------------------------+---------------------------------------------*
+ | original | later |
+ +---------------------------------------------+---------------------------------------------+
+ | 2008-12-25 07:30:00.000 America/Los_Angeles | 2008-12-25 07:40:00.000 America/Los_Angeles |
+ *---------------------------------------------+---------------------------------------------*/
+```
-This function returns `NULL` if any of the following is true:
+### `TIMESTAMP_DIFF`
-+ It cannot parse the host from the input;
-+ The parsed host contains adjacent dots in the middle
- (not leading or trailing);
-+ The parsed host does not contain any public suffix.
+```sql
+TIMESTAMP_DIFF(timestamp_expression_a, timestamp_expression_b, date_part)
+```
-Before looking up the public suffix, this function temporarily normalizes the
-host by converting uppercase English letters to lowercase and encoding all
-non-ASCII characters with [Punycode][net-link-to-punycode].
-The function then returns the public suffix as part of the original host instead
-of the normalized host.
+**Description**
-Note: The function does not perform
-[Unicode normalization][unicode-normalization].
+Returns the whole number of specified `date_part` intervals between two
+timestamps (`timestamp_expression_a` - `timestamp_expression_b`).
+If the first timestamp is earlier than the second one,
+the output is negative. Produces an error if the computation overflows the
+result type, such as if the difference in
+nanoseconds
+between the two timestamps would overflow an
+`INT64` value.
-Note: The public suffix data at
-[publicsuffix.org][net-link-to-public-suffix] also contains
-private domains. This function ignores the private domains.
+`TIMESTAMP_DIFF` supports the following values for `date_part`:
-Note: The public suffix data may change over time. Consequently, input that
-produces a `NULL` result now may produce a non-`NULL` value in the future.
++ `NANOSECOND`
+ (if the SQL engine supports it)
++ `MICROSECOND`
++ `MILLISECOND`
++ `SECOND`
++ `MINUTE`
++ `HOUR`. Equivalent to 60 `MINUTE`s.
++ `DAY`. Equivalent to 24 `HOUR`s.
**Return Data Type**
-`STRING`
+`INT64`
**Example**
```sql
SELECT
- FORMAT("%T", input) AS input,
- description,
- FORMAT("%T", NET.HOST(input)) AS host,
- FORMAT("%T", NET.PUBLIC_SUFFIX(input)) AS suffix,
- FORMAT("%T", NET.REG_DOMAIN(input)) AS domain
-FROM (
- SELECT "" AS input, "invalid input" AS description
- UNION ALL SELECT "http://abc.xyz", "standard URL"
- UNION ALL SELECT "//user:password@a.b:80/path?query",
- "standard URL with relative scheme, port, path and query, but no public suffix"
- UNION ALL SELECT "https://[::1]:80", "standard URL with IPv6 host"
- UNION ALL SELECT "http://例å.å·ç’纸.ä¸å›½", "standard URL with internationalized domain name"
- UNION ALL SELECT " www.Example.Co.UK ",
- "non-standard URL with spaces, upper case letters, and without scheme"
- UNION ALL SELECT "mailto:?to=&subject=&body=", "URI rather than URL--unsupported"
-);
+ TIMESTAMP("2010-07-07 10:20:00+00") AS later_timestamp,
+ TIMESTAMP("2008-12-25 15:30:00+00") AS earlier_timestamp,
+ TIMESTAMP_DIFF(TIMESTAMP "2010-07-07 10:20:00+00", TIMESTAMP "2008-12-25 15:30:00+00", HOUR) AS hours;
+
+-- Display of results may differ, depending upon the environment and time zone where this query was executed.
+/*---------------------------------------------+---------------------------------------------+-------*
+ | later_timestamp | earlier_timestamp | hours |
+ +---------------------------------------------+---------------------------------------------+-------+
+ | 2010-07-07 03:20:00.000 America/Los_Angeles | 2008-12-25 07:30:00.000 America/Los_Angeles | 13410 |
+ *---------------------------------------------+---------------------------------------------+-------*/
```
-| input | description | host | suffix | domain |
-|--------------------------------------------------------------------|-------------------------------------------------------------------------------|--------------------|---------|----------------|
-| "" | invalid input | NULL | NULL | NULL |
-| "http://abc.xyz" | standard URL | "abc.xyz" | "xyz" | "abc.xyz" |
-| "//user:password@a.b:80/path?query" | standard URL with relative scheme, port, path and query, but no public suffix | "a.b" | NULL | NULL |
-| "https://[::1]:80" | standard URL with IPv6 host | "[::1]" | NULL | NULL |
-| "http://例å.å·ç’纸.ä¸å›½" | standard URL with internationalized domain name | "例å.å·ç’纸.ä¸å›½" | "ä¸å›½" | "å·ç’纸.ä¸å›½" |
-| " www.Example.Co.UK "| non-standard URL with spaces, upper case letters, and without scheme | "www.Example.Co.UK"| "Co.UK" | "Example.Co.UK |
-| "mailto:?to=&subject=&body=" | URI rather than URL--unsupported | "mailto" | NULL | NULL |
+In the following example, the first timestamp occurs before the
+second timestamp, resulting in a negative output.
-[unicode-normalization]: https://en.wikipedia.org/wiki/Unicode_equivalence
+```sql
+SELECT TIMESTAMP_DIFF(TIMESTAMP "2018-08-14", TIMESTAMP "2018-10-14", DAY) AS negative_diff;
-[net-link-to-punycode]: https://en.wikipedia.org/wiki/Punycode
+/*---------------*
+ | negative_diff |
+ +---------------+
+ | -61 |
+ *---------------+
+```
-[net-link-to-public-suffix]: https://publicsuffix.org/list/
+In this example, the result is 0 because only the number of whole specified
+`HOUR` intervals are included.
-[net-link-to-rfc-3986-appendix-a]: https://tools.ietf.org/html/rfc3986#appendix-A
+```sql
+SELECT TIMESTAMP_DIFF("2001-02-01 01:00:00", "2001-02-01 00:00:01", HOUR) AS diff;
-### `NET.REG_DOMAIN`
+/*---------------*
+ | diff |
+ +---------------+
+ | 0 |
+ *---------------+
+```
+
+### `TIMESTAMP_FROM_UNIX_MICROS`
+```sql
+TIMESTAMP_FROM_UNIX_MICROS(int64_expression)
```
-NET.REG_DOMAIN(url)
+
+```sql
+TIMESTAMP_FROM_UNIX_MICROS(timestamp_expression)
```
**Description**
-Takes a URL as a string and returns the registered or registrable domain (the
-[public suffix](#netpublic_suffix) plus one preceding label), as a
-string. For best results, URL values should comply with the format as defined by
-[RFC 3986][net-link-to-rfc-3986-appendix-a]. If the URL value does not comply
-with RFC 3986 formatting, this function makes a best effort to parse the input
-and return a relevant result.
-
-This function returns `NULL` if any of the following is true:
-
-+ It cannot parse the host from the input;
-+ The parsed host contains adjacent dots in the middle
- (not leading or trailing);
-+ The parsed host does not contain any public suffix;
-+ The parsed host contains only a public suffix without any preceding label.
+Interprets `int64_expression` as the number of microseconds since
+1970-01-01 00:00:00 UTC and returns a timestamp. If a timestamp is passed in,
+the same timestamp is returned.
-Before looking up the public suffix, this function temporarily normalizes the
-host by converting uppercase English letters to lowercase and encoding all
-non-ASCII characters with [Punycode][net-link-to-punycode]. The function then
-returns the registered or registerable domain as part of the original host
-instead of the normalized host.
+**Return Data Type**
-Note: The function does not perform
-[Unicode normalization][unicode-normalization].
+`TIMESTAMP`
-Note: The public suffix data at
-[publicsuffix.org][net-link-to-public-suffix] also contains
-private domains. This function does not treat a private domain as a public
-suffix. For example, if `us.com` is a private domain in the public suffix data,
-`NET.REG_DOMAIN("foo.us.com")` returns `us.com` (the public suffix `com` plus
-the preceding label `us`) rather than `foo.us.com` (the private domain `us.com`
-plus the preceding label `foo`).
+**Example**
-Note: The public suffix data may change over time.
-Consequently, input that produces a `NULL` result now may produce a non-`NULL`
-value in the future.
+```sql
+SELECT TIMESTAMP_FROM_UNIX_MICROS(1230219000000000) AS timestamp_value;
-**Return Data Type**
+-- Display of results may differ, depending upon the environment and time zone where this query was executed.
+/*------------------------*
+ | timestamp_value |
+ +------------------------+
+ | 2008-12-25 15:30:00+00 |
+ *------------------------*/
+```
-`STRING`
+### `TIMESTAMP_FROM_UNIX_MILLIS`
-**Example**
+```sql
+TIMESTAMP_FROM_UNIX_MILLIS(int64_expression)
+```
```sql
-SELECT
- FORMAT("%T", input) AS input,
- description,
- FORMAT("%T", NET.HOST(input)) AS host,
- FORMAT("%T", NET.PUBLIC_SUFFIX(input)) AS suffix,
- FORMAT("%T", NET.REG_DOMAIN(input)) AS domain
-FROM (
- SELECT "" AS input, "invalid input" AS description
- UNION ALL SELECT "http://abc.xyz", "standard URL"
- UNION ALL SELECT "//user:password@a.b:80/path?query",
- "standard URL with relative scheme, port, path and query, but no public suffix"
- UNION ALL SELECT "https://[::1]:80", "standard URL with IPv6 host"
- UNION ALL SELECT "http://例å.å·ç’纸.ä¸å›½", "standard URL with internationalized domain name"
- UNION ALL SELECT " www.Example.Co.UK ",
- "non-standard URL with spaces, upper case letters, and without scheme"
- UNION ALL SELECT "mailto:?to=&subject=&body=", "URI rather than URL--unsupported"
-);
+TIMESTAMP_FROM_UNIX_MILLIS(timestamp_expression)
```
-| input | description | host | suffix | domain |
-|--------------------------------------------------------------------|-------------------------------------------------------------------------------|--------------------|---------|----------------|
-| "" | invalid input | NULL | NULL | NULL |
-| "http://abc.xyz" | standard URL | "abc.xyz" | "xyz" | "abc.xyz" |
-| "//user:password@a.b:80/path?query" | standard URL with relative scheme, port, path and query, but no public suffix | "a.b" | NULL | NULL |
-| "https://[::1]:80" | standard URL with IPv6 host | "[::1]" | NULL | NULL |
-| "http://例å.å·ç’纸.ä¸å›½" | standard URL with internationalized domain name | "例å.å·ç’纸.ä¸å›½" | "ä¸å›½" | "å·ç’纸.ä¸å›½" |
-| " www.Example.Co.UK "| non-standard URL with spaces, upper case letters, and without scheme | "www.Example.Co.UK"| "Co.UK" | "Example.Co.UK"|
-| "mailto:?to=&subject=&body=" | URI rather than URL--unsupported | "mailto" | NULL | NULL |
+**Description**
-[unicode-normalization]: https://en.wikipedia.org/wiki/Unicode_equivalence
+Interprets `int64_expression` as the number of milliseconds since
+1970-01-01 00:00:00 UTC and returns a timestamp. If a timestamp is passed in,
+the same timestamp is returned.
-[net-link-to-public-suffix]: https://publicsuffix.org/list/
+**Return Data Type**
-[net-link-to-punycode]: https://en.wikipedia.org/wiki/Punycode
+`TIMESTAMP`
-[net-link-to-rfc-3986-appendix-a]: https://tools.ietf.org/html/rfc3986#appendix-A
+**Example**
-### `NET.SAFE_IP_FROM_STRING`
+```sql
+SELECT TIMESTAMP_FROM_UNIX_MILLIS(1230219000000) AS timestamp_value;
+
+-- Display of results may differ, depending upon the environment and time zone where this query was executed.
+/*------------------------*
+ | timestamp_value |
+ +------------------------+
+ | 2008-12-25 15:30:00+00 |
+ *------------------------*/
+```
+
+### `TIMESTAMP_FROM_UNIX_SECONDS`
+```sql
+TIMESTAMP_FROM_UNIX_SECONDS(int64_expression)
```
-NET.SAFE_IP_FROM_STRING(addr_str)
+
+```sql
+TIMESTAMP_FROM_UNIX_SECONDS(timestamp_expression)
```
**Description**
-Similar to [`NET.IP_FROM_STRING`][net-link-to-ip-from-string], but returns `NULL`
-instead of throwing an error if the input is invalid.
+Interprets `int64_expression` as the number of seconds since
+1970-01-01 00:00:00 UTC and returns a timestamp. If a timestamp is passed in,
+the same timestamp is returned.
**Return Data Type**
-BYTES
+`TIMESTAMP`
**Example**
```sql
-SELECT
- addr_str,
- FORMAT("%T", NET.SAFE_IP_FROM_STRING(addr_str)) AS safe_ip_from_string
-FROM UNNEST([
- '48.49.50.51',
- '::1',
- '3031:3233:3435:3637:3839:4041:4243:4445',
- '::ffff:192.0.2.128',
- '48.49.50.51/32',
- '48.49.50',
- '::wxyz'
-]) AS addr_str;
+SELECT TIMESTAMP_FROM_UNIX_SECONDS(1230219000) AS timestamp_value;
-/*---------------------------------------------------------------------------------------------------------------*
- | addr_str | safe_ip_from_string |
- +---------------------------------------------------------------------------------------------------------------+
- | 48.49.50.51 | b"0123" |
- | ::1 | b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01" |
- | 3031:3233:3435:3637:3839:4041:4243:4445 | b"0123456789@ABCDE" |
- | ::ffff:192.0.2.128 | b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xc0\x00\x02\x80" |
- | 48.49.50.51/32 | NULL |
- | 48.49.50 | NULL |
- | ::wxyz | NULL |
- *---------------------------------------------------------------------------------------------------------------*/
+-- Display of results may differ, depending upon the environment and time zone where this query was executed.
+/*------------------------*
+ | timestamp_value |
+ +------------------------+
+ | 2008-12-25 15:30:00+00 |
+ *------------------------*/
```
-[net-link-to-ip-from-string]: #netip_from_string
-
-## Debugging functions
-
-ZetaSQL supports the following debugging functions.
-
-### Function list
-
-Name | -Summary | -
---|---|
ERROR
+### `TIMESTAMP_MICROS`
- |
- - Produces an error with a custom error message. - | -
IFERROR
+**Description**
- |
- - Evaluates a try expression, and if an evaluation error is produced, returns - the result of a catch expression. - | -
ISERROR
+**Return Data Type**
- |
-
- Evaluates a try expression, and if an evaluation error is produced, returns
- TRUE .
- |
-
NULLIFERROR
+**Example**
- |
-
- Evaluates a try expression, and if an evaluation error is produced, returns
- NULL .
- |
-
ST_EXTERIORRING
ST_INTERIORRINGS
ST_INTERSECTION
ST_LINEINTERPOLATEPOINT
ST_LINESUBSTRING
ST_SIMPLIFY
ST_SNAPTOGRID
ST_LINEINTERPOLATEPOINT
+
+GEOGRAPHY
+ value.
+ ST_LINELOCATEPOINT
@@ -1225,13 +1236,13 @@ determine how much the resulting geography can deviate from the ideal
buffer radius.
+ `geography`: The input `GEOGRAPHY` to encircle with the buffer radius.
-+ `buffer_radius`: `DOUBLE` that represents the radius of the buffer
- around the input geography. The radius is in meters. Note that polygons
- contract when buffered with a negative `buffer_radius`. Polygon shells and
- holes that are contracted to a point are discarded.
-+ `num_seg_quarter_circle`: (Optional) `DOUBLE` specifies the number of
- segments that are used to approximate a quarter circle. The default value is
- `8.0`. Naming this argument is optional.
++ `buffer_radius`: `DOUBLE` that represents the radius of the
+ buffer around the input geography. The radius is in meters. Note that
+ polygons contract when buffered with a negative `buffer_radius`. Polygon
+ shells and holes that are contracted to a point are discarded.
++ `num_seg_quarter_circle`: (Optional) `DOUBLE` specifies the
+ number of segments that are used to approximate a quarter circle. The
+ default value is `8.0`. Naming this argument is optional.
+ `endcap`: (Optional) `STRING` allows you to specify one of two endcap
styles: `ROUND` and `FLAT`. The default value is `ROUND`. This option only
affects the endcaps of buffered linestrings.
@@ -1296,13 +1307,13 @@ but you provide tolerance instead of segments to determine how much the
resulting geography can deviate from the ideal buffer radius.
+ `geography`: The input `GEOGRAPHY` to encircle with the buffer radius.
-+ `buffer_radius`: `DOUBLE` that represents the radius of the buffer
- around the input geography. The radius is in meters. Note that polygons
- contract when buffered with a negative `buffer_radius`. Polygon shells
- and holes that are contracted to a point are discarded.
-+ `tolerance_meters`: `DOUBLE` specifies a tolerance in meters with
- which the shape is approximated. Tolerance determines how much a polygon can
- deviate from the ideal radius. Naming this argument is optional.
++ `buffer_radius`: `DOUBLE` that represents the radius of the
+ buffer around the input geography. The radius is in meters. Note that
+ polygons contract when buffered with a negative `buffer_radius`. Polygon
+ shells and holes that are contracted to a point are discarded.
++ `tolerance_meters`: `DOUBLE` specifies a tolerance in
+ meters with which the shape is approximated. Tolerance determines how much a
+ polygon can deviate from the ideal radius. Naming this argument is optional.
+ `endcap`: (Optional) `STRING` allows you to specify one of two endcap
styles: `ROUND` and `FLAT`. The default value is `ROUND`. This option only
affects the endcaps of buffered linestrings.
@@ -1834,7 +1845,7 @@ FROM example
| GEOMETRYCOLLECTION(POINT(0 0), | [POINT(0 0), LINESTRING(1 2, 2 1)] |
| LINESTRING(1 2, 2 1)) | |
*-------------------------------------+------------------------------------*/
- ```
+```
The following example shows how `ST_DUMP` with the dimension argument only
returns simple geographies of the given dimension.
@@ -2991,6 +3002,66 @@ the value `FALSE`. The default value of `use_spheroid` is `FALSE`.
[wgs84-link]: https://en.wikipedia.org/wiki/World_Geodetic_System
+### `ST_LINEINTERPOLATEPOINT`
+
+```sql
+ST_LINEINTERPOLATEPOINT(linestring_geography, fraction)
+```
+
+**Description**
+
+Gets a point at a specific fraction in a linestring GEOGRAPHY
+value.
+
+**Definitions**
+
++ `linestring_geography`: A linestring `GEOGRAPHY` on which the target point
+ is located.
++ `fraction`: A `DOUBLE` value that represents a fraction
+ along the linestring `GEOGRAPHY` where the target point is located.
+ This should be an inclusive value between `0` (start of the
+ linestring) and `1` (end of the linestring).
+
+**Details**
+
++ Returns `NULL` if any input argument is `NULL`.
++ Returns an empty geography if `linestring_geography` is an empty geography.
++ Returns an error if `linestring_geography` is not a linestring or an empty
+ geography, or if `fraction` is outside the `[0, 1]` range.
+
+**Return Type**
+
+`GEOGRAPHY`
+
+**Example**
+
+The following query returns a few points on a linestring. Notice that the
+ midpoint of the linestring `LINESTRING(1 1, 5 5)` is slightly different from
+ `POINT(3 3)` because the `GEOGRAPHY` type uses geodesic line segments.
+
+```sql
+WITH fractions AS (
+ SELECT 0 AS fraction UNION ALL
+ SELECT 0.5 UNION ALL
+ SELECT 1 UNION ALL
+ SELECT NULL
+ )
+SELECT
+ fraction,
+ ST_LINEINTERPOLATEPOINT(ST_GEOGFROMTEXT('LINESTRING(1 1, 5 5)'), fraction)
+ AS point
+FROM fractions
+
+/*-------------+-------------------------------------------*
+ | fraction | point |
+ +-------------+-------------------------------------------+
+ | 0 | POINT(1 1) |
+ | 0.5 | POINT(2.99633827268976 3.00182528336078) |
+ | 1 | POINT(5 5) |
+ | NULL | NULL |
+ *-------------+-------------------------------------------*/
+```
+
### `ST_LINELOCATEPOINT`
```sql
diff --git a/docs/json_functions.md b/docs/json_functions.md
index c98f2168f..7fd5a6f3a 100644
--- a/docs/json_functions.md
+++ b/docs/json_functions.md
@@ -2189,6 +2189,7 @@ SELECT JSON_REMOVE(JSON 'null', '$.a.b') AS json_data
JSON_SET(
json_expr,
json_path_value_pair[, ...]
+ [, create_if_missing=> { TRUE | FALSE }]
)
json_path_value_pair:
@@ -2213,35 +2214,42 @@ Arguments:
+ `value`: A [JSON encoding-supported][json-encodings] value to
insert.
++ `create_if_missing`: An optional, mandatory named argument.
+
+ + If TRUE (default), replaces or inserts data if the path does not exist.
+
+ + If FALSE, only _existing_ JSONPath values are replaced. If the path
+ doesn't exist, the set operation is ignored.
Details:
+ Path value pairs are evaluated left to right. The JSON produced by
evaluating one pair becomes the JSON against which the next pair
is evaluated.
-+ If a path doesn't exist, the remainder of the path is recursively created.
+ If a matched path has an existing value, it overwrites the existing data
with `value`.
++ If `create_if_missing` is `TRUE`:
+
+ + If a path doesn't exist, the remainder of the path is recursively
+ created.
+ + If the matched path prefix points to a JSON null, the remainder of the
+ path is recursively created, and `value` is inserted.
+ + If a path token points to a JSON array and the specified index is
+ _larger_ than the size of the array, pads the JSON array with JSON
+ nulls, recursively creates the remainder of the path at the specified
+ index, and inserts the path value pair.
+ This function applies all path value pair set operations even if an
individual path value pair operation is invalid. For invalid operations,
the operation is ignored and the function continues to process the rest
of the path value pairs.
+ If the path exists but has an incompatible type at any given path
token, no update happens for that specific path value pair.
-+ If the matched path prefix points to a JSON null, the remainder of the
- path is recursively created, and `value` is inserted.
-+ If a path token points to a JSON array and the specified
- index is _larger_ than the size of the array, pads the JSON array with
- JSON nulls, recursively creates the remainder of the path at the specified
- index, and inserts the path value pair.
-+ If a matched path points to a JSON array and the specified index is
- _less than_ the length of the array, replaces the existing JSON array value
- at index with `value`.
+ If any `json_path` is an invalid [JSONPath][JSONPath-format], an error is
produced.
+ If `json_expr` is SQL `NULL`, the function returns SQL `NULL`.
+ If `json_path` is SQL `NULL`, the `json_path_value_pair` operation is
ignored.
++ If `create_if_missing` is SQL `NULL`, the set operation is ignored.
**Return type**
@@ -2262,6 +2270,38 @@ SELECT JSON_SET(JSON '{"a": 1}', '$', JSON '{"b": 2, "c": 3}') AS json_data
*---------------*/
```
+In the following example, `create_if_missing` is `FALSE` and the path `$.b`
+doesn't exist, so the set operation is ignored.
+
+```sql
+SELECT JSON_SET(
+ JSON '{"a": 1}',
+ "$.b", 999,
+ create_if_missing => false) AS json_data
+
+/*------------*
+ | json_data |
+ +------------+
+ | '{"a": 1}' |
+ *------------*/
+```
+
+In the following example, `create_if_missing` is `TRUE` and the path `$.a`
+exists, so the value is replaced.
+
+```sql
+SELECT JSON_SET(
+ JSON '{"a": 1}',
+ "$.a", 999,
+ create_if_missing => false) AS json_data
+
+/*--------------*
+ | json_data |
+ +--------------+
+ | '{"a": 999}' |
+ *--------------*/
+```
+
In the following example, the path `$.a` is matched, but `$.a.b` does not
exist, so the new path and the value are inserted.
@@ -3202,8 +3242,8 @@ Details:
BIGNUMERIC
value, and then safe casts the result as a
+ If the JSON string represents a JSON number, parses it as
+ a BIGNUMERIC
value, and then safe casts the result as a
DOUBLE
value.
If the JSON string can't be converted, returns NULL
.
BIGNUMERIC
value, and then safe casts the results as an
+ If the JSON string represents a JSON number, parses it as
+ a BIGNUMERIC
value, and then safe casts the results as an
INT64
value.
If the JSON string can't be converted, returns NULL
.
STRING value.
+ Returns the JSON string as a STRING
value.
STRING value.
+ Returns the JSON number as a STRING
value.
Category | +Functions | +
---|---|
Trigonometric | +
+ ACOS
+ ACOSH
+ ASIN
+ ASINH
+ ATAN
+ ATAN2
+ ATANH
+ COS
+ COSH
+ COT
+ COTH
+ CSC
+ CSCH
+ SEC
+ SECH
+ SIN
+ SINH
+ TAN
+ TANH
+ |
+
+ Exponential and + logarithmic + |
+
+ EXP
+ LN
+ LOG
+ LOG10
+ |
+
+ Rounding and + truncation + |
+
+ CEIL
+ CEILING
+ FLOOR
+ ROUND
+ TRUNC
+ |
+
+ Power and + root + |
+
+ CBRT
+ POW
+ POWER
+ SQRT
+ |
+
Sign | +
+ ABS
+ SIGN
+ |
+
+ Distance + | +
+ COSINE_DISTANCE
+ EUCLIDEAN_DISTANCE
+ |
+
+ Comparison + | +
+ GREATEST
+ LEAST
+ |
+
Random number generator | +
+ RAND
+ |
+
Arithmetic and error handling | +
+ DIV
+ IEEE_DIVIDE
+ IS_INF
+ IS_NAN
+ MOD
+ SAFE_ADD
+ SAFE_DIVIDE
+ SAFE_MULTIPLY
+ SAFE_NEGATE
+ SAFE_SUBTRACT
+ |
+
Bucket | +
+ RANGE_BUCKET
+ |
+
Numerical constants | +
+ PI
+ PI_BIGNUMERIC
+ PI_NUMERIC
+ |
+
RANGE_BUCKET
+
+ |
+ + Scans through a sorted array and returns the 0-based position + of a point's upper bound. + | +||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ROUND
@@ -1093,100 +1244,103 @@ Generates an error if overflow occurs.
### `COSINE_DISTANCE`
-
-
```sql
COSINE_DISTANCE(vector1, vector2)
```
**Description**
-Computes the [cosine distance][cosine-distance] between two vectors.
+Computes the [cosine distance][wiki-cosine-distance] between two vectors.
**Definitions**
-+ `vector1`: The first vector.
-+ `vector2`: The second vector.
++ `vector1`: A vector that is represented by an
+ `ARRAY
|