Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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?

share|improve this question
    
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? – a_horse_with_no_name Jun 20 at 12:46
    
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. – pdagog Jun 20 at 12:56
1  
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() – a_horse_with_no_name Jun 20 at 13:00
    
Thanks for the pointer to the doc! – pdagog Jun 20 at 13:04
up vote 1 down vote accepted

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 
----------
 []
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.