How to write a basic MySQL query that has a WHERE on a property within a JSON data-type field? I don't see basic where clause q for json fields on SO.
Something like this, but of course these dont work:
SELECT * from my_table where meta_data->name = 'bob'; SELECT * from my_table where meta_data[name] IS NOT NULL;
Key takeaway for extracting data from a JSON field in MySQL: Use $. key to extract the value of a key from a JSON object. Use $[index] to extract the value of an element from a JSON array.
To query JSON data, you can use standard T-SQL. If you must create a query or report on JSON data, you can easily convert JSON data to rows and columns by calling the OPENJSON rowset function. For more information, see Convert JSON Data to Rows and Columns with OPENJSON (SQL Server).
In MySQL, the only way to index a JSON path expression is to add a virtual column that mirrors the path expression in question and build an index on the virtual column. As you can see, the title column is mapped to the $. title path expression on the properties JSON column.
The drawback? If your JSON has multiple fields with the same key, only one of them, the last one, will be retained. The other drawback is that MySQL doesn't support indexing JSON columns, which means that searching through your JSON documents could result in a full table scan.
Some examples of how to query a json data type field:
SELECT * FROM users WHERE JSON_EXTRACT(meta_data, "$.first_name") = 'bob'; SELECT * FROM users WHERE JSON_EXTRACT(meta_data, "$.age") IS NOT NULL; SELECT * FROM users WHERE JSON_EXTRACT(meta_data, "$.accepted_policy") = true;
With mysql 5.7.9 +
You can also just do this (shortcut for JSON_EXTRACT):
SELECT * FROM users WHERE meta_data->"$.first_name" = 'bob'
You might notice your json data results are "quoted". You could use JSON_UNQUOTE, or you could use this, which is a shortcut of JSON_EXTRACT & JSON_UNQUOTE:
SELECT meta_data->>"$.first_name" FROM users WHERE meta_data->>"$.first_name" IS NOT NULL
And to select data from within sub objects:
SELECT meta_data->>"$.address.tel" FROM users WHERE meta_data->>"$.address.street" = "123 Main St"
docs: https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html
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