patternsqlMinor
Pushing or appending to JSON array in PostgreSQL 9.4
Viewed 0 times
postgresqlarrayappendingjsonpushing
Problem
I have table where one of the fields is JSON array. I need to append received JSON array into that field without overriding existing values.
Something like that:
Something like that:
CREATE OR REPLACE FUNCTION add_array(
array_received json[])
RETURNS void AS
$BODY$
update table set _array_field = _array_field | array_received ...;
$BODY$
LANGUAGE plpgsql VOLATILE;Solution
In pre-9.5 you can use
You can also write this using the
json_array_elements, and array_to_json(array_agg()), like this.SELECT array_to_json(array_agg(x))
FROM (
SELECT jsonb_array_elements('[1,2,3]'::jsonb)
UNION ALL SELECT '4'::jsonb
) AS t(x);You can also write this using the
ARRAY constructor like this..SELECT array_to_json(ARRAY(
SELECT jsonb_array_elements('[1,2,3]'::jsonb)
UNION ALL SELECT '4'::jsonb
));Code Snippets
SELECT array_to_json(array_agg(x))
FROM (
SELECT jsonb_array_elements('[1,2,3]'::jsonb)
UNION ALL SELECT '4'::jsonb
) AS t(x);SELECT array_to_json(ARRAY(
SELECT jsonb_array_elements('[1,2,3]'::jsonb)
UNION ALL SELECT '4'::jsonb
));Context
StackExchange Database Administrators Q#102906, answer score: 3
Revisions (0)
No revisions yet.