SQL JSON_OBJECTAGG function
Aggregates two columns of a group into one JSON object keyed by the first.
- Категория
- Aggregates
- Returns
json- In this category
- 18 of 52
Синтаксис
JSON_OBJECTAGG(key, value) | JSON_OBJECTAGG(KEY key VALUE value) | JSON_OBJECTAGG(key : value)
Поддержка движка
| Движок | Support | Заметки |
|---|---|---|
| SQL Server | Да | SQL Server 2025 / Azure SQL, colon syntax: JSON_OBJECTAGG(k : v) |
| PostgreSQL | Да | PostgreSQL 16+ as JSON_OBJECTAGG(k VALUE v); json_object_agg and jsonb_object_agg on every version |
| MySQL | Да | comma syntax: JSON_OBJECTAGG(k, v) |
| SQLite | Not built in | use json_group_object |
| Oracle | Да | JSON_OBJECTAGG(KEY k VALUE v); the comma form also parses |
Примеры
MySQL
SELECT JSON_OBJECTAGG(id, name) FROM employees;
PostgreSQL
SELECT jsonb_object_agg(code, label) FROM status_codes;
SQL Server
SELECT JSON_OBJECTAGG(code : label) FROM status_codes;
SQLite
SELECT json_group_object(code, label) FROM status_codes;
Полезно знать
- The argument syntax differs per engine: MySQL takes a comma, PostgreSQL 16+ wants k VALUE v, SQL Server 2025 uses k : v, and Oracle accepts KEY k VALUE v or the comma.
- Duplicate keys: MySQL and jsonb_object_agg keep the last value; PostgreSQL's json_object_agg, SQL Server, Oracle and SQLite emit both pairs, producing an object most JSON parsers will read as last-wins.
- NULL keys: PostgreSQL, MySQL, SQL Server and Oracle raise an error; SQLite silently drops the pair. NULL values are fine and become JSON null.
- JSON keys are always strings, so numeric keys come out quoted.
Questions about JSON_OBJECTAGG
What happens with duplicate keys?
MySQL and jsonb_object_agg keep the last value per key. PostgreSQL's json_object_agg, SQL Server, Oracle and SQLite write every pair, which leaves a duplicate-key object that parsers resolve inconsistently.
What is JSON_OBJECTAGG in PostgreSQL?
PostgreSQL 16+ has JSON_OBJECTAGG(k VALUE v). On older versions use json_object_agg(k, v) or jsonb_object_agg(k, v).
How do I build an array of objects per group?
Combine them: JSON_ARRAYAGG over JSON_OBJECT is one way, or PostgreSQL's jsonb_agg(to_jsonb(row)).
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.