Imagine a table which tracks baseball pitchers like so...
+------------+--------------------+-------+
| id | name | secondary_pitch |
+------------+--------------------+-------+
| 13 | Chris Sale | ['Curveball','Slider'] |
| 14 | Justin Verlander | ['Fastball','Changeup'] |
| 15 | CC Sabathia | ['Fastball','Curveball'] |
| 16 | Sonny Grey | ['Slider'] |
| 17 | Aldoris Chapman | [] |
+------------+--------------------+-------+
Notice the secondary_pitch column has a JSON value. So if a pitcher, like Chapman, has no secondary pitch, it will not return null, instead it returns an empty JSON string ('[]').
How then can I get a count of the number of pitchers who have no secondary pitch?
I can't do...
select count(*) from pitchers where secondary_pitch is null
JSON data has the concept of null and empty arrays and objects.
SELECT * FROM yourTableName WHERE yourSpecificColumnName IS NULL OR yourSpecificColumnName = ' '; The IS NULL constraint can be used whenever the column is empty and the symbol ( ' ') is used when there is empty value.
MySQL provides two operators ( -> and ->> ) to extract data from JSON columns. ->> will get the string value while -> will fetch value without quotes. As you can see ->> returns output as quoted strings, while -> returns values as they are. You can also use these operators in WHERE clause as shown below.
I think you can just use json_length()
:
where json_length(secondary_pitch) = 0
I see this is not answering original question of matching against empty array ([]
) but this has worked for me, matching against empty dictionary ({}
), at mysql 5.7.20-0ubuntu0.16.04.1 - (Ubuntu)
.
I used JSON_OBJECT function but it is very likely the JSON_ARRAY will also work in similar way, creating the 'empty' object when called without arguments.
If I wanted to match against the json column vmkeys
value of {}
(empty dictionary), I used the following query:
SELECT vmkeys FROM `labinstances` WHERE vmkeys=JSON_OBJECT()
To match against the vmkeys
value of NULL, I used this:
SELECT vmkeys FROM `labinstances` WHERE vmkeys is NULL
Hope this helps...
You could use JSON_EXTRACT
to get first value from your column and check for not null
where JSON_EXTRACT(`secondary_pitch`, '$[0]') is not null
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With