My table:
CREATE TABLE items (
id BIGINT PRIMARY KEY NOT NULL,
name VARCHAR,
images json
);
images format:
[
{
"id": "owner",
"full": "<url>",
"thumb": "<url>"
},
{
"id": "note_0",
"full": "<url>",
"thumb": "<url>"
},
{
"id": "note_1",
"full": "<url>",
"thumb": "<url>"
},
{
"id": "note_2",
"full": "<url>",
"thumb": "<url>"
}
]
I need something like this:
UPDATE items SET images = delete(images, 'note_1');
Best Answer
To remove all elements from the column
images
(holding a json array) where'id'
is'note_1'
:pg 9.3
SQL Fiddle.
Explain
json_array_elements()
in a subquery using an implicitJOIN LATERAL
for the set-returning function. Details:WHERE
condition usingjson_array_length()
to exclude unaffected rows - so you don't update each and every row of the table, which would be expensive (and wide-spread) nonsense.pg 9.4
This gets much easier with
jsonb
and additionaljsonb
operators.Eliminates unaffected rows at the start, which is much faster. Plus, there is extensive native index support for
jsonb
, too, now.Here are some example, benchmarks and comparison of new features to old json and MongoDB, plus outlook to jsquery by (some of) their main authors, Alexander Korotkov, Oleg Bartunov andTeodor Sigaevat PGCon 2014: