CodexBloom - Programming Q&A Platform

MySQL: Difficulty Filtering Nested JSON Data with Complex Conditions in MySQL 8.0

πŸ‘€ Views: 226 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-15
mysql json sql-queries sql

I'm updating my dependencies and I'm updating my dependencies and After trying multiple solutions online, I still can't figure this out... I'm working on a MySQL 8.0 application where I need to filter records based on specific conditions applied to nested JSON data. I have a table named `orders` that contains a column `order_details`, which is a JSON object. The structure of `order_details` looks something like this: ```json { "items": [ {"product_id": 1, "quantity": 2}, {"product_id": 2, "quantity": 1} ], "customer": {"id": 1001, "name": "John Doe"} } ``` I want to retrieve all orders where the `customer.id` is `1001` and at least one item has a `quantity` greater than `1`. I thought I could do this with a `JSON_CONTAINS` call, but I'm struggling to get the syntax right. Here’s what I tried: ```sql SELECT * FROM orders WHERE JSON_UNQUOTE(JSON_EXTRACT(order_details, "$.customer.id")) = '1001' AND JSON_CONTAINS(order_details, '{"quantity": 2}', "$.items"); ``` However, this results in an empty set, even though there are matching records. The behavior I get is `No rows returned` which is unexpected as I know there are orders meeting those criteria. I also tried changing the `JSON_CONTAINS` condition to `JSON_SEARCH`, but that didn't yield any results either. ```sql SELECT * FROM orders WHERE JSON_UNQUOTE(JSON_EXTRACT(order_details, "$.customer.id")) = '1001' AND JSON_SEARCH(order_details, 'one', '2', NULL, "$.items[*].quantity") IS NOT NULL; ``` This also returned an empty set. I feel like I'm missing something when it comes to querying nested JSON arrays. Can someone guide to understand how to properly filter based on nested JSON structures in MySQL? The documentation is a bit overwhelming, and I need to seem to find a clear example for this specific use case. My development environment is Windows. Any help would be greatly appreciated! I'm on Ubuntu 20.04 using the latest version of Sql. Any pointers in the right direction? Has anyone else encountered this?