Skip to content

Instantly share code, notes, and snippets.

@mpneuried
Last active April 5, 2023 11:35
  • Star 7 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Add and remove elements unique to a Postgres jsonb sub key: Short a Set implemetation
UPDATE public.mytable SET
jsonfieldname = jsonb_set( jsonfieldname, '{json_obj_key}', array_to_json(
ARRAY(
SELECT DISTINCT( UNNEST( ARRAY(
SELECT json_array_elements_text( COALESCE( jsonfieldname::json->'json_obj_key', '[]' ) )
) || ARRAY['Element to add'] ) )
)
)::jsonb )
WHERE id = 23
RETURNING *;
UPDATE public.mytable SET
jsonfieldname = jsonb_set( jsonfieldname, '{json_obj_key}', array_to_json(
array_remove( ARRAY(
SELECT json_array_elements_text( COALESCE( jsonfieldname::json->'json_obj_key', '[]' ) )
), 'Element to remove' )
)::jsonb )
WHERE id = 23
RETURNING *;
@ilaipi
Copy link

ilaipi commented Nov 2, 2021

Thanks, very useful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment