Skip to content
Advertisement

Conditional update with jsonb_set()

I have a table in a Postgres 11.3 database with a jsonb column.

Trying to update all objects inside a nested array name "iProps".

If the path {iProps -> value -> rules -> ao -> sc} is an object, then the path should be updated from an object to a string with the value {iProps -> value -> rules -> ao -> sc -> name}

If the path {iProps -> value -> rules -> ao -> sc} is not present, then the object should be left unchanged.

Test setup with query: Fiddle link

Desired result:

I have modified the query and linked in the fiddle. Can someone take a look to see if it’s right?

Advertisement

Answer

A plain CASE should make the difference.

db<>fiddle here (Postgres 11!)

To also meet the second filter you added in the update (must be an object), check with jsonb_typeof().

The query in your fiddle seems needlessly complicated (tl;dr). Also, it does not preserve original order of array elements. If that’s in fact irrelevant, omit WITH ORDINALITY and ORDER BY and simplify further:

db<>fiddle here

This typically still preserves the order of array elements (unlike your original). There’s just no guarantee with two levels of aggregation.

See:

More advice in my answer to your earlier related question:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement