New versions: Dev (3.14)

JSON_OBJECTAGG

Applies to ✅ Open Source Edition   ✅ Express Edition   ✅ Professional Edition   ✅ Enterprise Edition

A data set can be aggregated into a org.jooq.JSON or org.jooq.JSONB object using JSON_OBJECTAGG

SELECT json_objectagg(
  CAST(author.id AS varchar(100)),
  first_name
)
FROM author
 
create.select(jsonObjectAgg(
         cast(AUTHOR.ID, VARCHAR(100)),
         AUTHOR.FIRST_NAME
      ))
      .from(AUTHOR)
      .fetch();

The result would look like this:

+----------------------------+
| json_objectagg             |
+----------------------------+
| {"1":"George","2":"Paulo"} |
+----------------------------+

NULL handling

Some dialects support the SQL standard NULL ON NULL and ABSENT ON NULL syntax, which allows for including / excluding NULL values from aggregation. By default, SQL aggregate functions always exclude NULL values, but in the context of JSON data types, NULL may have a different significance:

SELECT 
  json_objectagg(
    CAST(author.id AS varchar(100)),
    nullif(first_name, 'George')
    NULL ON NULL
  ) AS c1,
  json_objectagg(
    CAST(author.id AS varchar(100)),
    nullif(first_name, 'George')
    ABSENT ON NULL
  ) AS c2
FROM author
create.select(
         jsonObjectAgg(
           cast(AUTHOR.ID, VARCHAR(100)),
           nullif(AUTHOR.FIRST_NAME, "George")
         ).nullOnNull().as("c1"),
         jsonObjectAgg(
           cast(AUTHOR.ID, VARCHAR(100)),
           nullif(AUTHOR.FIRST_NAME, "George")
         ).absentOnNull().as("c2")
       )
      .from(AUTHOR)
      .fetch();

The result would look like this:

+------------------------+---------------+
| C1                     | C2            |
+------------------------+---------------+
| {"1":null,"2":"Paulo"} | {"2":"Paulo"} |
+------------------------+---------------+

The effect is similar to that of the FILTER clause.

Dialect support

This example using jOOQ:

jsonObjectAgg(AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME)

Translates to the following dialect specific expressions:

-- AURORA_POSTGRES, POSTGRES
json_object_agg(AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME)

-- COCKROACHDB
(('{' || string_agg(('"' || replace(AUTHOR.FIRST_NAME, '"', '\"') || '":' || coalesce(CAST(json_extract_path(json_build_object('x', AUTHOR.LAST_NAME), 'x') AS string), 'null')), ',') || '}'))

-- DB2
(('{' || listagg(('"' || replace(AUTHOR.FIRST_NAME, '"', '\"') || '":' || CAST(coalesce(json_value(JSON_OBJECT(KEY 'x' VALUE AUTHOR.LAST_NAME), '$.x'), 'null') AS varchar(32672))), ',') || '}'))

-- H2, ORACLE
json_objectagg(KEY AUTHOR.FIRST_NAME VALUE AUTHOR.LAST_NAME)

-- MARIADB, MYSQL
json_objectagg(AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME)

-- ACCESS, ASE, AURORA_MYSQL, CUBRID, DERBY, FIREBIRD, HANA, HSQLDB, INFORMIX, INGRES, MEMSQL, REDSHIFT, SQLDATAWAREHOUSE, 
-- SQLITE, SQLSERVER, SYBASE, TERADATA, VERTICA
/* UNSUPPORTED */

(These are currently generated with jOOQ 3.14, see #10141)

The jOOQ Logo