To set the column NULL in case the subquery does not find anything, you could use a correlated subquery instead of the join:
UPDATE container c
SET member_containers = (
SELECT string_agg(member_container_id, ',')
FROM inter_container_membership i
WHERE i.owning_container_id = c.id
GROUP BY owning_container_id
);
Often, this kind of query is wrong, because the column shouldn't be nullified if nothing is found. But you seem to want exactly that.
Also, correlated subqueries tend to be slow. Consider to add this left join instead (doing the same):
UPDATE container c
SET member_containers = i.members
FROM container c1
LEFT JOIN (
SELECT owning_container_id
, string_agg(member_container_id, ',') AS members
FROM inter_container_membership
GROUP BY 1
) i ON i.owning_container_id = c1.id
WHERE c.id = c1.id;
Also using string_agg()
instead of array_to_string(array_agg(...))
. Requires Postgres 9.0+.