'If the object we made by the group is null, I want to give [ ] instead postgresql

with 
    zakaz as (
      select
        o.*,  
        (select f_name from clients where id = o.client_id) as f_name,
        (select l_name from clients where id = o.client_id) as l_name,
        (select phone from clients where id = o.client_id) as phone,
    
        (select name from item_types where id = o.item_type_id) as item_name,
    
        (select name from trailer_types where id = o.trailer_type_id) as trailer_name,
    
        (select name from cover_types where id = o.cover_type_id) as cover_name,
    
        (select name from cities where id = o.from_city_id) as from_city,
        (select name from cities where id = o.to_city_id) as to_city,
    
        (select name from transport_types where id = o.transport_type_id) as transport_type,
    
        (select  first_name || ' ' || last_name || ' ' || middle_name as name from workers where id = o.logist_id) as logist_name
    
      from orders as o 
        where o.transport_type_id = (select id from transport_types where name = $tt$${transport_type}$tt$)
        ${ where_key ? `and ${where_key} = $v$${where_val}$v$` : ``}
        order by o.created_at
    ),
    zakaz_j_agg as (
      select 
      COALESCE(json_agg(zakaz.*), '[]') as array
      from zakaz
        group by zakaz.status  
    )

    select 
      json_agg(ord.*) as result
    from zakaz_j_agg as ord


Solution 1:[1]

Replace json_agg(ord.*) as result with coalesce(json_agg(ord.*), '[]') as result. The same pattern is used in the zakaz_j_agg CTE.

with 
zakaz as (... your CTE query ...),
zakaz_j_agg as (... your CTE query ...)
select 
   coalesce(json_agg(ord.*), '[]') as result
from zakaz_j_agg as ord;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stefanov.sm