Expressions, Functions, and Operators

This page explains Cloud Spanner SQL expressions, including functions and operators.

Function call rules

The following rules apply to all functions unless explicitly indicated otherwise in the function description:

  • For functions that accept numeric types, if one operand is a floating point operand and the other operand is another numeric type, both operands are converted to FLOAT64 before the function is evaluated.
  • If an operand is NULL, the result is NULL, with the exception of the IS operator.

  • For functions that are time zone sensitive (as indicated in the function description), the default time zone, America/Los_Angeles, is used if a time zone is not specified.

Conversion rules

"Conversion" includes, but is not limited to, casting and coercion.

  • Casting is explicit conversion and uses the CAST() function.
  • Coercion is implicit conversion, which Cloud Spanner SQL performs automatically under the conditions described below.
  • There is a third group of conversion functions that have their own function names, such as UNIX_DATE().

The table below summarizes all possible CAST and coercion possibilities for Cloud Spanner SQL data types. "Coercion To" applies to all expressions of a given data type (e.g. a column) .

From Type CAST to Coercion To
INT64 BOOL
FLOAT64
INT64
STRING
FLOAT64
FLOAT64 FLOAT64
INT64
STRING
 
BOOL BOOL
INT64
STRING
 
STRING BOOL
BYTES
DATE
FLOAT64
INT64
STRING
TIMESTAMP
 
BYTES BYTES
STRING
 
DATE DATE
STRING
TIMESTAMP
 
TIMESTAMP DATE
STRING
TIMESTAMP
 
ARRAY ARRAY  
STRUCT STRUCT  

Casting

Syntax:

CAST(expr AS typename)

Cast syntax is used in a query to indicate that the result type of an expression should be converted to some other type.

Example:

CAST(x=1 AS STRING)

This results in "true" if x is 1, "false" for any other non-NULL value, and NULL if x is NULL.

Casts between supported types that do not successfully map from the original value to the target domain produce runtime errors. For example, casting BYTES to STRING where the byte sequence is not valid UTF-8 results in a runtime error.

When casting an expression x of the following types, these rules apply:

From To Rule(s) when casting x
INT64 FLOAT64 Returns a close but potentially not exact FLOAT64 value.
INT64 BOOL Returns FALSE if x is 0, TRUE otherwise.
FLOAT64 INT64 Returns the closest INT64 value.
Halfway cases such as 1.5 or -0.5 round away from zero.
FLOAT64 STRING Returns an approximate string representation.
BOOL INT64 Returns 1 if x is TRUE, 0 otherwise.
BOOL STRING Returns "true" if x is TRUE, "false" otherwise.
STRING FLOAT64 Returns x as a FLOAT64 value, interpreting it as having the same form as a valid FLOAT64 literal.
Also supports casts from "inf", "+inf", "-inf", and "nan".
Conversions are case-insensitive.
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 BOOL.
STRINGs are case-insensitive when converting to BOOL.
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.
BYTES STRING Returns x interpreted as a UTF-8 STRING.
For example, the BYTES literal b'\xc2\xa9', when cast to STRING, is interpreted as UTF-8 and becomes the unicode character "©".
An error occurs if x is not valid UTF-8.
ARRAY ARRAY Must be the exact same ARRAY type.
STRUCT STRUCT Allowed if the following conditions are met:
  1. The two STRUCTs have the same number of fields.
  2. The original STRUCT field types can be explicitly cast to the corresponding target STRUCT field types (as defined by field order, not field name).

Casting hex strings to integers

If you are working with hex strings (0x123), you can cast those strings as integers:

SELECT '0x123' as hex_value, CAST('0x123' as INT64) as hex_to_int;

+-----------+------------+
| hex_value | hex_to_int |
+-----------+------------+
| 0x123     | 291        |
+-----------+------------+

SELECT '0x123' as hex_value, CAST('-0x123' as INT64) as hex_to_int;

+-----------+------------+
| hex_value | hex_to_int |
+-----------+------------+
| 0x123     | -291       |
+-----------+------------+

Casting date types

Cloud Spanner SQL supports casting date types to/from strings as follows:

CAST(date_expression AS STRING)
CAST(string_expression AS DATE)

Casting from a date type to a string is independent of time zone and is of the form YYYY-MM-DD. 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.

Casting timestamp types

Cloud Spanner SQL supports casting timestamp types to/from strings as follows:

CAST(timestamp_expression AS STRING)
CAST(string_expression AS TIMESTAMP)

When casting from timestamp types to string, the timestamp is interpreted using the default time zone, America/Los_Angeles. 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.

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—see time zones. If there is a time zone in the string_expression, that time zone is used for conversion, otherwise the default time zone, America/Los_Angeles, 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.

Casting between date and timestamp types

Cloud Spanner SQL supports casting between date and timestamp types as follows:

CAST(date_expression AS TIMESTAMP)
CAST(timestamp_expression AS DATE)

Casting from a date to a timestamp interprets date_expression as of midnight (start of the day) in the default time zone, America/Los_Angeles. Casting from a timestamp to date effectively truncates the timestamp as of the default time zone.

Coercion

Cloud Spanner SQL coerces the result type of an expression to another type if needed to match function signatures. For example, if function func() is defined to take a single argument of type INT64 and an expression is used as an argument that has a result type of FLOAT64, then the result of the expression will be coerced to INT64 type before func() is computed.

Additional conversion functions

Cloud Spanner SQL provides the following additional conversion functions:

Aggregate functions

An aggregate function is a function that performs a calculation on a set of values. COUNT, MIN and MAX are examples of aggregate functions.

SELECT COUNT(*) as total_count, COUNT(fruit) as non_null_count,
       MIN(fruit) as min, MAX(fruit) as max
FROM UNNEST([NULL, "apple", "pear", "orange"]) as fruit;
+-------------+----------------+-------+------+
| total_count | non_null_count | min   | max  |
+-------------+----------------+-------+------+
| 4           | 3              | apple | pear |
+-------------+----------------+-------+------+

The following sections describe the aggregate functions that Cloud Spanner SQL supports.

ANY_VALUE

ANY_VALUE(expression)

Description

Returns any value from the input or NULL if there are zero input rows. Returns NULL if expression evaluates to NULL for all rows and non-NULL value otherwise. The value returned is non-deterministic, which means you might receive a different result each time you use this function.

Supported Argument Types

Any

Returned Data Types

Matches the input data type.

Examples

SELECT ANY_VALUE(fruit) as any_value
FROM UNNEST(["apple", "banana", "pear"]) as fruit;

+-----------+
| any_value |
+-----------+
| apple     |
+-----------+

ARRAY_AGG

ARRAY_AGG(expression)

Description

Returns an ARRAY of expression values.

Supported Argument Types

All data types except ARRAY.

Output Element Order

The order of the elements in the output is non-deterministic, which means you might receive a different result each time you use this function.

Returned Data Types

ARRAY

If there are zero input rows, this function returns NULL.

Examples

SELECT ARRAY_AGG(x) AS array_agg
FROM UNNEST([NULL, 1, -2, 3, -2, 1, NULL]) AS x;

+-------------------------------+
| array_agg                     |
+-------------------------------+
| [NULL, 1, -2, 3, -2, 1, NULL] |
+-------------------------------+

AVG

AVG(expression)

Description

Returns the average of non-NULL input values, or NaN if the input contains a NaN.

Supported Argument Types

Any numeric input type, such as INT64. Note that, for floating point input types, the return result is non-deterministic, which means you might receive a different result each time you use this function.

Returned Data Types

FLOAT64

Examples

SELECT AVG(x) as avg
FROM UNNEST([0, 2, NULL, 4, 4, 5]) as x;

+-----+
| avg |
+-----+
| 3   |
+-----+

BIT_AND

BIT_AND(expression)

Description

Performs a bitwise AND operation on expression and returns the result.

Supported Argument Types

INT64

Returned Data Types

INT64

Examples

SELECT BIT_AND(x) as bit_and FROM UNNEST([0xF001, 0x00A1]) as x;

+---------+
| bit_and |
+---------+
| 1       |
+---------+

BIT_OR

BIT_OR(expression)

Description

Performs a bitwise OR operation on expression and returns the result.

Supported Argument Types

INT64

Returned Data Types

INT64

Examples

SELECT BIT_OR(x) as bit_or FROM UNNEST([0xF001, 0x00A1]) as x;

+--------+
| bit_or |
+--------+
| 61601  |
+--------+

BIT_XOR

BIT_XOR(expression)

Description

Performs a bitwise XOR operation on expression and returns the result.

Supported Argument Types

INT64

Returned Data Types

INT64

Examples

SELECT BIT_XOR(x) AS bit_xor FROM UNNEST([5678, 1234]) AS x;

+---------+
| bit_xor |
+---------+
| 4860    |
+---------+

SELECT BIT_XOR(x) AS bit_xor FROM UNNEST([1234, 5678, 1234]) AS x;
+---------+
| bit_xor |
+---------+
| 5678    |
+---------+

COUNT

1. COUNT(*)
2. COUNT(expression)

Description

  1. Returns the number of rows in the input.
  2. Returns the number of rows with expression evaluated to any value other than NULL.

Supported Argument Types

expression can be any data type.

Return Data Types

INT64

Examples

SELECT COUNT(*) AS count_star, COUNT(x) AS count_x
FROM UNNEST([1, 4, NULL, 4, 5]) AS x;

+------------+---------+
| count_star | count_x |
+------------+---------+
| 5          | 4       |
+------------+---------+

LOGICAL_AND

LOGICAL_AND(expression)

Description

Returns the logical AND of all non-NULL expressions. Returns NULL if there are zero input rows or expression evaluates to NULL for all rows.

Supported Argument Types

BOOL

Return Data Types

BOOL

Examples

SELECT LOGICAL_AND(x) as logical_and FROM UNNEST([true, false, true]) as x;

+-------------+
| logical_and |
+-------------+
| false       |
+-------------+

LOGICAL_OR

LOGICAL_OR(expression)

Description

Returns the logical OR of all non-NULL expressions. Returns NULL if there are zero input rows or expression evaluates to NULL for all rows.

Supported Argument Types

BOOL

Return Data Types

BOOL

Examples

SELECT LOGICAL_OR(x) as logical_or FROM UNNEST([true, false, true]) as x;

+------------+
| logical_or |
+------------+
| true       |
+------------+

MAX

MAX(expression)

Description

Returns the maximum value of non-NULL expressions. Returns NULL if there are zero input rows or expression evaluates to NULL for all rows. Returns NaN if the input contains a NaN.

Supported Argument Types

Any data type except: STRUCT ARRAY

Return Data Types

Same as the data type used as the input values.

Examples

SELECT MAX(x) AS max
FROM UNNEST([8, NULL, 37, 4, NULL, 55]) AS x;

+-----+
| max |
+-----+
| 55  |
+-----+

MIN

MIN(expression)

Description

Returns the minimum value of non-NULL expressions. Returns NULL if there are zero input rows or expression evaluates to NULL for all rows. Returns NaN if the input contains a NaN.

Supported Argument Types

Any data type except: STRUCT ARRAY

Return Data Types

Same as the data type used as the input values.

Examples

SELECT MIN(x) AS min
FROM UNNEST([8, NULL, 37, 4, NULL, 55]) AS x;

+-----+
| min |
+-----+
| 4   |
+-----+

STRING_AGG

STRING_AGG(expression [, delimiter])

Description

Returns a value (either STRING or BYTES) obtained by concatenating non-null values.

If a delimiter is specified, concatenated values are separated by that delimiter; otherwise, a comma is used as a delimiter.

Supported Argument Types

STRING BYTES

Output Element Order

The order of the elements in the output is non-deterministic, which means you might receive a different result each time you use this function.

Return Data Types

STRING BYTES

Examples

SELECT STRING_AGG(fruit) AS string_agg
FROM UNNEST(["apple", NULL, "pear", "banana", "pear"]) AS fruit;

+------------------------+
| string_agg             |
+------------------------+
| apple,pear,banana,pear |
+------------------------+

SELECT STRING_AGG(fruit, " & ") AS string_agg
FROM UNNEST(["apple", NULL, "pear", "banana", "pear"]) AS fruit;

+------------------------------+
| string_agg                   |
+------------------------------+
| apple & pear & banana & pear |
+------------------------------+

SUM

SUM(expression)

Description

Returns the sum of non-null values.

If the expression is a floating point value, the sum is non-deterministic, which means you might receive a different result each time you use this function.

Supported Argument Types

Any supported numeric data types.

Return Data Types

Returns INT64 if the input is an integer.

Returns FLOAT64 if the input is a floating point value.

Returns NULL if the input contains only NULLs.

Returns Inf if the input contains Inf.

Returns -Inf if the input contains -Inf.

Returns NaN if the input contains a NaN.

Returns NaN if the input contains a combination of Inf and -Inf.

Examples

SELECT SUM(x) AS sum
FROM UNNEST([1, 2, 3, 4, 5, 4, 3, 2, 1]) AS x;

+-----+
| sum |
+-----+
| 25  |
+-----+

Mathematical functions

Mathematical functions:

  • Return NULL if any of the input parameters is NULL.
  • Return NaN if any of the arguments is NaN.
Function Description
ABS(X) Computes absolute value. With integer argument, generates an error if the value cannot be represented as the same type (which happens only for the largest negative input value, which has no positive representation). Returns +inf for +/-inf argument.
SIGN(X) Returns -1, 0, or +1 for negative, zero and positive argument respectively. With floating point argument does not distinguish positive and negative zero. Returns NaN for NaN argument.
IS_INF(X) Return TRUE if the value is positive or negative infinity. Returns NULL for NULL inputs.
IS_NAN(X) Return TRUE if the value is a NaN value. Returns NULL for NULL inputs.
IEEE_DIVIDE(X, Y)

Divides X by Y; never fails. Returns FLOAT64. Unlike division operator (/), does not generate errors for division by zero or overflow.

Special cases:

  • If the result overflows, returns +/-inf.
  • If Y=0 and X=0, returns NaN.
  • If Y=0 and X!=0, returns +/-inf.
  • If X = +/-inf and Y = +/-inf, returns NaN.
The behavior of IEEE_DIVIDE is further illustrated in the table below.
SQRT(X) Computes the square root of X. Generates an error if X less than 0. Returns +inf if X is +inf.
POW(X, Y) Power function: returns the value of X raised to the power of Y. If the result underflows and is not representable then zero value is returned. An error can be generated if one of the following is true:X is a finite value less than 0 and Y is a noninteger,if X is 0, and Y is a finite value less than 0,the result overflows.The behavior of POW() is further illustrated in the table below.
POWER(X, Y) Synonym of POW(). The behavior of POWER() is further illustrated in the table below.
EXP(X) Computes natural exponential function ex. If the result underflows a zero is returned. Generates an error if the result overflows. If X is +/-inf, then +inf (or 0) is returned.
LN(X) Computes the natural logarithm of X. Generates an error if X is less or equal zero. If X is +inf, then +inf is returned.
LOG(X) Synonym of LN(X)
LOG(X, Y) Computes logarithm of X to base Y. Generates an error if:X less or equal zero,Y is 1.0,Y less or equal zero.The behavior of LOG(X, Y) is further illustrated in the table below.
LOG10(X) Similar to LOG(X) but computes logarithm to base 10.
GREATEST(X1,...,XN) Returns NULL if any of the inputs is NULL. Otherwise, returns NaN if any of the inputs is NaN. Otherwise, returns the largest value among X1,...,XN according to the < comparison.
LEAST(X1,...,XN) Returns NULL if any of the inputs is NULL. Otherwise, returns NaN if any of the inputs is NaN. Otherwise, returns the smallest value among X1,...,XN according to the > comparison.
DIV(X, Y) Returns the result of integer division of X by Y. Division by zero returns an error. Division by -1 may overflow. See the table below for possible result types.
MOD(X, Y) Modulo function: returns the remainder of the division of X by Y. Returned value has the same sign as X. An error is generated if Y is 0. See the table below for possible result types.

Special cases for IEEE_DIVIDE(X, Y)

The following table lists special cases for IEEE_DIVIDE(X,Y).

Numerator Data Type (X) Denominator Data Type (Y) Result Value
Anything except 0 0 +/-inf
0 0 NaN
0 NaN NaN
NaN 0 NaN
+/-inf +/-inf NaN

Special cases for POW(X, Y) and POWER(X, Y)

The following are special cases for POW(X, Y) and POWER(X, Y).

X Y POW(X, Y) or POWER(X, Y)
1.0 Any value including NaN 1.0
any including NaN 0 1.0
-1.0 +/-inf 1.0
ABS(X) < 1 -inf +inf
ABS(X) > 1 -inf 0
ABS(X) < 1 +inf 0
ABS(X) > 1 +inf +inf
-inf Y < 0 0
-inf Y > 0 -inf if Y is an odd integer, +inf otherwise
+inf Y < 0 0
+inf Y > 0 +inf

Special cases for LOG(X, Y)

X Y LOG(X, Y)
-inf Any value NaN
Any value +inf NaN
+inf 0.0 Y < 1.0 -inf
+inf Y > 1.0 +inf

Rounding functions

Syntax Description
ROUND(X) Rounds X to the nearest integer. Halfway cases are rounded away from zero.
ROUND(X, N) Rounds X to N decimal places after decimal point. N can be negative, which will round off digits to the left of the decimal point. Halfway cases are rounded away from zero. Generates an error if overflow occurs.
TRUNC(X) Rounds X to the nearest integer whose absolute value is not greater than Xs.
TRUNC(X, N) Similar to ROUND(X, N) but always rounds towards zero. Unlike ROUND(X, N) it never overflows.
CEIL(X) Returns the smallest integral value (with FLOAT64 type) that is not less than X.
CEILING(X) Synonym of CEIL(X)
FLOOR(X) Returns the largest integral value (with FLOAT64 type) that is not greater than X.

Example behavior of Cloud Spanner SQL rounding functions:

Input "X" ROUND(X) TRUNC(X) CEIL(X) FLOOR(X)
2.0 2.0 2.0 2.0 2.0
2.3 2.0 2.0 3.0 2.0
2.8 3.0 2.0 3.0 2.0
2.5 3.0 2.0 3.0 2.0
-2.3 -2.0 -2.0 -2.0 -3.0
-2.8 -3.0 -2.0 -2.0 -3.0
-2.5 -3.0 -2.0 -2.0 -3.0
0 0 0 0 0
+/-inf +/-inf +/-inf +/-inf +/-inf
NaN NaN NaN NaN NaN

Trigonometric and hyperbolic functions

Syntax Description
COS(X) Computes cosine of X. Never fails.
COSH(X) Computes the hyperbolic cosine of X. Generates an error if an overflow occurs.
ACOS(X) Computes the principal value of the arc cosine of X. The return value is in the range [0,]. Generates an error if X is a finite value outside of range [-1, 1].
ACOSH(X) Computes the inverse hyperbolic cosine of X. Generates an error if X is a finite value less than 1.
SIN(X) Computes the sine of X. Never fails.
SINH(X) Computes the hyperbolic sine of X. Generates an error if an overflow occurs.
ASIN(X) Computes the principal value of the arc sine of X. The return value is in the range [-π/2,π/2]. Generates an error if X is a finite value outside of range [-1, 1].
ASINH(X) Computes the inverse hyperbolic sine of X. Does not fail.
TAN(X) Computes tangent of X. Generates an error if an overflow occurs.
TANH(X) Computes hyperbolic tangent of X. Does not fail.
ATAN(X) Computes the principal value of the arc tangent of X. The return value is in the range [-π/2,π/2]. Does not fail.
ATANH(X) Computes the inverse hyperbolic tangent of X. Generates an error if the absolute value of X is greater or equal 1.
ATAN2(Y, X) Calculates the principal value of the arc tangent of Y/X using the signs of the two arguments to determine the quadrant. The return value is in the range [-π,π]. The behavior of this function is further illustrated in the table below.

Special cases for ATAN2()

Y X ATAN2(Y, X)
NaN Any value NaN
Any value NaN NaN
0 0 0, π or -π depending on the sign of X and Y
Finite value -inf π or -π depending on the sign of Y
Finite value +inf 0
+/-inf Finite value π/2 or π/2 depending on the sign of Y
+/-inf -inf ¾π or -¾π depending on the sign of Y
+/-inf +inf π/4 or -π/4 depending on the sign of Y

Special cases for trigonometric and hyperbolic rounding functions

X COS(X) COSH(X) ACOS(X) ACOSH(X) SIN(X) SINH(X) ASIN(X) ASINH(X) TAN(X) TANH(X) ATAN(X) ATANH(X)
+/-inf NaN =+inf NaN =+inf NaN =+inf NaN =+inf NaN =+1.0 π/2 NaN
-inf NaN =+inf NaN NaN NaN -inf NaN -inf NaN -1.0 -π/2 NaN
NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

String functions

These string functions work on two different values: STRING and BYTES data types. STRING values must be well-formed UTF-8.

Functions that return position values, such as STRPOS, encode those positions as INT64. The value 1 refers to the first character (or byte), 2 refers to the second, and so on. The value 0 indicates an invalid index. When working on STRING types, the returned positions refer to character positions.

All string comparisons are done byte-by-byte, without regard to Unicode canonical equivalence.

BYTE_LENGTH

BYTE_LENGTH(value)

Description

Returns the length of the value in bytes, regardless of whether the type of the value is STRING or BYTES.

Return type

INT64

Examples

Table example:

+----------------+--------+
| characters     | bytes  |
+----------------+--------+
| абвгд          | абвгд  |
+----------------+--------+

SELECT
  characters,
  BYTE_LENGTH(characters) AS string_example,
  bytes,
  BYTE_LENGTH(bytes) AS bytes_example
FROM example;

+------------+----------------+-------+---------------+
| characters | string_example | bytes | bytes_example |
+------------+----------------+-------+---------------+
| абвгд      | 10             | абвгд | 10            |
+------------+----------------+-------+---------------+

CHAR_LENGTH

CHAR_LENGTH(value)

Description

Returns the length of the STRING in characters.

Return type

INT64

Examples

Table example:

+----------------+
| characters     |
+----------------+
| абвгд          |
+----------------+

SELECT
  characters,
  CHAR_LENGTH(characters) AS char_length_example
FROM example;

+------------+---------------------+
| characters | char_length_example |
+------------+---------------------+
| абвгд      |                   5 |
+------------+---------------------+

CHARACTER_LENGTH

CHARACTER_LENGTH(value)

Description

Synonym for CHAR_LENGTH.

Return type

INT64

Examples

Table example:

+----------------+
| characters     |
+----------------+
| абвгд          |
+----------------+

SELECT
  characters,
  CHARACTER_LENGTH(characters) AS char_length_example
FROM example;

+------------+---------------------+
| characters | char_length_example |
+------------+---------------------+
| абвгд      |                   5 |
+------------+---------------------+

CONCAT

CONCAT(value1[, ...])

Description

Concatenates one or more values into a single result.

Return type

STRING or BYTES

Examples

Table Employees:

+-------------+-----------+
| first_name  | last_name |
+-------------+-----------+
| John        | Doe       |
| Jane        | Smith     |
| Joe         | Jackson   |
+-------------+-----------+

SELECT
  CONCAT(first_name, " ", last_name)
  AS full_name
FROM Employees;

+---------------------+
| full_name           |
+---------------------+
| John Doe            |
| Jane Smith          |
| Joe Jackson         |
+---------------------+

ENDS_WITH

ENDS_WITH(value1, value2)

Description

Takes two values. Returns TRUE if the second value is a suffix of the first.

Return type

BOOL

Examples

Table items:

+----------------+
| item           |
+----------------+
| apple          |
| banana         |
| orange         |
+----------------+

SELECT
  ENDS_WITH(item, "e") as example
FROM items;

+---------+
| example |
+---------+
|    True |
|   False |
|    True |
+---------+

LENGTH

LENGTH(value)

Description

Returns the length of the value. The returned value is in characters for STRING arguments and in bytes for the BYTES argument.

Return type

INT64

Examples

Table example:

+----------------+
| characters     |
+----------------+
| абвгд          |
+----------------+

SELECT
  characters,
  LENGTH(characters) AS string_example,
  LENGTH(CAST(characters AS BYTES)) AS bytes_example
FROM example;

+------------+----------------+---------------+
| characters | string_example | bytes_example |
+------------+----------------+---------------+
| абвгд      |              5 |            10 |
+------------+----------------+---------------+

LOWER

LOWER(value)

Description

For STRING arguments, returns the original string with all alphabetic characters in lowercase. Mapping between lowercase and uppercase is done according to the Unicode Character Database without taking into account language-specific mappings.

For BYTES arguments, the argument is treated as ASCII text, with all bytes greater than 127 left intact.

Return type

STRING or BYTES

Examples

Table items:

+----------------+
| item           |
+----------------+
| FOO            |
| BAR            |
| BAZ            |
+----------------+

SELECT
  LOWER(item) AS example
FROM items;

+---------+
| example |
+---------+
| foo     |
| bar     |
| baz     |
+---------+

LTRIM

LTRIM(value1[, value2])

Description

Identical to TRIM, but only removes leading characters.

Return type

STRING or BYTES

Examples

Table items:

+----------------+
| item           |
+----------------+
|    apple       |
|    banana      |
|    orange      |
+----------------+

SELECT
  CONCAT("#", LTRIM(item), "#") as example
FROM items;

+-------------+
| example     |
+-------------+
| #apple   #  |
| #banana   # |
| #orange   # |
+-------------+

Table items:

+----------------+
| item           |
+----------------+
| ***apple***    |
| ***banana***   |
| ***orange***   |
+----------------+

SELECT
  LTRIM(item, "*") as example
FROM items;

+-----------+
| example   |
+-----------+
| apple***  |
| banana*** |
| orange*** |
+-----------+

Table items:

+----------------+
| item           |
+----------------+
| xxxapple       |
| yyybanana      |
| zzzorange      |
| xyzpear        |
+----------------+

SELECT
  LTRIM(item, "xyz") as example
FROM items;

+---------+
| example |
+---------+
| apple   |
| banana  |
| orange  |
| pear    |
+---------+

REGEXP_CONTAINS

REGEXP_CONTAINS(value, regex)

Description

Returns TRUE if value is a partial match for the regular expression, regex. You can search for a full match by using ^ (beginning of text) and $ (end of text).

If the regex argument is invalid, the function returns an error.

Note: Cloud Spanner SQL provides regular expression support using the re2 library; see that documentation for its regular expression syntax.

Return type

BOOL

Examples

SELECT
  email,
  REGEXP_CONTAINS(email, r"@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+") AS is_valid
FROM
  (SELECT
    ["foo@example.com", "bar@example.org", "www.example.net"]
    AS addresses),
  UNNEST(addresses) AS email;

+-----------------+----------+
| email           | is_valid |
+-----------------+----------+
| foo@example.com | true     |
| bar@example.org | true     |
| www.example.net | false    |
+-----------------+----------+

# Performs a full match, using ^ and $.
SELECT
  email,
  REGEXP_CONTAINS(email, r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$")
    AS valid_email_address
FROM
  (SELECT
    ["foo@example.com", "bar@example.org", "www.example.net"]
    AS addresses),
  UNNEST(addresses) AS email;

+-----------------+---------------------+
| email           | valid_email_address |
+-----------------+---------------------+
| foo@example.com | true                |
| bar@example.org | true                |
| www.example.net | false               |
+-----------------+---------------------+

REGEXP_EXTRACT

REGEXP_EXTRACT(value, regex)

Description

Returns the first substring in value that matches the regular expression, regex. Returns NULL if there is no match.

If the regular expression contains a capturing group, the function returns the substring that is matched by that capturing group. If the expression does not contain a capturing group, the function returns the entire matching substring.

Returns an error if:

  • The regular expression is invalid
  • The regular expression has more than one capturing group

Note: Cloud Spanner SQL provides regular expression support using the re2 library; see that documentation for its regular expression syntax.

Return type

STRING or BYTES

Examples

Table email_addresses:

+-------------------------+
| email                   |
+-------------------------+
| foo@example.com         |
| bar@example.com         |
| baz@example.com         |
+-------------------------+

SELECT
  REGEXP_EXTRACT(email, r"^[a-zA-Z0-9_.+-]+")
  AS user_name
FROM email_addresses;

+-----------+
| user_name |
+-----------+
| foo       |
| bar       |
| baz       |
+-----------+

Table email_addresses:

+-------------------------+
| email                   |
+-------------------------+
| foo@example.com         |
| bar@example.com         |
| baz@example.com         |
+-------------------------+

SELECT
  REGEXP_EXTRACT(email, r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.([a-zA-Z0-9-.]+$)")
  AS top_level_domain
FROM email_addresses;

+------------------+
| top_level_domain |
+------------------+
| com              |
| org              |
| net              |
+------------------+

REGEXP_EXTRACT_ALL

REGEXP_EXTRACT_ALL(value, regex)

Description

Returns an array of all substrings of value that match the regular expression, regex.

The REGEXP_EXTRACT_ALL function only returns non-overlapping matches. For example, using this function to extract ana from banana returns only one substring, not two.

Note: Cloud Spanner SQL provides regular expression support using the re2 library; see that documentation for its regular expression syntax.

Return type

An ARRAY of either STRINGs or BYTES

Examples

Table code_markdown:

+------------------------------------+
| code                               |
+------------------------------------+
| Try `function(x)` or `function(y)` |
+------------------------------------+

SELECT
  REGEXP_EXTRACT_ALL(code, "`(.+?)`") AS example
FROM code_markdown;

+----------------------------+
| example                    |
+----------------------------+
| [function(x), function(y)] |
+----------------------------+

REGEXP_REPLACE

REGEXP_REPLACE(value, regex, replacement)

Description

Returns a STRING where all substrings of value that match regular expression regex are replaced with replacement.

You can use backslashed-escaped digits (\1 to \9) within the replacement argument to insert text matching the corresponding parenthesized group in the regex pattern. Use \0 to refer to the entire matching text.

Note: To add a backslash in your regular expression, you must first escape it. For example, SELECT REGEXP_REPLACE("abc", "b(.)", "X\\1"); returns aXc.

The REGEXP_REPLACE function only replaces non-overlapping matches. For example, replacing ana within banana results in only one replacement, not two.

If the regex argument is not a valid regular expression, this function returns an error.

Note: Cloud Spanner SQL provides regular expression support using the re2 library; see that documentation for its regular expression syntax.

Return type

STRING or BYTES

Examples

Table markdown:

+-------------------------+
| heading                 |
+-------------------------+
| # Heading               |
| # Another heading       |
+-------------------------+

SELECT
  REGEXP_REPLACE(heading, r"^# ([a-zA-Z0-9\s]+$)", "<h1>\\1</h1>")
  AS html
FROM markdown;

+--------------------------+
| html                     |
+--------------------------+
| <h1>Heading</h1>         |
| <h1>Another heading</h1> |
+--------------------------+

REPLACE

REPLACE(original_value, from_value, to_value)

Description

Replaces all occurrences of from_value with to_value in original_value. If from_value is empty, no replacement is made.

Return type

STRING or BYTES

Examples

+--------------------+
| dessert            |
+--------------------+
| apple pie          |
| blackberry pie     |
| cherry pie         |
+--------------------+

SELECT
  REPLACE (dessert, "pie", "cobbler") as example
FROM desserts;

+--------------------+
| example            |
+--------------------+
| apple cobbler      |
| blackberry cobbler |
| cherry cobbler     |
+--------------------+

RTRIM

RTRIM(value1[, value2])

Description

Identical to TRIM, but only removes trailing characters.

Return type

STRING or BYTES

Examples

Table items:

+----------------+
| item           |
+----------------+
| ***apple***    |
| ***banana***   |
| ***orange***   |
+----------------+

SELECT
  RTRIM(item, "*") as example
FROM items;

+-----------+
| example   |
+-----------+
| ***apple  |
| ***banana |
| ***orange |
+-----------+

Table items:

+----------------+
| item           |
+----------------+
| applexxx       |
| bananayyy      |
| orangezzz      |
| pearxyz        |
+----------------+

SELECT
  RTRIM(item, "xyz") as example
FROM items;

+---------+
| example |
+---------+
| apple   |
| banana  |
| orange  |
| pear    |
+---------+

STARTS_WITH

STARTS_WITH(value1, value2)

Description

Takes two values. Returns TRUE if the second value is a prefix of the first.

Return type

BOOL

Examples

SELECT
  STARTS_WITH(item, "b") as example
FROM (
  SELECT "foo" as item
  UNION ALL SELECT "bar" as item
  UNION ALL SELECT "baz" as item) AS items;

+---------+
| example |
+---------+
|   False |
|    True |
|    True |
+---------+

STRPOS

STRPOS(value1, value2)

Description

Returns the 1-based index of the first occurrence of value2 inside value1. Returns 0 if value2 is not found.

Return type

INT64

Examples

Table email_addresses:

+-------------------------+
| email_address           |
+-------------------------+
| foo@example.com         |
| foobar@example.com      |
| foobarbaz@example.com   |
| quxexample.com          |
+-------------------------+

SELECT
  STRPOS(email_address, "@") AS example
FROM email_addresses;

+---------+
| example |
+---------+
|       4 |
|       7 |
|      10 |
|       0 |
+---------+

SUBSTR

SUBSTR(value, position[, length])

Description

Returns a substring of the supplied value. The position argument is an integer specifying the starting position of the substring, with position = 1 indicating the first character or byte. The length argument is the maximum number of characters for STRING arguments, or bytes for BYTES arguments.

If position is negative, the function counts from the end of value, with -1 indicating the last character.

If position is a position off the left end of the STRING (position = 0 or position < -LENGTH(value)), the function starts from position = 1. If length exceeds the length of value, returns fewer than length characters.

If length is less than 0, the function returns an error.

Return type

STRING or BYTES

Examples

Table items:

+----------------+
| item           |
+----------------+
| apple          |
| banana         |
| orange         |
+----------------+

SELECT
  SUBSTR(item, 2) as example
FROM items;

+---------+
| example |
+---------+
| pple    |
| anana   |
| range   |
+---------+

Table items:

+----------------+
| item           |
+----------------+
| apple          |
| banana         |
| orange         |
+----------------+

SELECT
  SUBSTR(item, 2, 2) as example
FROM items;

+---------+
| example |
+---------+
| pp      |
| an      |
| ra      |
+---------+

Table items:

+----------------+
| item           |
+----------------+
| apple          |
| banana         |
| orange         |
+----------------+

SELECT
  SUBSTR(item, -2) as example
FROM items;

+---------+
| example |
+---------+
| le      |
| na      |
| ge      |
+---------+

TRIM

TRIM(value1[, value2])

Description

Removes all leading and trailing characters that match value2. If value2 is not specified, all leading and trailing whitespace characters (as defined by the Unicode standard) are removed. If the first argument is of type BYTES, the second argument is required.

If value2 contains more than one character or byte, the function removes all leading or trailing characters or bytes contained in value2.

Return type

STRING or BYTES

Examples

Table items:

+----------------+
| item           |
+----------------+
|    apple       |
|    banana      |
|    orange      |
+----------------+

SELECT
  CONCAT("#", TRIM(item), "#") as example
FROM items;

+----------+
| example  |
+----------+
| #apple#  |
| #banana# |
| #orange# |
+----------+

Table items:

+----------------+
| item           |
+----------------+
| ***apple***    |
| ***banana***   |
| ***orange***   |
+----------------+

SELECT
  TRIM(item, "*") as example
FROM items;

+---------+
| example |
+---------+
| apple   |
| banana  |
| orange  |
+---------+

Table items:

+----------------+
| item           |
+----------------+
| xxxapplexxx    |
| yyybananayyy   |
| zzzorangezzz   |
| xyzpearxyz     |
+----------------+

SELECT
  TRIM(item, "xyz") as example
FROM items;

+---------+
| example |
+---------+
| apple   |
| banana  |
| orange  |
| pear    |
+---------+

UPPER

UPPER(value)

Description

For STRING arguments, returns the original string with all alphabetic characters in uppercase. Mapping between uppercase and lowercase is done according to the Unicode Character Database without taking into account language-specific mappings.

For BYTES arguments, the argument is treated as ASCII text, with all bytes greater than 127 left intact.

Return type

STRING or BYTES

Examples

Table items:

+----------------+
| item           |
+----------------+
| foo            |
| bar            |
| baz            |
+----------------+

SELECT
  UPPER(item) AS example
FROM items;

+---------+
| example |
+---------+
| FOO     |
| BAR     |
| BAZ     |
+---------+

Array functions

ARRAY_LENGTH

ARRAY_LENGTH(array_expression)

Description

Returns the size of the array. Returns 0 for an empty array. Returns NULL if the array_expression is NULL.

Return type

INT64

Examples

SELECT list, ARRAY_LENGTH(list) AS size
FROM (
  SELECT ["apples", "bananas", NULL, "grapes"] as list
  UNION ALL SELECT ["coffee", "tea", "milk" ] as list
  UNION ALL SELECT ["cake", "pie"] as list) AS items
ORDER BY size DESC;

+---------------------------------+------+
| list                            | size |
+---------------------------------+------+
| [apples, bananas, NULL, grapes] | 4    |
| [coffee, tea, milk]             | 3    |
| [cake, pie]                     | 2    |
+---------------------------------+------+

OFFSET and ORDINAL

array_expression[OFFSET(zero_based_offset)]
array_expression[ORDINAL(one_based_offset)]

Description

Accesses an ARRAY element by position and returns the element. OFFSET means that the numbering starts at zero, ORDINAL means that the numbering starts at one.

A given array can be interpreted as either 0-based or 1-based. When accessing an array element, you must preface the array position with OFFSET or ORDINAL, respectively; there is no default behavior.

Both OFFSET and ORDINAL generate an error if the index is out of range.

Return type

Varies depending on the elements in the ARRAY.

Examples

SELECT list, list[OFFSET(1)] as offset_1, list[ORDINAL(1)] as ordinal_1
FROM (
  SELECT ["apples", "bananas", "pears", "grapes"] as list
  UNION ALL SELECT ["coffee", "tea", "milk" ] as list
  UNION ALL SELECT ["cake", "pie"] as list) AS items;

+----------------------------------+-----------+-----------+
| list                             | offset_1  | ordinal_1 |
+----------------------------------+-----------+-----------+
| [apples, bananas, pears, grapes] | bananas   | apples    |
| [coffee, tea, milk]              | tea       | coffee    |
| [cake, pie]                      | pie       | cake      |
+----------------------------------+-----------+-----------+

Date functions

Cloud Spanner SQL supports the following DATE functions.

EXTRACT

EXTRACT(part FROM date_expression)

Description

Returns the value corresponding to the specified date part. The part must be one of:

  • DAYOFWEEK: Returns values in the range [1,7] with Sunday as the first day of the week.
  • DAY
  • DAYOFYEAR
  • WEEK: Returns the week number of the date in the range [0, 53]. Weeks begin with Sunday, and dates prior to the first Sunday of the year are in week 0.
  • ISOWEEK: Returns the ISO 8601 week number of the date. Return values are in the range [1, 53], where dates prior to the first Monday of the Gregorian calendar year belong to the last ISO week of the previous year.
  • MONTH
  • QUARTER: Returns values in the range [1,4].
  • YEAR
  • ISOYEAR: Returns the ISO 8601 week-numbering year, which is the Gregorian calendar year containing the Thursday of the week to which date_expression belongs.

Return Data Type

INT64

Examples

In the following example, EXTRACT returns a value corresponding to the DAY time part.

SELECT EXTRACT(DAY FROM DATE '2013-12-25') as the_day;

+---------+
| the_day |
+---------+
| 25      |
+---------+

DATE

1. DATE(year, month, day)
2. DATE(timestamp_expression[, timezone])

Description

  1. Constructs a DATE from INT64 values representing the year, month, and day.
  2. Converts a timestamp_expression to a DATE data type. It supports an optional parameter to specify a timezone. If no timezone is specified, the default timezone, America/Los_Angeles, is used.

Return Data Type

DATE

Example

SELECT
  DATE(2016, 12, 25) as date_ymd,
  DATE(TIMESTAMP "2016-12-25 05:30:00+07", "America/Los_Angeles") as date_tstz;

+------------+------------+
| date_ymd   | date_tstz  |
+------------+------------+
| 2016-12-25 | 2016-12-24 |
+------------+------------+

DATE_ADD

DATE_ADD(date_expression, INTERVAL INT64_expr date_part)

Description

Adds a specified time interval to a DATE.

DATE_ADD supports the following date_part values:

  • DAY
  • WEEK. Equivalent to 7 DAYs.
  • MONTH
  • QUARTER
  • YEAR

Special handling is required for MONTH, QUARTER, and YEAR parts when the date is at (or near) the last day of the month. If the resulting month has fewer days than the original date's day, then the result day is the last day of the new month.

Return Data Type

DATE

Example

SELECT DATE_ADD(DATE "2008-12-25", INTERVAL 5 DAY) as five_days_later;

+--------------------+
| five_days_later    |
+--------------------+
| 2008-12-30         |
+--------------------+

DATE_SUB

DATE_SUB(date_expression, INTERVAL INT64_expr date_part)

Description

Subtracts a specified time interval from a DATE.

DATE_SUB supports the following date_part values:

  • DAY
  • WEEK. Equivalent to 7 DAYs.
  • MONTH
  • QUARTER
  • YEAR

Special handling is required for MONTH, QUARTER, and YEAR parts when the date is at (or near) the last day of the month. If the resulting month has fewer days than the original date's day, then the result day is the last day of the new month.

Return Data Type

DATE

Example

SELECT DATE_SUB(DATE "2008-12-25", INTERVAL 5 DAY) as five_days_ago;

+---------------+
| five_days_ago |
+---------------+
| 2008-12-20    |
+---------------+

DATE_DIFF

DATE_DIFF(date_expression, date_expression, date_part)

Description

Computes the number of specified date_part differences between two date expressions. This can be thought of as the number of date_part boundaries crossed between the two dates. If the first date occurs before the second date, then the result is negative.

DATE_DIFF supports the following date_part values:

  • DAY
  • MONTH
  • QUARTER
  • YEAR

Return Data Type

INT64

Example

SELECT DATE_DIFF(DATE "2010-07-07", DATE "2008-12-25", DAY) as days_diff;

+-----------+
| days_diff |
+-----------+
| 559       |
+-----------+

DATE_TRUNC

DATE_TRUNC(date_expression, date_part)

Description

Truncates the date to the specified granularity.

DATE_TRUNC supports the following values for date_part:

  • DAY
  • WEEK
  • MONTH
  • QUARTER
  • YEAR

Return Data Type

DATE

Example

SELECT DATE_TRUNC(DATE '2008-12-25', MONTH) as month;

+------------+
| month      |
+------------+
| 2008-12-01 |
+------------+

DATE_FROM_UNIX_DATE

DATE_FROM_UNIX_DATE(INT64_expression)

Description

Interprets INT64_expression as the number of days since 1970-01-01.

Return Data Type

DATE

Example

SELECT DATE_FROM_UNIX_DATE(14238) as date_from_epoch;

+-----------------+
| date_from_epoch |
+-----------------+
| 2008-12-25      |
+-----------------+

FORMAT_DATE

FORMAT_DATE(format_string, date_expr)

Description

Formats the date_expr according to the specified format_string.

See Supported Format Elements For DATE for a list of format elements that this function supports.

Return Data Type

STRING

Example

SELECT FORMAT_DATE("%x", DATE "2008-12-25") as US_format;

+------------+
| US_format  |
+------------+
| 12/25/08   |
+------------+

PARSE_DATE

PARSE_DATE(format_string, date_string)

Description

Uses a format_string and a string representation of a date to return a DATE object.

When using PARSE_DATE, keep the following in mind:

  • Unspecified fields. Any unspecified field is initialized from 1970-01-01.
  • Case insensitive names. 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 date string. In addition, leading and trailing white spaces in the date 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.

See Supported Format Elements For DATE for a list of format elements that this function supports.

Return Data Type

DATE

Example

SELECT PARSE_DATE("%x", "12/25/08") as parsed;

+------------+
| parsed     |
+------------+
| 2008-12-25 |
+------------+

UNIX_DATE

UNIX_DATE(date_expression)

Description

Returns the number of days since 1970-01-01.

Return Data Type

INT64

Example

SELECT UNIX_DATE(DATE "2008-12-25") as days_from_epoch;

+-----------------+
| days_from_epoch |
+-----------------+
| 14238           |
+-----------------+

Supported Format Elements for DATE

Unless otherwise noted, DATE functions that use format strings support the following elements:

Format element Description
%A The full weekday name.
%a The abbreviated weekday name.
%B The full month name.
%b or %h The abbreviated month name.
%C The century (a year divided by 100 and truncated to an integer) as a decimal number (00-99).
%D The date in the format %m/%d/%y.
%d The day of the month as a decimal number (01-31).
%e The day of month as a decimal number (1-31); single digits are preceded by a space.
%F The date in the format %Y-%m-%d.
%G The ISO 8601 year with century as a decimal number.
%g The ISO 8601 year without century as a decimal number (00-99).
%j The day of the year as a decimal number (001-366).
%m The month as a decimal number (01-12).
%n A newline character.
%t A tab character.
%U The week number of the year (Sunday as the first day of the week) as a decimal number (00-53).
%u The weekday (Monday as the first day of the week) as a decimal number (1-7).
%V The week number of the year (Monday as the first day of the week) as a decimal number (01-53). If the week containing January 1 has four or more days in the new year, then it is week 1; otherwise it is week 53 of the previous year, and the next week is week 1.
%W The week number of the year (Monday as the first day of the week) as a decimal number (00-53).
%w The weekday (Sunday as the first day of the week) as a decimal number (0-6).
%x The date representation in MM/DD/YY format.
%Y The year with century as a decimal number.
%y The year without century as a decimal number (00-99), with an optional leading zero. Can be mixed with %C. If %C is not specified, years 00-68 are 2000s, while years 69-99 are 1900s.
%E4Y Four-character years (0001 ... 9999). Note that %Y produces as many characters as it takes to fully render the year.

Timestamp functions

Cloud Spanner SQL supports the following TIMESTAMP functions.

NOTE: These functions return a runtime error if overflow occurs; result values are bounded by the defined date and timestamp min/max values.

CURRENT_TIMESTAMP

CURRENT_TIMESTAMP()

Description

Parentheses are optional. This function handles leap seconds by smearing them across a window of 20 hours around the inserted leap second. CURRENT_TIMESTAMP() produces a TIMESTAMP value that is continuous, non-ambiguous, has exactly 60 seconds per minute and does not repeat values over the leap second.

Supported Input Types

Not applicable

Result Data Type

TIMESTAMP

Example

SELECT CURRENT_TIMESTAMP() as now;

+----------------------------------+
| now                              |
+----------------------------------+
| 2016-05-16 18:12:47.145482639+00 |
+----------------------------------+

EXTRACT

EXTRACT(part FROM timestamp_expression [AT TIME ZONE tz_spec])

Description

Returns an INT64 value that corresponds to the specified part from a supplied timestamp_expression.

Allowed part values are:

  • NANOSECOND
  • MICROSECOND
  • MILLISECOND
  • SECOND
  • MINUTE
  • HOUR
  • DAYOFWEEK
  • DAY
  • DAYOFYEAR
  • WEEK: Returns the week number of the date in the range [0, 53]. Weeks begin with Sunday, and dates prior to the first Sunday of the year are in week 0.
  • ISOWEEK: Returns the ISO 8601 week number of the date. Return values are in the range [1, 53], where dates prior to the first Monday of the Gregorian calendar year belong to the last ISO week of the previous year.
  • MONTH
  • QUARTER
  • YEAR
  • ISOYEAR: Returns the ISO 8601 week-numbering year, which is the Gregorian calendar year containing the Thursday of the week to which date_expression belongs.
  • DATE

Returned values truncate lower order time periods. For example, when extracting seconds, EXTRACT truncates the millisecond and microsecond values.

See Timezone definitions for information on how to specify a time zone.

Return Data Type

Generally INT64 . Returns DATE if part is DATE.

In the following example, EXTRACT returns values corresponding to different time parts from a column of timestamps.

SELECT
  timestamp,
  EXTRACT(ISOYEAR FROM timestamp) AS isoyear,
  EXTRACT(ISOWEEK FROM timestamp) AS isoweek,
  EXTRACT(YEAR FROM timestamp) AS year,
  EXTRACT(WEEK FROM timestamp) AS week
FROM (
    SELECT TIMESTAMP '2005-01-03 12:34:56' AS timestamp UNION ALL
    SELECT TIMESTAMP '2007-12-31' UNION ALL
    SELECT TIMESTAMP '2009-01-01' UNION ALL
    SELECT TIMESTAMP '2009-12-31' UNION ALL
    SELECT TIMESTAMP '2017-01-02' UNION ALL
    SELECT TIMESTAMP '2017-05-26'
  ) AS Timestamps
ORDER BY timestamp;
+------------------------+---------+---------+------+------+
| timestamp              | isoyear | isoweek | year | week |
+------------------------+---------+---------+------+------+
| 2005-01-03 12:34:56+00 | 2005    | 1       | 2005 | 1    |
| 2007-12-31 00:00:00+00 | 2008    | 1       | 2007 | 52   |
| 2009-01-01 00:00:00+00 | 2009    | 1       | 2009 | 0    |
| 2009-12-31 00:00:00+00 | 2009    | 53      | 2009 | 52   |
| 2017-01-02 00:00:00+00 | 2017    | 1       | 2017 | 1    |
| 2017-05-26 00:00:00+00 | 2017    | 21      | 2017 | 21   |
+------------------------+---------+---------+------+------+

STRING

STRING(timestamp_expression[, timezone])

Description

Converts a timestamp_expression to a STRING data type. Supports an optional parameter to specify a timezone. See Timezone definitions for information on how to specify a time zone.

Return Data Type

STRING

TIMESTAMP

1. TIMESTAMP(string_expression[, timezone])
2. TIMESTAMP(date_expression[, timezone])

Description

  1. Converts a STRING expression to a TIMESTAMP data type.

  2. Converts a DATE object to a TIMESTAMP data type.

This function supports an optional parameter to specify a timezone. If no timezone is specified, the default timezone, America/Los_Angeles, is used.

Return Data Type

TIMESTAMP

Example

SELECT
  CAST(TIMESTAMP("2008-12-25 15:30:00", "America/Los_Angeles") AS STRING) AS timestamp_str,
  CAST(TIMESTAMP(DATE "2008-12-25", "America/Los_Angeles") AS STRING) AS timestamp_date;

+------------------------+------------------------+
| timestamp_str          | timestamp_date         |
+------------------------+------------------------+
| 2008-12-25 15:30:00-08 | 2008-12-25 00:00:00-08 |
+------------------------+------------------------+

TIMESTAMP_ADD

TIMESTAMP_ADD(timestamp_expression, INTERVAL int64_expression date_part)

Description

Adds int64_expression units of date_part to the timestamp, independent of any time zone.

TIMESTAMP_ADD supports the following values for date_part:

  • NANOSECOND
  • MICROSECOND
  • MILLISECOND
  • SECOND
  • MINUTE
  • HOUR. Equivalent to 60 MINUTEs.

Return Data Types

TIMESTAMP

Example

SELECT
  TIMESTAMP "2008-12-25 15:30:00 UTC" as original,
  TIMESTAMP_ADD(TIMESTAMP "2008-12-25 15:30:00 UTC", INTERVAL 10 MINUTE) AS later;

+------------------------+------------------------+
| original               | later                  |
+------------------------+------------------------+
| 2008-12-25 15:30:00+00 | 2008-12-25 15:40:00+00 |
+------------------------+------------------------+

TIMESTAMP_SUB

TIMESTAMP_SUB(timestamp_expression, INTERVAL int64_expression date_part)

Description

Subtracts int64_expression units of date_part from the timestamp, independent of any time zone.

TIMESTAMP_SUB supports the following values for date_part:

  • NANOSECOND
  • MICROSECOND
  • MILLISECOND
  • SECOND
  • MINUTE
  • HOUR. Equivalent to 60 MINUTEs.

Return Data Type

TIMESTAMP

Example

SELECT
  TIMESTAMP "2008-12-25 15:30:00 UTC" as original,
  TIMESTAMP_SUB(TIMESTAMP "2008-12-25 15:30:00 UTC", INTERVAL 10 MINUTE) AS earlier;

+------------------------+------------------------+
| original               | earlier                |
+------------------------+------------------------+
| 2008-12-25 15:30:00+00 | 2008-12-25 15:20:00+00 |
+------------------------+------------------------+

TIMESTAMP_DIFF

TIMESTAMP_DIFF(timestamp_expression, timestamp_expression, date_part)

Description

Returns the number of whole specified date_part intervals between two timestamps. Throws 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.

TIMESTAMP_DIFF supports the following values for date_part:

  • NANOSECOND
  • MICROSECOND
  • MILLISECOND
  • SECOND
  • MINUTE
  • HOUR. Equivalent to 60 MINUTEs.

Return Data Type

INT64

Example

SELECT
  TIMESTAMP "2010-07-07 10:20:00 UTC" as first_timestamp,
  TIMESTAMP "2008-12-25 15:30:00 UTC" as second_timestamp,
  TIMESTAMP_DIFF(TIMESTAMP "2010-07-07 10:20:00 UTC",
    TIMESTAMP "2008-12-25 15:30:00 UTC", HOUR) AS hours;

+------------------------+------------------------+-------+
| first_timestamp        | second_timestamp       | hours |
+------------------------+------------------------+-------+
| 2010-07-07 10:20:00+00 | 2008-12-25 15:30:00+00 | 13410 |
+------------------------+------------------------+-------+

TIMESTAMP_TRUNC

TIMESTAMP_TRUNC(timestamp_expression, date_part, [, time_zone])

Description

Truncates a timestamp to the granularity of date_part.

TIMESTAMP_TRUNC supports the following values for date_part:

  • NANOSECOND
  • MICROSECOND
  • MILLISECOND
  • SECOND
  • MINUTE
  • HOUR
  • DAY
  • WEEK
  • MONTH
  • QUARTER
  • YEAR

In addition, TIMESTAMP_TRUNC function supports an optional time_zone parameter. This parameter applies to the following date_parts:

  • MINUTE
  • HOUR
  • DAY
  • WEEK
  • MONTH
  • QUARTER
  • YEAR

Use this parameter if you want to use a time zone other than the default timezone, America/Los_Angeles, as part of the truncate operation.

Return Data Type

TIMESTAMP

Example

SELECT
  TIMESTAMP_TRUNC(TIMESTAMP '2008-12-25 15:30:00', DAY, 'UTC') as utc,
  TIMESTAMP_TRUNC(TIMESTAMP '2008-12-25 15:30:00', DAY, 'America/Los_Angeles') as la;

+------------------------+------------------------+
| utc                    | la                     |
+------------------------+------------------------+
| 2008-12-25 00:00:00+00 | 2008-12-25 08:00:00+00 |
+------------------------+------------------------+

FORMAT_TIMESTAMP

FORMAT_TIMESTAMP(format_string, timestamp[, time_zone])

Description

Formats a timestamp according to the specified format_string.

See Supported Format Elements For TIMESTAMP for a list of format elements that this function supports.

Return Data Type

STRING

Example

SELECT FORMAT_TIMESTAMP("%c", TIMESTAMP "2008-12-25 15:30:00", "America/Los_Angeles")
  AS formatted;

+--------------------------+
| formatted                |
+--------------------------+
| Thu Dec 25 07:30:00 2008 |
+--------------------------+

TIMESTAMP_SECONDS

TIMESTAMP_SECONDS(int64_expression)

Description

Interprets int64_expression as the number of seconds since 1970-01-01 00:00:00 UTC.

Return Data Type

TIMESTAMP

Example

SELECT TIMESTAMP_SECONDS(1230219000) as timestamp;

+-------------------------+
| timestamp               |
+-------------------------+
| 2008-12-25 15:30:00 UTC |
+-------------------------+

TIMESTAMP_MILLIS

TIMESTAMP_MILLIS(int64_expression)

Description

Interprets int64_expression as the number of milliseconds since 1970-01-01 00:00:00 UTC.

Return Data Type

TIMESTAMP

Example

SELECT TIMESTAMP_MILLIS(1230219000000) as timestamp;

+-------------------------+
| timestamp               |
+-------------------------+
| 2008-12-25 15:30:00 UTC |
+-------------------------+

TIMESTAMP_MICROS

TIMESTAMP_MICROS(int64_expression)

Description

Interprets int64_expression as the number of microseconds since 1970-01-01 00:00:00 UTC.

Return Data Type

TIMESTAMP

Example

SELECT TIMESTAMP_MICROS(1230219000000000) as timestamp;

+-------------------------+
| timestamp               |
+-------------------------+
| 2008-12-25 15:30:00 UTC |
+-------------------------+

UNIX_SECONDS

UNIX_SECONDS(timestamp_expression)

Description

Returns the number of seconds since 1970-01-01 00:00:00 UTC. Truncates higher levels of precision.

Return Data Type

INT64

Example

SELECT UNIX_SECONDS(TIMESTAMP "2008-12-25 15:30:00") as seconds;

+------------+
| seconds    |
+------------+
| 1230219000 |
+------------+

UNIX_MILLIS

UNIX_MILLIS(timestamp_expression)

Description

Returns the number of milliseconds since 1970-01-01 00:00:00 UTC. Truncates higher levels of precision.

Return Data Type

INT64

Example

SELECT UNIX_MILLIS(TIMESTAMP "2008-12-25 15:30:00 UTC") as millis;

+---------------+
| millis        |
+---------------+
| 1230219000000 |
+---------------+

UNIX_MICROS

UNIX_MICROS(timestamp_expression)

Description

Returns the number of microseconds since 1970-01-01 00:00:00 UTC. Truncates higher levels of precision.

Return Data Type

INT64

Example

SELECT UNIX_MICROS(TIMESTAMP "2008-12-25 15:30:00") as micros;

+------------------+
| micros           |
+------------------+
| 1230219000000000 |
+------------------+

Supported format elements for TIMESTAMP

Unless otherwise noted, TIMESTAMP functions that use format strings support the following elements:

Format element Description
%A The full weekday name.
%a The abbreviated weekday name.
%B The full month name.
%b or %h The abbreviated month name.
%C The century (a year divided by 100 and truncated to an integer) as a decimal number (00-99).
%c The date and time representation.
%D The date in the format %m/%d/%y.
%d The day of the month as a decimal number (01-31).
%e The day of month as a decimal number (1-31); single digits are preceded by a space.
%F The date in the format %Y-%m-%d.
%G The ISO 8601 year with century as a decimal number.
%g The ISO 8601 year without century as a decimal number (00-99).
%H The hour (24-hour clock) as a decimal number (00-23).
%I The hour (12-hour clock) as a decimal number (01-12).
%j The day of the year as a decimal number (001-366).
%k The hour (24-hour clock) as a decimal number (0-23); single digits are preceded by a space.
%l The hour (12-hour clock) as a decimal number (1-12); single digits are preceded by a space.
%M The minute as a decimal number (00-59).
%m The month as a decimal number (01-12).
%n A newline character.
%P Either am or pm.
%p Either AM or PM.
%R The time in the format %H:%M.
%r The 12-hour clock time using AM/PM notation.
%S The second as a decimal number (00-60).
%s The number of seconds since 1970-01-01 00:00:00 UTC. Always overrides all other format elements, independent of where %s appears in the string. If multiple %s elements appear, then the last one takes precedence.
%T The time in the format %H:%M:%S.
%t A tab character.
%U The week number of the year (Sunday as the first day of the week) as a decimal number (00-53).
%u The weekday (Monday as the first day of the week) as a decimal number (1-7).
%V The week number of the year (Monday as the first day of the week) as a decimal number (01-53). If the week containing January 1 has four or more days in the new year, then it is week 1; otherwise it is week 53 of the previous year, and the next week is week 1.
%W The week number of the year (Monday as the first day of the week) as a decimal number (00-53).
%w The weekday (Sunday as the first day of the week) as a decimal number (0-6).
%X The time representation in HH:MM:SS format.
%x The date representation in MM/DD/YY format.
%Y The year with century as a decimal number.
%y The year without century as a decimal number (00-99), with an optional leading zero. Can be mixed with %C. If %C is not specified, years 00-68 are 2000s, while years 69-99 are 1900s.
%Z The time zone name.
%z The offset from the Prime Meridian in the format +HHMM or -HHMM as appropriate, with positive values representing locations east of Greenwich.
%% A single % character.
%Ez RFC3339-compatible numeric time zone (+HH:MM or -HH:MM).
%E#S Seconds with # digits of fractional precision.
%E*S Seconds with full fractional precision (a literal '*').
%E4Y Four-character years (0001 ... 9999). Note that %Y produces as many characters as it takes to fully render the year.

Timezone definitions

Certain date and timestamp functions allow you to override the default time zone and specify a different one. You can specify a timezone by supplying its UTC offset using the following format:

(+|-)H[H][:M[M]]

For example:

-08:00

Operators

Operators are represented by special characters or keywords; they do not use function call syntax. An operator manipulates any number of data inputs, also called operands, and returns a result.

Common conventions:

  • Unless otherwise specified, all operators return NULL when one of the operands is NULL.
  • All operators will throw an error if the computation result overflows.
  • For all floating point operations, +/-inf and NaN may only be returned if one of the operands is +/-inf or NaN. In other cases, an error is returned.

The following table lists all Cloud Spanner SQL operators from highest to lowest precedence, i.e. the order in which they will be evaluated within a statement.

Order of Precedence Operator Input Data Types Name Operator Arity
1 . STRUCT
Member field access operator Binary
  [ ] ARRAY Array position. Must be used with OFFSET or ORDINAL—see ARRAY Functions. Binary
2 - Numeric Unary minus Unary
  ~ Integer Bitwise not Unary
3 * Numeric Multiplication Binary
  / Numeric Division Binary
4 + Numeric Addition Binary
  - Numeric Subtraction Binary
5 << Integer Bitwise left-shift Binary
  >> Integer Bitwise right-shift Binary
6 & Integer Bitwise and Binary
7 ^ Integer Bitwise xor Binary
8 | Integer Bitwise or Binary
9 (Comparison Operators) = Any comparable type. See Data Types for a complete list. Equal Binary
  < Any comparable type. See Data Types for a complete list. Less than Binary
  > Any comparable type. See Data Types for a complete list. Greater than Binary
  <= Any comparable type. See Data Types for a complete list. Less than or equal to Binary
  >= Any comparable type. See Data Types for a complete list. Greater than or equal to Binary
  !=, <> Any comparable type. See Data Types for a complete list. Not equal Binary
  [NOT] LIKE STRING and byte Value does [not] match the pattern specified Binary
  [NOT] BETWEEN Any comparable types. See Data Types for list. Value is [not] within the range specified Binary
  [NOT] IN Any comparable types. See Data Types for list. Value is [not] in the set of values specified Binary
  IS [NOT] NULL All Value is [not] NULL Unary
  IS [NOT] TRUE BOOL Value is [not] TRUE. Unary
  IS [NOT] FALSE BOOL Value is [not] FALSE. Unary
10 NOT BOOL Logical NOT Unary
11 AND BOOL Logical AND Binary
12 OR BOOL Logical OR Binary

Operators with the same precedence are left associative. This means that those operators are grouped together starting from the left and moving right. For example, the expression:

x AND y AND z

is interpreted as

( ( x AND y ) AND z )

The expression:

x * y / z

is interpreted as:

( ( x * y ) / z )

All comparison operators have the same priority and are grouped using left associativity. However, comparison operators are not associative. As a result, it is recommended that you use parentheses to improve readability and ensure expressions are resolved as desired. For example:

(x < y) IS FALSE

is recommended over:

x < y IS FALSE

Element access operators

Operator Syntax Input Data Types Result Data Type Description
. expression.fieldname1... STRUCT
Type T stored in fieldname1 Dot operator. Can be used to access nested fields, e.g.expression.fieldname1.fieldname2...
[ ] array_expression [position_keyword (int_expression ) ] See ARRAY Functions. Type T stored in ARRAY position_keyword is either OFFSET or ORDINAL. See ARRAY Functions for the two functions that use this operator.

Arithmetic operators

All arithmetic operators accept input of numeric type T, and the result type has type T unless otherwise indicated in the description below:

Name Syntax
Addition X + Y
Subtraction X - Y
Multiplication X * Y
Division X / Y
Unary Minus - X

NOTE: Divide by zero operations return an error. To return a different result, consider the IEEE_DIVIDE or SAFE_DIVIDE functions.

Result types for Addition and Multiplication:

 FLOAT64INT64
FLOAT64FLOAT64FLOAT64
INT64FLOAT64INT64

Result types for Subtraction:

 FLOAT64INT64
FLOAT64FLOAT64FLOAT64
INT64FLOAT64INT64

Result types for Division:

 FLOAT64INT64
FLOAT64FLOAT64FLOAT64
INT64FLOAT64FLOAT64

Result types for Unary Minus:

Input Data Type Result Data Type
INT64 INT64
FLOAT64 FLOAT64

Bitwise operators

All bitwise operators return the same type as the first operand.

Name Syntax Input Data Type Description
Bitwise not ~ X Integer Performs logical negation on each bit, forming the ones' complement of the given binary value.
Bitwise or X | Y X: Integer
Y: Same type as X
Takes two bit patterns of equal length and performs the logical inclusive OR operation on each pair of the corresponding bits.
Bitwise xor X ^ Y X: Integer
Y: Same type as X
Takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of the corresponding bits.
Bitwise and X & Y X: Integer
Y: Same type as X
Takes two bit patterns of equal length and performs the logical AND operation on each pair of the corresponding bits.
Left shift X << Y X: Integer
Y: INT64
Shifts the first operand X to the left. This operator returns 0 if the second operand Y is greater than or equal to 64. This operator throws an error if Y is negative.
Right shift X >> Y X: Integer
Y: INT64
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 with 0). This operator returns 0 if the second operand Y is greater than or equal to 64. This operator throws an error if Y is negative.

Logical operators

All logical operators allow only BOOL input.

Name Syntax Description
Logical NOT NOT X Returns FALSE if input is TRUE. Returns TRUE if input is FALSE. Returns NULL otherwise.
Logical AND X AND Y Returns FALSE if at least one input is FALSE. Returns TRUE if both X and Y are TRUE. Returns NULL otherwise.
Logical OR X OR Y Returns FALSE if both X and Y are FALSE. Returns TRUE if at least one input is TRUE. Returns NULL otherwise.

Comparison operators

Comparisons always return BOOL. Comparisons require both operands to be the same type; if they are different, they are coerced to a common type for the comparison. Comparable data types are defined in Data Types.

STRUCTs support only 4 comparison operators: equal (=), not equal (!= and <>), and IN.

The following rules apply when comparing these data types:

  • FLOAT64 : 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.
Name Syntax Description
Less Than X < Y Returns TRUE if X is less than Y.
Less Than or Equal To X <= Y Returns TRUE if X is less than or equal to Y.
Greater Than X > Y Returns TRUE if X is greater than Y.
Greater Than or Equal To X >= Y Returns TRUE if X is greater than or equal to Y.
Equal X = Y Returns TRUE if X is equal to Y.
Not Equal X != Y
X <> Y
Returns TRUE if X is not equal to Y.
BETWEEN X [NOT] BETWEEN Y AND Z Returns TRUE if X is [not] within the range specified. The result of "X BETWEEN Y AND Z" is equivalent to "Y <= X AND X <= Z" but X is evaluated only once in the former.
LIKE X [NOT] LIKE Y Checks if the STRING in the first operand X matches a pattern specified by the second operand Y. Expressions can contain these characters:
  • A percent sign "%" matches any number of characters or bytes
  • An underscore "_" matches a single character or byte
  • You can escape "\", "_", or "%" using two backslashes. For example, "\\%". If you are using raw strings, only a single backslash is required. For example, r"\%".
IN Multiple - see below Returns FALSE if the right operand is empty. Returns NULL if the left operand is NULL. Returns TRUE or NULL, never FALSE, if the right operand contains NULL. Arguments on either side of IN are general expressions. Neither operand is required to be a literal, although using a literal on the right is most common. X is evaluated only once.

When testing values that have a STRUCT data type for equality, it's possible that one or more fields are NULL. In such cases:

  • If all non-NULL field values are equal, the comparison returns NULL.
  • If any non-NULL field values are not equal, the comparison returns false.

The following table demonstrates how STRUCT data types are compared when they have fields that are NULL valued.

Struct1 Struct2 Struct1 = Struct2
STRUCT(1, NULL) STRUCT(1, NULL) NULL
STRUCT(1, NULL) STRUCT(2, NULL) FALSE
STRUCT(1,2) STRUCT(1, NULL) NULL

IN operators

The IN operator supports the following syntaxes:

x [NOT] IN (y, z, ... ) # Requires at least one element
x [NOT] IN (<subquery>)
x [NOT] IN UNNEST(<array expression>) # analysis error if the expression
                                      # does not return an ARRAY type.

Arguments on either side of the IN operator are general expressions. It is common to use literals on the right side expression; however, this is not required.

The semantics of:

x IN (y, z, ...)

are defined as equivalent to:

(x = y) OR (x = z) OR ...

and the subquery and array forms are defined similarly.

x NOT IN ...

is equivalent to:

NOT(x IN ...)

The UNNEST form treats an array scan like UNNEST in the FROM clause:

x [NOT] IN UNNEST(<array expression>)

This form is often used with ARRAY parameters. For example:

x IN UNNEST(@array_parameter)

Note: A NULL ARRAY will be treated equivalently to an empty ARRAY.

When using the IN operator, the following semantics apply:

  • IN with an empty right side expression is always FALSE
  • IN with a NULL left side expression and a non-empty right side expression is always NULL
  • IN with a NULL in the IN-list can only return TRUE or NULL, never FALSE
  • NULL IN (NULL) returns NULL
  • IN UNNEST(<NULL array>) returns FALSE (not NULL)

IN can be used with multi-part keys by using the struct constructor syntax. For example:

(Key1, Key2) IN ( (12,34), (56,78) )
(Key1, Key2) IN ( SELECT (table.a, table.b) FROM table )

See the Struct Type section of the Data Types topic for more information on this syntax.

IS operators

IS operators return TRUE or FALSE for the condition they are testing. They never return NULL, even for NULL inputs, unlike the IS_INF and IS_NAN functions defined in Mathematical Functions. If NOT is present, the output BOOL value is inverted.

Function Syntax Input Data Type Result Data Type Description
X IS [NOT] NULL
Any value type BOOL Returns TRUE if the operand X evaluates to NULL, and returns FALSE otherwise.
X IS [NOT] TRUE
BOOL BOOL Returns TRUE if the BOOL operand evaluates to TRUE. Returns FALSE otherwise.
X IS [NOT] FALSE
BOOL BOOL Returns TRUE if the BOOL operand evaluates to FALSE. Returns FALSE otherwise.

Conditional expressions

Conditional expressions impose constraints on the evaluation order of their inputs. In essence, they are evaluated left to right, with short-circuiting, and only evaluate the output value that was chosen. In contrast, all inputs to regular functions are evaluated before calling the function. Short-circuiting in conditional expressions can be exploited for error handling or performance tuning.

Syntax Input Data Types Result Data Type Description
CASE expr
  WHEN value THEN result
  [WHEN ...]
  [ELSE else_result]
  END
expr and value: Any type result and else_result: Supertype of input types. Compares expr to value of each successive WHEN clause and returns the first result where this comparison returns true. The remaining WHEN clauses and else_result are not evaluated. If the expr = value comparison returns false or NULL for all WHEN clauses, returns else_result. expr and value expressions must be implicitly coercible to a common supertype; equality comparisons are done on coerced values. result and else_result expressions must be coercible to a common supertype.
CASE
  WHEN cond1 THEN result
  [WHEN cond2...]
  [ELSE else_result]
  END
cond: BOOL result and else_result: Supertype of input types. Evaluates condition cond of each successive WHEN clause and returns the first result where the condition is true; any remaining WHEN clauses and else_result are not evaluated. If all conditions are false or NULL, returns else_result. result and else_result expressions must be implicitly coercible to a common supertype.
COALESCE(expr1, ..., exprN) Any type Supertype of input types Returns the value of the first non-null expression. The remaining expressions are not evaluated. All input expressions must be implicitly coercible to a common supertype.
IF(cond, true_result, else_result) cond: BOOL true_result and else_result: Any type. If cond is true, returns true_result, else returns else_result. else_result is not evaluated if cond is true. true_result is not evaluated if cond is false or NULL. true_result and else_result must be coercible to a common supertype.
IFNULL(expr, null_result) Any type Any type or supertype of input types. If expr is NULL, return null_result. Otherwise, return expr. If expr is not NULL, null_result is not evaluated. expr and null_result must be implicitly coercible to a common supertype. Synonym for COALESCE(expr, null_result).
NULLIF(expression, expression_to_match) Any type T or subtype of T Any type T or subtype of T Returns NULL if expression = expression_to_match is true, otherwise returns expression. expression and expression_to_match must be implicitly coercible to a common supertype; equality comparison is done on coerced values.

NULLIF does not support STRUCT types.

Expression subqueries

There are four types of expression subqueries, i.e. subqueries that are used as expressions. Expression subqueries return NULL or a single value, as opposed to a column or table, and must be surrounded by parentheses. For a fuller discussion of subqueries, see Subqueries.

Type of Subquery Result Data Type Description
Scalar Any type T A subquery in parentheses inside an expression (e.g. in the SELECT list or WHERE clause) is interpreted as a scalar subquery. The SELECT list in a scalar subquery must have exactly one field. If the subquery returns exactly one row, that single value is the scalar subquery result. If the subquery returns zero rows, the scalar subquery value is NULL. If the subquery returns more than one row, the query fails with a runtime error. When the subquery is written with SELECT AS STRUCT , it can include multiple columns, and the returned value is the constructed STRUCT. Selecting multiple columns without using SELECT AS is an error.
ARRAY ARRAY Can use SELECT AS STRUCT to build arrays of structs, and conversely, selecting multiple columns without using SELECT AS is an error. Returns an empty ARRAY if the subquery returns zero rows. Never returns a NULL ARRAY.
IN BOOL Occurs in an expression following the IN operator. The subquery must produce a single column whose type is equality-compatible with the expression on the left side of the IN operator. Returns FALSE if the subquery returns zero rows. x IN () is equivalent to x IN (value, value, ...) See the IN operator in Comparison Operators for full semantics.
EXISTS BOOL Returns TRUE if the subquery produced one or more rows. Returns FALSE if the subquery produces zero rows. Never returns NULL. Unlike all other expression subqueries, there are no rules about the column list. Any number of columns may be selected and it will not affect the query result.

Examples

The following examples of expression subqueries assume that t.int_array has type ARRAY<INT64>.

Type Subquery Result Data Type Notes
Scalar (SELECT COUNT(*) FROM t.int_array) INT64  
(SELECT DISTINCT i FROM t.int_array i) INT64, possibly runtime error  
(SELECT i FROM t.int_array i WHERE i=5) INT64, possibly runtime error  
(SELECT ARRAY_AGG(i) FROM t.int_array i) ARRAY Uses the ARRAY_AGG aggregation function to return an ARRAY.
(SELECT 'xxx' a) STRING  
(SELECT 'xxx' a, 123 b) Error Returns an error because there is more than one column
(SELECT AS STRUCT 'xxx' a, 123 b) STRUCT  
(SELECT AS STRUCT 'xxx' a) STRUCT  
ARRAY ARRAY(SELECT COUNT(*) FROM t.int_array) ARRAY of size 1  
ARRAY(SELECT x FROM t) ARRAY  
ARRAY(SELECT 5 a, COUNT(*) b FROM t.int_array) Error Returns an error because there is more than one column
ARRAY(SELECT AS STRUCT 5 a, COUNT(*) b FROM t.int_array) ARRAY  
ARRAY(SELECT AS STRUCT i FROM t.int_array i) ARRAY Makes an ARRAY of one-field STRUCTs
ARRAY(SELECT AS STRUCT 1 x, 2, 3 x) ARRAY Returns an ARRAY of STRUCTs with anonymous or duplicate fields.
ARRAY(SELECT AS TypeName SUM(x) a, SUM(y) b, SUM(z) c from t) array<TypeName> Selecting into a named type. Assume TypeName is a STRUCT type with fields a,b,c.
STRUCT (SELECT AS STRUCT 1 x, 2, 3 x) STRUCT Constructs a STRUCT with anonymous or duplicate fields.
EXISTS EXISTS(SELECT x,y,z FROM table WHERE y=z) BOOL  
NOT EXISTS(SELECT x,y,z FROM table WHERE y=z) BOOL  
IN x IN (SELECT y FROM table WHERE z) BOOL  
x NOT IN (SELECT y FROM table WHERE z) BOOL  

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...

Cloud Spanner Documentation