Return empty array from aggregate in Prostgres

Reading Time: 1 minute

When you want to avoid NULL for the result of JSONB_AGG and instead you want to get an empty array.

Solution

Use COALESCE and '[]'::JSONB.

SELECT
   COALESCE(
      JSONB_AGG(
        JSONB_BUILD_OBJECT(
          'id', role.id,
          'name', role.name
        )
      ) FILTER (WHERE role.id IS NOT NULL),
      '[]'::JSONB
    ) AS "adminRoles",
FROM ...

 



We transform challenges into digital experiences

Get in touch to let us know what you’re looking for. Our policy includes 14 days risk-free!

Free project consultation