Forked from mpneuried/postgres_add_json_sub_array_unique.sql
Created
July 27, 2019 12:43
-
-
Save monaxmp/26b76ecc086fdd21da975b95bc8fbcfa to your computer and use it in GitHub Desktop.
Add and remove elements unique to a Postgres jsonb sub key: Short a Set implemetation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 *; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 *; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment