Still learning SQL/PostgreSQL. I am struggling to figure out how to stop returning an array with a null value as [null]
and instead just return an empty array.
COALESCE(
json_agg(
CASE
WHEN socials.id IS NULL THEN NULL
ELSE json_build_object('id', socials.id, 'name', socials.social_id, 'url', socials.url)
END
), '[]'
) AS socials
What am I missing or doing wrong? From what I understood, COALESCE
is used to basically replace when the return value is null
/false
. Am I wrong in thinking this way? Also what might be the issue with my SQL query?
2
Answers
Add a
FILTER
clause:The outer
COALESCE
does not do what you want sincejson_agg()
never returnsnull
, unless no input row qualifies. AndCOALESCE
only kicks in fornull
input – notnull
/false
like you put it! (An array containing a singlenull
value as array element is not the same asnull
!)Use an aggregate
FILTER
clause instead:Now,
COALESCE
can make sense, since you can get result rows, but the addedFILTER
clause can make the result ofjson_agg()
null
.Depending on your undisclosed query, you might instead add an outer
WHERE
clause:In this case, there is no point in adding an outer
COALESCE
, since you would get no row if the addedWHERE
clause filters all input rows.