1

I wanted to check my column. If there was a 'null' string, I wanted to replace it with a NULL value. This works but is there a better way to do it? Such that I don't have to repeat the same thing twice JSON_DATA :"ContactPerson"::STRING

SELECT 
  IFF(JSON_DATA :"ContactPerson"::STRING = 'null',NULL, JSON_DATA :"ContactPerson"::STRING) AS "ContactPerson",
  FROM TEST_TABLE  

I want to use REPLACE or REGEX_REPLACE instead.

2
  • 1
    Seems a very reasonable approach to me. Not sure why repeating the column reference is considered less desirable. Commented Feb 21, 2022 at 15:59
  • I agree with JNevill. An "better" solution could be to hunt down the person who thought it was a good idea to use the text 'null' as a value and make them fix the problem. Commented Feb 21, 2022 at 16:03

1 Answer 1

1

Using IS_NULL_VALUE could be a bit shorter:

SELECT
  IFF(IS_NULL_VALUE(JSON_DATA:"ContactPerson"), NULL, 
       JSON_DATA :"ContactPerson"::STRING)
FROM TEST_TABLE;

or NULLIF:

Returns NULL if expr1 is equal to expr2, otherwise returns expr1.

SELECT NULIF(JSON_DATA :"ContactPerson"::STRING, 'null')
FROM TEST_TABLE;

Regarding comments:

Still, how would regex_replace be used? REGEXP_REPLACE( , [ , , , , ] )what would the subject be here?

REGEXP_REPLACE(JSON_DATA :"Business_Type"::STRING, 'null', NULL) AS "BS2",but this would give me NULL if "null" doesn't exist in the original value

CREATE FUNCTION:

CALLED ON NULL INPUT

Specifies the behavior of the UDF when called with null inputs. In contrast to system-defined functions, which always return null when any input is null, UDFs can handle null inputs, returning non-null values even when an input is null

and REPLACE function has this behaviour described explicitly"

If any of the arguments is a NULL, the result is also a NULL.

Sign up to request clarification or add additional context in comments.

4 Comments

Still, how would regex_replace be used? REGEXP_REPLACE( <subject> , <pattern> [ , <replacement> , <position> , <occurrence> , <parameters> ] )what would the subject be here?
@x89 First argument for REGEXP_REPLACE should be text so JSON_DATA :"ContactPerson"::STRING
REGEXP_REPLACE(JSON_DATA :"Business_Type"::STRING, 'null', NULL) AS "BS2",but this would give me NULL if "null" doesn't exist in the original value.
@x89 Please see my update why you cannot use REGEXP_REPLACE that way

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.