I'm trying to delete rows from a table depending on a specific value on a details
column which is of json
type.
The column is expected to have a json
value like this one:
{
"tax": 0,
"note": "",
"items": [
{
"price": "100",
"quantity": "1",
"description": "Test"
}
]
}
The objects inside items
could have a name
entry or not. I'd like to delete those that don't have that entry.
NOTE: All objects inside items have the same entries so all of them will have or will not have the name
entry
CodePudding user response:
You can use a JSON path expression.
delete from the_table
where details::jsonb @@ '$.items[*].name <> ""'
This checks if there is at least one array element where the name is not empty. Note that this wouldn't delete rows with an array element having "name": ""
As you didn't use the recommended jsonb
type (which is the one that supports all the nifty JSON path operators), you need to cast the column to jsonb
.