MySQL - JSON_OBJECTAGG() Function



The MySQL JSON_OBJECTAGG() function accepts the names of two columns of a table as arguments and returns a JSON object literal as a result which have the entities of first argument as keys and the entities of the second argument as values.

JSON object literals are stored in the form of key-value pairs and are enclosed by curly braces {}. Keys must be strings, and values must be a valid JSON data type: string, number, object, array, boolean, NULL. Each key-value pair is separated by a comma.

If the specified columns have no rows this function returns NULL.

Syntax

Following is the syntax of MySQL JSON_OBJECTAGG() function −

JSON_OBJECTAGG(key, value);

Parameters

This method accepts two parameters. The same is described below −

  • key: The expression whose distinct values will be used as keys in the resulting JSON object.

  • value: The expression whose values will be associated with the corresponding keys in the resulting JSON object.

Return value

This function aggregates key-value pairs into a JSON object.

Example

Following is an example demonstrating the usage of this function. Assume we have created a table with name CUSTOMERS using CREATE statement as shown below −

CREATE TABLE CUSTOMERS (
   ID INT AUTO_INCREMENT,
   NAME VARCHAR(20) NOT NULL,
   AGE INT NOT NULL,
   ADDRESS CHAR (25),
   SALARY DECIMAL (18, 2),
   PRIMARY KEY (ID)
);

The below query inserts 7 records into the above created table −

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES 
(1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ),
(2, 'Khilan', 25, 'Delhi', 1500.00 ),
(3, 'Kaushik', 23, 'Kota', 2000.00 ),
(4, 'Chaitali', 25, 'Mumbai', 6500.00 ),
(5, 'Hardik', 27, 'Bhopal', 8500.00 ),
(6, 'Komal', 22, 'Hyderabad', 4500.00 ),
(7, 'Muffy', 24, 'Indore', 10000.00 );

To verify whether the records are inserted, execute the following query −

Select * From CUSTOMERS;

Following is the CUSTOMERS table −

ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

The below query creates a single JSON object with key-value pairs, using the names of customers as keys and their salaries as values −

SELECT JSON_OBJECTAGG(NAME, SALARY) as Salaries from CUSTOMERS;

This will produce the following result −

Salaries
{ "Komal": 4500.00, "Muffy": 10000.00, "Hardik": 8500.00, "Khilan": 1500.00,
"Ramesh": 2000.00, "Kaushik": 2000.00, "Chaitali": 6500.00 }

Following query groups the salaries of the customers, based on the AGE −

SELECT AGE, JSON_OBJECTAGG(NAME, SALARY) as Salaries 
FROM CUSTOMERS 
GROUP BY AGE;

This will produce the following result −

AGE Salaries
22 {"Komal": 4500.00}
23 {"Kaushik": 2000.00}
24 {"Muffy": 10000.00}
25 {"Khilan": 1500.00, "Chaitali": 6500.00}
27 {"Hardik": 8500.00}
32 {"Ramesh": 2000.00}
Advertisements