Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a key exists in a Snowflake variant

Is there a function to check if a key exists in a Snowflake variant field?

like image 210
Ollie Glass Avatar asked May 12 '20 15:05

Ollie Glass


People also ask

What does Check_json do in Snowflake?

Checks the validity of a JSON document. If the input string is a valid JSON document or a NULL, the output is NULL (i.e. no error). If the input cannot be translated to a valid JSON value, the output string contains the error message.

What is variant in Snowflake?

In a Snowflake OBJECT, each key is a VARCHAR, and each value is a VARIANT. Because VARIANT can store any other data type, different values (in different key-value pairs) can have different underlying data types. For example, an OBJECT can hold a person's name as a VARCHAR and a person's age as an INTEGER.

How do you parse JSON in Snowflake?

Create a table and add VARCHAR, generic VARIANT, and JSON-compatible VARIANT data. The INSERT statement inserts a VARCHAR value, and the UPDATE statement generates a JSON value that corresponds to that VARCHAR. Although both PARSE_JSON and TO_VARIANT can take a string and return a variant, they are not equivalent.


1 Answers

You can use IS_NULL_VALUE to see if the key exists. If the key does not exist, the result will be NULL. If the key exists, the result will be TRUE if the value is JSON null or FALSE if there's a non-null JSON value:

select  parse_json('{hello: NULL, world: 123}') as V,
        V:hello, 
        V:world,
        IS_NULL_VALUE(v:hello),
        IS_NULL_VALUE(v:world),
        IS_NULL_VALUE(v:goodbye),
        IFF(IS_NULL_VALUE(v:non_existing_key) is null, 'Key does not exist', 'Key exists'),
        IFF(IS_NULL_VALUE(v:hello) is null, 'Key does not exist', 'Key exists'),
        IFF(IS_NULL_VALUE(v:world) is null, 'Key does not exist', 'Key exists')
;
like image 174
Greg Pavlik Avatar answered Sep 30 '22 06:09

Greg Pavlik