Tutorialspoint

Is there any way to use values from a JSON object in a MySQL Select statement?


1 Answer
Kumar Varma

Yes, you can use json_extract(). Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Data json
   -> );
Query OK, 0 rows affected (0.63 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('{"Name": "John", "CountryName": "US"}');
Query OK, 1 row affected (0.33 sec)

mysql> insert into DemoTable values('{"Name": "Chris", "CountryName": "UK"}');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+----------------------------------------+
| Data                                   |
+----------------------------------------+
| {"Name": "John", "CountryName": "US"}  |
| {"Name": "Chris", "CountryName": "UK"} |
+----------------------------------------+
2 rows in set (0.01 sec)

Following is the query to use values from a JSON object in a MySQL Select statement −

mysql> SELECT *from DemoTable WHERE json_extract(Data, '$.CountryName') like '%US%';

Output

+---------------------------------------+
| Data                                  |
+---------------------------------------+
| {"Name": "John", "CountryName": "US"} |
+---------------------------------------+
1 row in set (0.00 sec)

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.