Variant functions
Use these functions to read the keys, elements, and types of VARIANT values, to test what they contain, and to aggregate rows into a VARIANT array or object. A query result cannot hold a VARIANT value, so cast a VARIANT result to VARCHAR or JSON when you select it.
The examples on this page make VARIANT values by casting other values to VARIANT, as in {'a': 1}::VARIANT. To turn JSON text into a VARIANT object or array, cast the text to JSON first, as in '{"a": 1}'::JSON::VARIANT. For more information about the VARIANT type, see VARIANT type.
variant_array_length function
Returns the number of elements in input_variant, or in the value at path, when that value is an array. For any other value, such as an object or a number, the function returns 0. If input_variant is NULL, or if path names a key that the object does not have, the result is NULL.
Like many VARIANT functions, variant_array_length takes an optional path. The path is the name of one key at the top level of an object, not a nested path, so 'a.b' looks for a key named a.b. An empty string selects the whole value. When you pass a list of paths, the function returns a list with one result for each path, in the same order.
Syntax
variant_array_length(input_variant [, path ])
Arguments
The variant_array_length function takes the following arguments:
input_variant-
The value to inspect, as a
VARIANTvalue. path-
The key of the value to measure. It must be a constant
VARCHARthat names a key at the top level ofinput_variant, or a constantVARCHAR[]list of key names. The default is the whole value. This argument is optional.
Return type
UBIGINT, or UBIGINT[] when path is a list.
Examples
The following SQL query returns the number of elements in an array.
SELECT variant_array_length([1, 2, 3]::VARIANT) AS result
The query returns the following result.
| result |
|---|
|
The following SQL query returns the length of the array stored under the key tags.
SELECT variant_array_length( {'tags': ['red', 'blue']}::VARIANT, 'tags' ) AS result
The query returns the following result.
| result |
|---|
|
The following SQL query passes a list of keys. The value of a is not an array, so its length is 0.
SELECT variant_array_length( {'a': 1, 'b': [10, 20, 30]}::VARIANT, ['a', 'b'] ) AS result
The query returns the following result.
| result |
|---|
|
The following SQL query shows the difference between casting JSON text straight to VARIANT and casting it to JSON first. Casting straight to VARIANT makes a string, and casting to JSON first makes an array.
SELECT variant_array_length( '[1, 2, 3]'::VARIANT ) AS from_text, variant_array_length( '[1, 2, 3]'::JSON::VARIANT ) AS from_json
The query returns the following result.
| from_text | from_json |
|---|---|
|
|
Considerations
A query result cannot contain a VARIANT value. When you select a VARIANT value, such as a column or the result of variant_extract, cast it to VARCHAR or JSON.
Casting a VARCHAR value straight to VARIANT makes a VARIANT that holds that string, not a parsed array or object. For example, variant_array_length('[1, 2, 3]'::VARIANT) returns 0. Cast JSON text to JSON before you cast it to VARIANT.
path must be a constant. You cannot pass a column as the path.
variant_contains function
Returns true if variant_needle matches variant_haystack or any value nested inside it, at any depth. An object needle matches an object that has each of the needle's keys with a matching value, and the haystack object can have other keys too. An array needle matches an array that has a matching element for each of the needle's elements, in any order. Other values match when they are equal.
The function compares values, not key names. To test whether an object has a key, use the variant_exists function. If either argument is NULL, the result is NULL.
Syntax
variant_contains(variant_haystack, variant_needle)
Arguments
The variant_contains function takes the following arguments:
variant_haystack-
The value to search, as a
VARIANTvalue. variant_needle-
The value to look for, as a
VARIANTvalue.
Return type
BOOLEAN
Examples
The following SQL query finds an object that is nested one level down in the haystack.
SELECT variant_contains( {'a': {'b': 42}}::VARIANT, {'b': 42}::VARIANT ) AS result
The query returns the following result.
| result |
|---|
|
The following SQL query shows that an array matches when it holds each value that you look for, in any order, even when it also holds other values.
SELECT variant_contains( {'tags': ['red', 'green', 'blue']}::VARIANT, {'tags': ['blue', 'red']}::VARIANT ) AS result
The query returns the following result.
| result |
|---|
|
The following SQL query shows that variant_contains does not match key names. Use variant_exists for that.
SELECT variant_contains( {'a': 1}::VARIANT, 'a' ) AS by_value, variant_exists({'a': 1}::VARIANT, 'a') AS key_exists
The query returns the following result.
| by_value | key_exists |
|---|---|
|
|
The following SQL query compares a price parsed from JSON, which is a DOUBLE, with a DECIMAL literal and with a literal cast to DOUBLE. Only the DOUBLE literal matches.
SELECT variant_contains( '{"price": 1.5}'::JSON::VARIANT, {'price': 1.5}::VARIANT ) AS decimal_literal, variant_contains( '{"price": 1.5}'::JSON::VARIANT, {'price': 1.5::DOUBLE}::VARIANT ) AS double_literal
The query returns the following result.
| decimal_literal | double_literal |
|---|---|
|
|
Considerations
Numbers match only within the same group of types. Integer and decimal values compare by numeric value, but they never match a FLOAT or DOUBLE value. A JSON number that has a decimal point or an exponent becomes a DOUBLE value. A JSON number that is a whole number and fits in a 64-bit integer becomes an integer value. As a result, the JSON values 100 and 100.0 do not match each other. A SQL literal such as 1.5 is a DECIMAL, so cast it to DOUBLE to match a JSON number that has a decimal point. Leave a whole-number literal such as 100 uncast to match a whole JSON number.
A VARCHAR argument becomes a VARIANT string. For example, variant_contains({'a': 1}::VARIANT, 'a') returns false, because the object has no value equal to the string a.
variant_exists function
Returns true if input_variant is an object that has the key path at its top level, even when the value for that key is null. Returns false when the object does not have the key, or when input_variant is not an object. An empty string as path returns true for any value that is not NULL. If input_variant is NULL, the result is NULL.
Key names are case sensitive. When path is a list of keys, the function returns a list with one BOOLEAN for each key, in the same order.
Syntax
variant_exists(input_variant, path)
Arguments
The variant_exists function takes the following arguments:
input_variant-
The value to check, as a
VARIANTvalue. path-
The key to look for. It must be a constant
VARCHARkey name, or a constantVARCHAR[]list of key names. A list cannot containNULL.
Return type
BOOLEAN, or BOOLEAN[] when path is a list.
Examples
The following SQL query checks whether an object has the key a.
SELECT variant_exists({'a': 1}::VARIANT, 'a') AS result
The query returns the following result.
| result |
|---|
|
The following SQL query checks two keys at once and returns one result for each key.
SELECT variant_exists( {'a': 1, 'b': 2}::VARIANT, ['a', 'c'] ) AS result
The query returns the following result.
| result |
|---|
|
The following SQL query shows that a key in a nested object is not found at the top level, and is found after you extract the nested object.
SELECT variant_exists( {'a': {'b': 1}}::VARIANT, 'b' ) AS top_level, variant_exists( variant_extract({'a': {'b': 1}}::VARIANT, 'a'), 'b' ) AS nested
The query returns the following result.
| top_level | nested |
|---|---|
|
|
The following SQL query passes the same JSON text as a VARCHAR value and as a JSON value. Only the JSON value becomes an object, so only it has the key a.
SELECT variant_exists('{"a": 1}', 'a') AS from_text, variant_exists( '{"a": 1}'::JSON::VARIANT, 'a' ) AS from_json
The query returns the following result.
| from_text | from_json |
|---|---|
|
|
Considerations
Only the top level of the object is checked. To check for a key in a nested object, extract the nested object first, as in variant_exists(variant_extract(.v, 'a'), 'b')
JSON text in a VARCHAR argument becomes a VARIANT string, not an object, so variant_exists returns false for it. Cast the text to JSON first.
variant_extract function
Returns the value for the key field when input_variant is an object, or the element at position index when input_variant is an array. Array positions start at 1. The result is a VARIANT, so you can pass it to another VARIANT function, or nest calls to reach deeper values.
The result is NULL if the key does not exist or the position is past the end of the array. It is also NULL if you pass a key and input_variant is not an object, or if you pass a position and input_variant is not an array.
Syntax
variant_extract(input_variant, field)
variant_extract(input_variant, index)
Arguments
The variant_extract function takes the following arguments:
input_variant-
The value to read from, as a
VARIANTvalue. field-
The name of a key at the top level of the object. It must be a constant
VARCHARvalue. index-
The position in the array, starting at
1. It must be a constantUINTEGERvalue.
Return type
VARIANT
Examples
The following SQL query returns the value of the key b, cast to VARCHAR.
SELECT variant_extract( {'a': 42, 'b': [1, 2, 3]}::VARIANT, 'b' )::VARCHAR AS result
The query returns the following result.
| result |
|---|
|
The following SQL query returns the second element of an array.
SELECT variant_extract( [10, 20, 30]::VARIANT, 2 )::VARCHAR AS result
The query returns the following result.
| result |
|---|
|
The following SQL query nests two calls to return the third element of the array stored under the key a.
SELECT variant_extract( variant_extract( {'a': [10, 20, 30]}::VARIANT, 'a' ), 3 )::VARCHAR AS result
The query returns the following result.
| result |
|---|
|
The following SQL query asks for a key that does not exist, and casts an extracted value to INTEGER to do arithmetic with it.
SELECT variant_extract( {'a': 1}::VARIANT, 'z' ) IS NULL AS missing_key, CAST( variant_extract( {'n': 41}::VARIANT, 'n' ) AS INTEGER ) + 1 AS next_value
The query returns the following result.
| missing_key | next_value |
|---|---|
|
|
Considerations
A query result cannot contain a VARIANT value, so cast the result to VARCHAR or JSON when you select it.
A position of 0 makes the query fail instead of returning NULL.
To use the value as another type, cast it, for example CAST(variant_extract(. The cast fails when the value cannot be converted. Use v, 'n') AS INTEGER)TRY_CAST to get NULL instead.
variant_extract_string function
Returns the value for the key path in input_variant as a VARCHAR. For a string, the function returns the text without quotes. For a number, a boolean, or a date, it returns the text form of the value. For an object or an array, it returns JSON text. An empty string as path returns the whole value as text.
If the key does not exist, its value is null, or input_variant is NULL, the result is NULL. When path is a list of keys, the function returns a list with one VARCHAR for each key, in the same order.
Syntax
variant_extract_string(input_variant, path)
Arguments
The variant_extract_string function takes the following arguments:
input_variant-
The value to read from, as a
VARIANTvalue. path-
The key whose value you want. It must be a constant
VARCHARthat names a key at the top level of the object, or a constantVARCHAR[]list of key names.
Return type
VARCHAR, or VARCHAR[] when path is a list.
Examples
The following SQL query returns the value of the key customer as text.
SELECT variant_extract_string( { 'customer': 'alice', 'amount': 120.50 }::VARIANT, 'customer' ) AS result
The query returns the following result.
| result |
|---|
|
The following SQL query returns an array as JSON text, next to a cast of the same array to VARCHAR.
SELECT variant_extract_string( {'id': 7, 'tags': ['red', 'blue']}::VARIANT, 'tags' ) AS as_text, variant_extract( {'id': 7, 'tags': ['red', 'blue']}::VARIANT, 'tags' )::VARCHAR AS as_cast
The query returns the following result.
| as_text | as_cast |
|---|---|
|
|
The following SQL query passes a list of keys. The key c holds a null value and the key d does not exist, so both results are NULL.
SELECT variant_extract_string( {'a': 42, 'b': true, 'c': NULL}::VARIANT, ['a', 'b', 'c', 'd'] ) AS result
The query returns the following result.
| result |
|---|
|
Considerations
For an object or array, the JSON text that variant_extract_string returns, such as ["red","blue"], differs from a cast of the same value to VARCHAR, which writes [red, blue] without quotes.
variant_group_array function
Aggregates x over the rows of each group and returns a VARIANT array with one element for each row. NULL values are kept as null elements. The function is a macro for CAST(list(. If there are no input rows, the result is x) AS VARIANT)NULL.
Syntax
variant_group_array(x)
Arguments
The variant_group_array function takes the following argument:
x-
The values to collect, of any type.
Return type
VARIANT (an array)
Examples
The following SQL query collects three values into one array and returns the number of elements in it. The order of the elements is not guaranteed, so the query shows the count instead of the array.
SELECT variant_array_length( variant_group_array(x) ) AS element_count FROM (VALUES (1), (4), (7)) AS v(x)
The query returns the following result.
| element_count |
|---|
|
The following SQL query builds one array for each group and casts it to JSON. Each group has one row, so each array has one element. The NULL input of the second group is kept as a null element.
SELECT id, variant_group_array(x)::JSON AS result FROM (VALUES (1, 'a'), (2, NULL)) AS v(id, x) GROUP BY id ORDER BY id
The query returns the following results.
| id | result |
|---|---|
|
|
|
|
The following SQL query builds a VARIANT array with its elements sorted in ascending order. It uses list with ORDER BY and casts the list to VARIANT, because variant_group_array does not accept ORDER BY. It then casts the array to VARCHAR so that the query can return it.
SELECT CAST( list(x ORDER BY x) AS VARIANT )::VARCHAR AS result FROM (VALUES (7), (1), (4)) AS v(x)
The query returns the following result.
| result |
|---|
|
Considerations
A query result cannot contain a VARIANT value, so cast the result to VARCHAR or JSON when you select it.
Because variant_group_array is a macro, you cannot add ORDER BY, DISTINCT, or FILTER to the call. The elements are in the order in which the rows reach the aggregate, which is not guaranteed. To control the order, write CAST(list( instead.x ORDER BY y) AS VARIANT)
variant_group_object function
Aggregates the rows of each group into one VARIANT object with one key-value pair for each row. Each pair takes its key from the key argument and its value from the value argument. A NULL value is kept as a null value in the object. The keys of the result are in sorted order, not in the order of the rows. If there are no input rows, the result is NULL.
Syntax
variant_group_object(key, value)
Arguments
The variant_group_object function takes the following arguments:
key-
The key for each row, as a
VARCHARvalue. It cannot beNULL. value-
The value for each row, as a
VARIANTvalue. Other types are not converted for you, so cast the value, as in.v::VARIANT
Return type
VARIANT (an object)
Examples
The following SQL query builds one object from two rows.
SELECT variant_group_object( k, v::VARIANT )::VARCHAR AS result FROM (VALUES ('a', 1), ('b', 2)) AS pairs(k, v)
The query returns the following result.
| result |
|---|
|
The following SQL query builds one object of attributes for each customer, and casts the result to JSON so that string values keep their quotes.
SELECT customer, variant_group_object( attribute, val::VARIANT )::JSON AS attributes FROM (VALUES ('alice', 'region', 'east'), ('alice', 'amount', '120.50'), ('bob', 'region', 'west') ) AS t(customer, attribute, val) GROUP BY customer ORDER BY customer
The query returns the following results.
| customer | attributes |
|---|---|
|
|
|
|
The following SQL query keeps a NULL value in the object.
SELECT variant_group_object( k, v::VARIANT )::VARCHAR AS result FROM (VALUES ('a', 1), ('b', NULL)) AS pairs(k, v)
The query returns the following result.
| result |
|---|
|
Considerations
A query result cannot contain a VARIANT value, so cast the result to VARCHAR or JSON when you select it.
Each key can appear only once in a group. A duplicate key or a NULL key makes the query fail.
A cast to VARCHAR writes string values without quotes, as in {'region': east}, so you cannot tell the string '120.50' from the number 120.50. Cast to JSON when you need to keep them apart.
variant_keys function
Returns the keys of the object input_variant, or of the object at path, as a list of VARCHAR values in sorted order. Returns an empty list when the value is not an object. If input_variant is NULL, or if path names a key that the object does not have, the result is NULL.
When path is a list of keys, the function returns a list with one list of keys for each path, in the same order.
Syntax
variant_keys(input_variant [, path ])
Arguments
The variant_keys function takes the following arguments:
input_variant-
The value to read the keys from, as a
VARIANTvalue. path-
The key of the object whose keys you want. It must be a constant
VARCHARthat names a key at the top level ofinput_variant, or a constantVARCHAR[]list of key names. The default is the whole value. This argument is optional.
Return type
VARCHAR[], or VARCHAR[][] when path is a list.
Examples
The following SQL query returns the keys of an object.
SELECT variant_keys({'a': 1, 'b': 2}::VARIANT) AS result
The query returns the following result.
| result |
|---|
|
The following SQL query parses JSON text and returns its keys in sorted order.
SELECT variant_keys( '{"region": "east", "amount": 120.5, "id": 1}'::JSON::VARIANT ) AS result
The query returns the following result.
| result |
|---|
|
The following SQL query returns the keys of the object stored under the key a.
SELECT variant_keys( {'a': {'x': 1, 'y': 2}, 'b': 3}::VARIANT, 'a' ) AS result
The query returns the following result.
| result |
|---|
|
The following SQL query passes an array, which has no keys, so the list of keys is empty and its length is 0.
SELECT len(variant_keys([1, 2]::VARIANT)) AS key_count
The query returns the following result.
| key_count |
|---|
|
Considerations
A VARIANT object keeps its keys in sorted order, so the keys do not come back in the order in which you wrote them.
variant_type function
Returns the type of input_variant, or of the value at path, as a VARCHAR. The name has no details, for example OBJECT, ARRAY, DECIMAL, VARCHAR, or INT32. Booleans report BOOL_TRUE or BOOL_FALSE, and a null value inside an object reports VARIANT_NULL. For details such as the length of an array, the keys of an object, or the precision of a decimal, use the variant_typeof function.
If input_variant is NULL, or if path names a key that the object does not have, the result is NULL. When path is a list of keys, the function returns a list with one type name for each key, in the same order.
Syntax
variant_type(input_variant [, path ])
Arguments
The variant_type function takes the following arguments:
input_variant-
The value to inspect, as a
VARIANTvalue. path-
The key of the value whose type you want. It must be a constant
VARCHARthat names a key at the top level ofinput_variant, or a constantVARCHAR[]list of key names. The default is the whole value. This argument is optional.
Return type
VARCHAR, or VARCHAR[] when path is a list.
Examples
The following SQL query returns the type of an array.
SELECT variant_type([1, 2]::VARIANT) AS result
The query returns the following result.
| result |
|---|
|
The following SQL query returns the type of the value stored under the key a.
SELECT variant_type( {'a': 1, 'b': 'x'}::VARIANT, 'a' ) AS result
The query returns the following result.
| result |
|---|
|
The following SQL query passes a list of keys: a boolean, a null value, and a key that does not exist.
SELECT variant_type( {'ok': true, 'note': NULL}::VARIANT, ['ok', 'note', 'missing'] ) AS result
The query returns the following result.
| result |
|---|
|
The following SQL query returns the types of three numbers parsed from JSON text.
SELECT variant_type( '{"n": -1, "m": 1, "f": 1.5}'::JSON::VARIANT, ['n', 'm', 'f'] ) AS result
The query returns the following result.
| result |
|---|
|
Considerations
A number gets its type from where it came from. A number from a SQL value keeps its SQL type, such as INT32 for an INTEGER. A number parsed from JSON text becomes UINT64 when it is a whole number of 0 or more, and INT64 when it is a negative whole number. It becomes DOUBLE when it has a decimal point or an exponent, such as 1.5 or 1e2, or when it is too large for a 64-bit integer.
variant_typeof function
Returns the type of input_variant as a VARCHAR, with details. An array reports its number of elements, as in ARRAY(3). An object reports its keys, as in OBJECT(a, b). A decimal reports its precision and scale, as in DECIMAL(10, 2). Other values report the same name as variant_type.
If input_variant is NULL, the result is the string VARIANT_NULL, not NULL.
Syntax
variant_typeof(input_variant)
Arguments
The variant_typeof function takes the following argument:
input_variant-
The value to inspect, as a
VARIANTvalue.
Return type
VARCHAR
Examples
The following SQL query returns the detailed type of an object.
SELECT variant_typeof( {'a': 42, 'b': [1, 2, 3]}::VARIANT ) AS result
The query returns the following result.
| result |
|---|
|
The following SQL query compares variant_typeof and variant_type for the same array.
SELECT variant_typeof([1, 2, 3]::VARIANT) AS typeof_result, variant_type([1, 2, 3]::VARIANT) AS type_result
The query returns the following result.
| typeof_result | type_result |
|---|---|
|
|
The following SQL query passes NULL. variant_typeof returns VARIANT_NULL, while variant_type returns NULL.
SELECT variant_typeof(NULL::VARIANT) AS typeof_result, variant_type(NULL::VARIANT) IS NULL AS type_is_null
The query returns the following result.
| typeof_result | type_is_null |
|---|---|
|
|
The following SQL query shows that the same number has a different type when it comes from an INTEGER value and when it comes from JSON text.
SELECT variant_typeof(42::VARIANT) AS from_integer, variant_typeof('42'::JSON::VARIANT) AS from_json
The query returns the following result.
| from_integer | from_json |
|---|---|
|
|