34

I'm returning a JSON array from a PostgreSQL request with the json_agg function. However, when no row is found, json_agg returns an empty string instead of an empty JSON array [] (square brackets are mandatory if I understand json.org).

For example:

SELECT json_agg(t.*) FROM (SELECT 'test' AS mycol WHERE 1 = 2) AS t ;

returns an empty string, whereas the same command with '1 = 1' returns a valid JSON array (tested with PostgreSQL 9.5).

Any idea?

4
  • where 1=2 will never return any rows and where 1=1 will return all rows. Of course the results are different. Why exactly do you find that surprising? Commented Jun 20, 2016 at 12:46
  • 6
    As explained in the question, IMHO json_agg should return a valid JSON array (i.e. []) when no row is selected. Instead, json_aggreturns an empty string. Commented Jun 20, 2016 at 12:56
  • 6
    It returns NULL not an empty string. And this behavior is documented: "It should be noted that except for count, these functions return a null value when no rows are selected". If you don't want that, use coalesce() Commented Jun 20, 2016 at 13:00
  • Thanks for the pointer to the doc! Commented Jun 20, 2016 at 13:04

1 Answer 1

49

json_agg returns null from an empty set:

select json_agg(t.*) is null
from (select 'test' as mycol where 1 = 2) t ;
 ?column? 
----------
 t

If you want an empty json array coalesce it:

select coalesce(json_agg(t.*), '[]'::json)
from (select 'test' as mycol where 1 = 2) t ;
 coalesce 
----------
 []
1
  • Works fine on 9.6 Commented Dec 28, 2017 at 11:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.