Categories:

Aggregate Functions (Semi-structured Data) , Window Functions , Semi-structured Data Functions (Array/Object)

OBJECT_AGG

Returns one OBJECT per group. For each (key, value) input pair, where key must be a VARCHAR and value must be a VARIANT, the resulting OBJECT contains a key:value field.

Aliases:

OBJECTAGG

Syntax

OBJECT_AGG(<key>, <value>)

Usage Notes

  • Input tuples with NULL key and/or value are ignored.

  • Duplicate keys within a group result in an error.

  • The DISTINCT keyword is supported, but it only filters out duplicate rows where both key and value are equal.

Examples

CREATE OR REPLACE TABLE objectagg_example(g NUMBER, k VARCHAR(30), v VARIANT);
    INSERT INTO objectagg_example SELECT 0, 'name', 'Joe'::variant;
    INSERT INTO objectagg_example SELECT 0, 'age', 21::variant;
    INSERT INTO objectagg_example SELECT 1, 'name', 'Sue'::variant;
    INSERT INTO objectagg_example SELECT 1, 'zip', 94401::variant;

SELECT * FROM objectagg_example;

---+------+-------+
 G |  K   |   V   |
---+------+-------+
 0 | name | "Joe" |
 0 | age  | 21    |
 1 | name | "Sue" |
 1 | zip  | 94401 |
---+------+-------+
SELECT objectagg(k, v) FROM objectagg_example GROUP BY g;

------------------+
 OBJECTAGG(K, V)  |
------------------+
 {                |
   "name": "Sue", |
   "zip": 94401   |
 }                |
 {                |
   "age": 21,     |
   "name": "Joe"  |
 }                |
------------------+
SELECT seq, key, value
FROM (SELECT objectagg(k, v) o FROM objectagg_example GROUP BY g),
    LATERAL FLATTEN(input => o);

-----+------+-------+
 SEQ | KEY  | VALUE |
-----+------+-------+
 1   | name | "Sue" |
 1   | zip  | 94401 |
 2   | age  | 21    |
 2   | name | "Joe" |
-----+------+-------+