Lets say i have json column as JSON_COLUMN in which i am storing the data in below format
Table structure: (2 columns only)
ID - Autoincrement
JSON_COLUMN - Varchar2(1000)
Sample Data:
ID : 1
JSON_COLUMN :
[
{
"Name":"Number",
"Id":"PhoneNumber",
"Value":"+393123456789"
},
{
"Name":"Name",
"Id":"FirstName",
"Value":"John"
},
{
"Name":"City",
"Id":"CityID",
"Value":"NYC"
}
]
Now i want update query of mariadb which should replace value of City from NYC to CALI
update tablename set JSON_COLUMN = ???? Not sure what to keep here where id = 1;
2
Answers
mysql and mariadb haven’t the datatype varchar2 but oracle has.
Using a simple
REPLACE
can help you.IF the term NYC is only one in your json, this is enough
{
"Name":"Number",
"Id":"PhoneNumber",
"Value":"+393123456789"
},
{
"Name":"Name",
"Id":"FirstName",
"Value":"John"
},
{
"Name":"City",
"Id":"CityID",
"Value":"CALI"
}
]
fiddle
Here’s a solution that updates only the ‘NYC’ corresponding to the key ‘Value’ in an array.
This works in MySQL 8.0 or later, but not in MariaDB, because MariaDB doesn’t support a common table expression before
update
.Demo: https://dbfiddle.uk/tN9Q9-Od
Here’s a solution for MariaDB 10.6 or later (won’t work with older versions):
Demo: https://dbfiddle.uk/fKHp8BmZ