2

I have this query

select json_length(data->"$.row.*.code") as count from hospitalization_history where id = 238

The result in count is 8, because data->"$.row.*.code" returns ["J00.00", "V01.00", "G00.00", null, null, null, null, null];

How can I a get number of not null values in json array?

Andriy Lozynskiy
  • 2,444
  • 2
  • 17
  • 35
  • 1
    Parse your array to the rowset then count non-`null` values. See https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=dd0a37bb25d526f029a7a82c6a1fe0cc – Akina Apr 22 '21 at 11:50
  • @Akina I posted your comment as a community wiki. – Scratte Apr 22 '21 at 12:48
  • @Scratte I am not sure that my code is applicable to OP's server (its version may be too old) - in this case the solution must be altered. – Akina Apr 22 '21 at 13:04
  • @Akina I see. I hadn't thought of that. If they reply that it's not working for them, or if you'd rather post an Answer yourself. I'll delete it. I just came upon your comment and played with it and learned something new myself :) – Scratte Apr 22 '21 at 13:07
  • @Akina seems like your solution works for MySQL 8.0.24+. I have 8.0.16 and get 8 as a result – Andriy Lozynskiy Apr 22 '21 at 21:53
  • *seems like your solution works for MySQL 8.0.24+.* No, JSON_TABLE() which is the most "young" option in the query was introduced since 8.0.4. So it **must** work in your 8.0.16. – Akina Apr 23 '21 at 04:37

2 Answers2

2

Finally, found this solution for MySQL 8+:

SELECT JSON_LENGTH(
    JSON_SEARCH('["J00.00", "V01.00", "G00.00", null, null, null]','all','%')
) AS count;

Try it here

Andriy Lozynskiy
  • 2,444
  • 2
  • 17
  • 35
1

A comment from Akina says to

Parse your array to the rowset then count non-null values. See https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=dd0a37bb25d526f029a7a82c6a1fe0cc

The SQL in the fiddle is:

WITH cte AS (SELECT '["J00.00", "V01.00", "G00.00", null, null, null, null, null]' jstr)
SELECT COUNT(val)
FROM cte
JOIN JSON_TABLE(cte.jstr,
                '$[*]' COLUMNS (val VARCHAR(255) PATH '$')) jtable

Results in

COUNT(val)
3
Scratte
  • 3,056
  • 6
  • 19
  • 26