JSON Aggregation
JSON_ARRAYAGG() and JSON_OBJECTAGG() aggregate rows into JSON arrays or objects — useful for building API responses in SQL.
JSON_ARRAYAGG() and JSON_OBJECTAGG() aggregate rows into JSON arrays or objects — useful for building API responses in SQL.
-- 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;
JSON_ARRAYAGG respects ORDER BY inside the function in MySQL 8.0+.