0

What would be the right way to identify null value when using JSON_EXTRACT,

I want to use a case statement to identify null values in a json field and if the value is null replace it with another value in this case 1.

CREATE TABLE `Log` (
  `change` json DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=345 DEFAULT CHARSET=utf32 COLLATE=utf32_unicode_ci;


insert into `Log` (`change`) values (JSON_OBJECT('documentNumber', 2));
insert into `Log` (`change`) values (JSON_OBJECT('documentNumber', null));

 select case 
    when isnull(JSON_EXTRACT(`change`, '$.documentNumber')) = 1 then '1'
    else JSON_EXTRACT(`change`, '$.documentNumber') 
    end as 'result'
 from  `Log`;

For this query i am getting result,

result
2
null

but i am expecting,

result
2
1

dbfiddle

1

1 Answer 1

4

JSON 'null' literal is not NULL value.

See this demo:

CREATE TABLE `Log` (
  `change` json DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=345 DEFAULT CHARSET=utf32 COLLATE=utf32_unicode_ci;


insert into `Log` (`change`) values (JSON_OBJECT('documentNumber', 2));
-- JSON 'null'
insert into `Log` (`change`) values (JSON_OBJECT('documentNumber', null));  
-- no key, this will produce regular NULL
insert into `Log` (`change`) values (JSON_OBJECT('documentNumberX', null)); 
 select `change`,
    case 
    when isnull(JSON_EXTRACT(`change`, '$.documentNumber')) = 1 then '1'
    else JSON_EXTRACT(`change`, '$.documentNumber') 
    end as 'result',
    JSON_EXTRACT(`change`, '$.documentNumber') IS NULL test1,
    JSON_EXTRACT(`change`, '$.documentNumber') = CAST('null' AS JSON) test2,
    case when JSON_EXTRACT(`change`, '$.documentNumber') = CAST('null' AS JSON) 
         then '1'
         else JSON_EXTRACT(`change`, '$.documentNumber') 
         end as 'result2'
 from  `Log`;

fiddle

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

1 Comment

Thanks! I will need time to process this

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.