Storing data in JSON is useful, but you also need to be able to query individual fields within it. In this step, you will use the JSON_EXTRACT function and JSON_UNQUOTE to pull specific values from the product_details column.
The JSON_EXTRACT function allows you to select a value from a JSON document using a path expression. The path starts with $ to represent the document root.
Let's extract the brand of the laptop.
SELECT JSON_EXTRACT(product_details, '$.brand') AS brand FROM products WHERE product_name = 'Laptop';
This query returns the brand, but notice that the result is a JSON string, which includes double quotes.
+--------+
| brand |
+--------+
| "Dell" |
+--------+
1 row in set (0.00 sec)
For a cleaner result, you can use JSON_UNQUOTE combined with JSON_EXTRACT. This combination extracts the value and removes the quotes, returning a standard string.
SELECT JSON_UNQUOTE(JSON_EXTRACT(product_details, '$.brand')) AS brand FROM products WHERE product_name = 'Laptop';
The output is now the plain text Dell.
+-------+
| brand |
+-------+
| Dell |
+-------+
1 row in set (0.00 sec)
You can also use path expressions to access values in nested objects. To get the processor from the specs object, use the path $.specs.processor.
SELECT JSON_UNQUOTE(JSON_EXTRACT(product_details, '$.specs.processor')) AS processor FROM products WHERE product_name = 'Laptop';
This will correctly extract the nested value.
+-----------------+
| processor |
+-----------------+
| Intel Core i7 |
+-----------------+
1 row in set (0.00 sec)
These functions are also useful in WHERE clauses for filtering rows. To find all products with a price over 1000, you must CAST the extracted JSON value to a numeric type for comparison.
SELECT product_name, JSON_UNQUOTE(JSON_EXTRACT(product_details, '$.price')) AS price FROM products WHERE CAST(JSON_UNQUOTE(JSON_EXTRACT(product_details, '$.price')) AS SIGNED) > 1000;
This query demonstrates how to filter records based on a numeric value inside a JSON field.
+--------------+-------+
| product_name | price |
+--------------+-------+
| Laptop | 1200 |
+--------------+-------+
1 row in set (0.00 sec)
You now know how to extract and filter data based on JSON fields.