Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why PostgreSQL json_agg() function does not return an empty array?

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?

like image 887
pdagog Avatar asked Jun 20 '16 12:06

pdagog


People also ask

What is Json_agg in PostgreSQL?

Postgres offers us the json_agg() function, which takes an input values and aggregates them as a JSON array.

What is Json_agg?

Aggregate Rows into a JSON Array Using the json_agg() Function. Postgres offers us the json_agg() function, which takes input values and aggregates them as a JSON array.

What is -> in PostgreSQL?

PostgreSQL provides two native operators -> and ->> to help you query JSON data. The operator -> returns JSON object field as JSON. The operator ->> returns JSON object field as text.

How do I check if a JSON key exists in Postgres?

In Postgres, if you select a key that does not exist it will return null. so u can check the existence of a key by checking the null value of that key.


1 Answers

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 
----------
 []
like image 166
Clodoaldo Neto Avatar answered Oct 06 '22 01:10

Clodoaldo Neto