SyntaxStudy
Sign Up
MySQL Aggregating Data into JSON
MySQL Intermediate 4 min read

Aggregating Data into JSON

JSON Aggregation

JSON_ARRAYAGG() and JSON_OBJECTAGG() aggregate rows into JSON arrays or objects — useful for building API responses in SQL.

Example
-- Build a JSON array of product names per category
SELECT c.name,
       JSON_ARRAYAGG(p.name) AS products
FROM categories c
JOIN products p ON p.category_id = c.id
GROUP BY c.id, c.name;

-- JSON object: id => name
SELECT JSON_OBJECTAGG(id, name) FROM products;
Pro Tip

JSON_ARRAYAGG respects ORDER BY inside the function in MySQL 8.0+.