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?
The outer
COALESCEdoes not do what you want sincejson_agg()never returnsnull, unless no input row qualifies. AndCOALESCEonly kicks in fornullinput - notnull/falselike you put it! (An array containing a singlenullvalue as array element is not the same asnull!)Use an aggregate
FILTERclause instead:Now,
COALESCEcan make sense, since you can get result rows, but the addedFILTERclause can make the result ofjson_agg()null.Depending on your undisclosed query, you might instead add an outer
WHEREclause:In this case, there is no point in adding an outer
COALESCE, since you would get no row if the addedWHEREclause filters all input rows.