How to tabulate a JSON document in MySQL
- 2 minutes read - 388 wordsYou can tabulate a JSON document (retrieve it as a row) in MySQL with the JSON_TABLE
function.
NOTE: more info is available in the MySQL JSON functions documentation page
👉 Want a FREE MySQL database?👈
🦀 Check Aiven’s FREE plans! 🦀
⚡️ Want to optimize your SQL query with AI? ⚡️
Check Aiven SQL Query Optimizer!
⚡️ Want a Fully MySQL optimized Database? ⚡️
🐧 Check Aiven AI database optimizer! Powered by EverSQL 🐧
The dataset
The dataset is the following:
{
"id": 778,
"shop": "Luigis Pizza",
"name": "Edward Olson",
"phoneNumbers":
["(935)503-3765x4154","(935)12345"],
"address": "Unit 9398 Box 2056 DPO AP 24022",
"image": null,
"pizzas": [
{
"pizzaName": "Salami",
"additionalToppings": ["🥓", "🌶️"]
},
{
"pizzaName": "Margherita",
"additionalToppings": ["🍌", "🌶️", "🍍"]
}
]
}
Check out the description of the fields
The following examples use a pizza order dataset with an order having:id
: 778shop
: “Luigis Pizza”name
: “Edward Olson”phoneNumbers
:["(935)503-3765x4154","(935)12345"]address
: “Unit 9398 Box 2056 DPO AP 24022”image
: null- and two pizzas contained in the
pizzas
item:
[
{
"pizzaName": "Salami",
"additionalToppings": ["🥓", "🌶️"]
},
{
"pizzaName": "Margherita",
"additionalToppings": ["🍌", "🌶️", "🍍"]
}
]
If you want to reproduce the examples, check how to recreate the dataset
It can be recreated with the following script:
create table test(id serial primary key, json_data json);
insert into test(json_data) values (
'{
"id": 778,
"shop": "Luigis Pizza",
"name": "Edward Olson",
"phoneNumbers":
["(935)503-3765x4154","(935)12345"],
"address": "Unit 9398 Box 2056 DPO AP 24022",
"image": null,
"pizzas": [
{
"pizzaName": "Salami",
"additionalToppings": ["🥓", "🌶️"]
},
{
"pizzaName": "Margherita",
"additionalToppings": ["🍌", "🌶️", "🍍"]
}
]
}');
Tabulate a JSON document with JSON_TABLE
function
To retrieve one or more JSON documents as columns and rows you can use the JSON_TABLE
function. To retrieve the list of pizzas and their first additional topping from the above as table you can:
select tbl.* from
test,
JSON_TABLE(
json_data,
'$.pizzas[*]'
COLUMNS (
pizzaName VARCHAR(100) PATH '$.pizzaName',
additionalToppings VARCHAR(100) PATH '$.additionalToppings[0]'
)
) tbl;
Where
json_data
is the JSON column'$.pizzas[*]'
generates a row for each pizza in thepizzas
arraypizzaName VARCHAR(100) PATH '$.pizzaName'
retrieves thepizzaName
fieldadditionalToppings VARCHAR(100) PATH '$.additionalToppings[0]'
retrieves the first element ([0]
) of theadditionalToppings
array
Result
+------------+--------------------+
| pizzaName | additionalToppings |
+------------+--------------------+
| Salami | 🥓 |
| Margherita | 🍌 |
+------------+--------------------+
Review all the JSON MySQL use-cases listed in the main page