---
title: "Merge JSON array values across multiple rows in MySQL"  
description: "Merge JSON array values across multiple rows in MySQL"  
author: "Sandra Emily"  
published: 2023-07-27  
updated: 2023-08-07  
canonical: https://www.mindstick.com/forum/159317/merge-json-array-values-across-multiple-rows-in-mysql  
category: "mysql"  
tags: ["database", "json", "mysql"]  
reading_time: 1 minute  

---

# Merge JSON array values across multiple rows in MySQL

[Merge](https://www.mindstick.com/startup/15/how-growthpal-helps-companies-make-the-right) [JSON array](https://www.mindstick.com/forum/12870/how-to-parse-json-array-using-newtonsoft) [values](https://www.mindstick.com/forum/327/sum-textbox-values) across [multiple rows](https://www.mindstick.com/forum/160908/how-to-concatenate-text-from-multiple-rows-into-a-single-text-string-in-sql-server) in [MySQL](https://www.mindstick.com/articles/12156/what-is-mysql)

## Replies

### Reply by Aryan Kumar

Here is a SQL query that you can use to merge [JSON](https://www.mindstick.com/forum/34446/convert-json-string-to-object) [array](https://www.mindstick.com/articles/335/jagged-array-in-c-sharp-dot-net) values across [multiple](https://www.mindstick.com/blog/12797/iowa-is-expected-to-see-heavy-growth-in-multiple-sectors) rows in MySQL:

SQL

```plaintext
SELECT
  id,
  name,
  json_array_agg(array_agg(value ORDER BY key)) AS values
FROM
  table
GROUP BY
  id,
  name;
```

This query will first group the rows by the `id` and `name` columns. It will then aggregate the `value` column into a JSON array. The `array_agg()` function will sort the values in the array by the `key` column. The `json_array_agg()` function will then create a JSON array from the aggregated values.

The following is an example of the output of this query:

```plaintext
id | name | values
-- | -- | --
1 | John Doe | [{"key": "a", "value": "1"}, {"key": "b", "value": "2"}]
2 | Jane Doe | [{"key": "a", "value": "3"}, {"key": "b", "value": "4"}]
```

As you can see, the query has merged the `value` columns from the two rows into a single JSON array. The array is sorted by the `key` column.


---

Original Source: https://www.mindstick.com/forum/159317/merge-json-array-values-across-multiple-rows-in-mysql

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
