In this post we are going to cover ARRAY_AGG and OBJECT_AGG in Snowflake.
Both of them are aggregates that collapse a group of rows into one cell, the same way LISTAGG does. The difference is what ends up in the cell. LISTAGG hands us a string. ARRAY_AGG hands us an array. OBJECT_AGG takes a key and a value and hands us a JSON object.
We will start with ARRAY_AGG, because it behaves almost exactly like LISTAGG. Then we will get to the one thing that makes it worth having. After that we move on to OBJECT_AGG, where the keys bring a few rules of their own.
Every query below was run on a real Snowflake account, and every result you see is the output it gave back.
Episode 20 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.
- Let's create some sample data
- Let's start with ARRAY_AGG
- Now let's ask for an order with WITHIN GROUP
- Now let's try DISTINCT inside it
- Is a NULL group dropped too?
- Now let's do something a string cannot do
- Let's move on to OBJECT_AGG
- Now let's get one object per group
- Let's see what OBJECT_AGG does about NULLs
- One last thing: the keys have to be unique
Let's create some sample data
Everything in this post runs against the same EMPLOYEES table the previous post used. The script below creates it.
Copy this into a Snowflake worksheet and run it once. Every post in this series uses the same table, so if you have run it already you are ready to go.
-- Sample data for this post.
-- Run this once. Every post in this series uses the same EMPLOYEES table.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;
CREATE OR REPLACE TABLE EMPLOYEES (
EMP_ID INT,
FIRST_NAME VARCHAR,
LAST_NAME VARCHAR,
EMAIL VARCHAR,
DEPT_ID INT,
MANAGER_ID INT,
SALARY NUMBER(10,2),
COMMISSION_PCT NUMBER(4,2),
HIRE_DATE DATE
);
INSERT INTO EMPLOYEES VALUES
(1, 'Aisha', 'Khan', 'aisha.khan@example.com', 10, 6, 118000.00, NULL, '2019-03-11'),
(2, 'Marcus', 'Reid', 'marcus.reid@example.com', 10, 6, 96500.00, NULL, '2021-07-01'),
(3, 'Lena', 'Fischer', 'lena.fischer@example.com', 20, 6, 104000.00, 0.05, '2018-01-22'),
(4, 'Tomas', 'Novak', 'tomas.novak@example.com', 20, 3, 87250.00, NULL, '2022-09-05'),
(5, 'Priya', 'Raman', 'priya.raman@example.com', 30, 6, 96500.00, 0.10, '2020-11-17'),
(6, 'Daniel', 'O''Connor', 'daniel.oconnor@example.com', 10, NULL, 131000.00, NULL, '2016-05-30'),
(7, 'Sofia', 'Marino', 'sofia.marino@example.com', 30, 5, 71400.00, 0.08, '2023-02-13'),
(8, 'Grace', 'Lin', 'grace.lin@example.com', NULL, 6, 92000.00, NULL, '2021-04-19');Three columns matter here. FIRST_NAME is what ARRAY_AGG collects. SALARY is what OBJECT_AGG pairs it with later. And DEPT_ID is the grouping column. Notice that Grace's DEPT_ID is NULL, which turns out to matter twice.
Let's start with ARRAY_AGG
If you read the LISTAGG post, this will look very familiar. We write ARRAY_AGG and the column we want collected.
SELECT ARRAY_AGG(FIRST_NAME) AS NAMES FROM EMPLOYEES;| NAMES |
|---|
| [ "Aisha", "Marcus", "Lena", "Tomas", "Priya", "Daniel", "Sofia", "Grace" ] |
One row, one column, and eight names in that single cell. That is the same shape LISTAGG produced. The square brackets and the quotes are Snowflake telling us this is an array rather than a sentence.
And here is the second familiar thing. Look at the order. Aisha, Marcus, Lena, Tomas. Not alphabetical. The rule is the same rule, and the documentation uses the same word.
“If you do not specify WITHIN GROUP (ORDER BY), the order of elements within each array is unpredictable.”
Now let's ask for an order with WITHIN GROUP
The fix is the same fix, spelled the same way.
SELECT ARRAY_AGG(FIRST_NAME) WITHIN GROUP (ORDER BY FIRST_NAME) AS NAMES FROM EMPLOYEES;| NAMES |
|---|
| [ "Aisha", "Daniel", "Grace", "Lena", "Marcus", "Priya", "Sofia", "Tomas" ] |
Alphabetical, because that is what we asked for. Everything we learned about LISTAGG's ordering applies here unchanged.
That is the useful way to hold ARRAY_AGG generally. It is not a new function to learn, it is LISTAGG with a different return type. Same WITHIN GROUP, same DISTINCT, same rule about NULLs. One thing to remember rather than two.
Now let's try DISTINCT inside it
DISTINCT works inside ARRAY_AGG the same way it works inside LISTAGG and inside COUNT. Let's run it over DEPT_ID and count the elements in the answer carefully.
SELECT ARRAY_AGG(DISTINCT DEPT_ID) AS DEPTS FROM EMPLOYEES;| DEPTS |
|---|
| [ 20, 10, 30 ] |
Three elements. Now think back to the DISTINCT episode. SELECT DISTINCT DEPT_ID on this same table returned four rows, and one of them was NULL. That count is not captured on this page, because it belongs to that episode, but you can read it straight off the setup script above.
Four distinct values go in. Three come out. The one that is missing is the NULL, and it is documented. “NULL values are omitted from the output.”
That is the same rule we met with COUNT and again with LISTAGG. Third outing. Aggregates leave NULLs out.
The elements in that cell are also not sorted. There is no WITHIN GROUP on this query, so the order is unpredictable, exactly as in the section above.
Is a NULL group dropped too?
It is not, and this is the pair of ideas worth separating. A NULL value and a NULL group sound the same and are not. Getting them the wrong way round sends people hunting for a bug that does not exist.
A NULL value is dropped from the array. That is the section above. A NULL group is not dropped. Let's group by department and see.
SELECT DEPT_ID, ARRAY_AGG(FIRST_NAME) WITHIN GROUP (ORDER BY FIRST_NAME) AS TEAM
FROM EMPLOYEES GROUP BY DEPT_ID ORDER BY DEPT_ID;| DEPT_ID | TEAM |
|---|---|
| 10 | [ "Aisha", "Daniel", "Marcus" ] |
| 20 | [ "Lena", "Tomas" ] |
| 30 | [ "Priya", "Sofia" ] |
| NULL | [ "Grace" ] |
Four rows, and the NULL department is still a row of its own holding an array with Grace in it.
Read it slowly, because it is exact. Grace's department is NULL, so she is in the NULL group. Her name is not NULL, so her name is in the array. The NULL-omitting rule applies to the values going into the array. It never applies to the groups the GROUP BY makes.
Now let's do something a string cannot do
Everything so far has been LISTAGG with square brackets. This is the actual difference. An array is still data, so we can do things to it. Let's wrap ARRAY_SIZE around the ARRAY_AGG and ask how many names are in each team.
SELECT DEPT_ID, ARRAY_SIZE(ARRAY_AGG(FIRST_NAME)) AS TEAM_SIZE FROM EMPLOYEES GROUP BY DEPT_ID ORDER BY DEPT_ID;| DEPT_ID | TEAM_SIZE |
|---|---|
| 10 | 3 |
| 20 | 2 |
| 30 | 2 |
| NULL | 1 |
Those four numbers are the same four that COUNT(*) returned back in the COUNT episode, which is exactly the point. We got there by asking a question of the array rather than of the table.
LISTAGG | ARRAY_AGG | |
|---|---|---|
| What you get back | A VARCHAR | An ARRAY |
WITHIN GROUP (ORDER BY ...) | Same | Same |
DISTINCT inside it | Works | Works |
NULL values | Skipped | Omitted |
| Get one value out of it | Split the string apart first | Index into it |
| Count what is in it | Split, then count the pieces | ARRAY_SIZE |
Indexing with NAMES[0] and FLATTEN belong to the semi-structured level later in the course. For now the thing to take away is that the option exists at all. With a string it does not.
Let's move on to OBJECT_AGG
OBJECT_AGG takes two arguments instead of one. A key and a value. Let's build an object that goes from first name to salary.
SELECT OBJECT_AGG(FIRST_NAME, SALARY::VARIANT) AS SALARY_BY_NAME FROM EMPLOYEES;| SALARY_BY_NAME |
|---|
| { "Aisha": 118000, "Daniel": 131000, "Grace": 92000, "Lena": 104000, "Marcus": 96500, "Priya": 96500, "Sofia": 71400, "Tomas": 87250 } |
One row again, and this time the cell is a JSON object rather than a list.
The ::VARIANT is a cast, which gets covered properly later in the course. It is in this query because OBJECT_AGG wants a VARIANT for the value and SALARY is a number.
The keys came back in alphabetical order on this run. That is what this one run did. This page has not checked for a guarantee, so do not build on it. If you need the keys in a particular order, that is a property of whatever reads the object, not of this query.
Now let's get one object per group
This is where it gets useful. We add a GROUP BY and each row becomes a small lookup table.
SELECT DEPT_ID, OBJECT_AGG(FIRST_NAME, SALARY::VARIANT) AS PAY FROM EMPLOYEES WHERE DEPT_ID IS NOT NULL GROUP BY DEPT_ID ORDER BY DEPT_ID;| DEPT_ID | PAY |
|---|---|
| 10 | { "Aisha": 118000, "Daniel": 131000, "Marcus": 96500 } |
| 20 | { "Lena": 104000, "Tomas": 87250 } |
| 30 | { "Priya": 96500, "Sofia": 71400 } |
One object per department. Department 10 holds three name-to-salary pairs, and 20 and 30 hold two each. That is a shape none of the other aggregates in this level can make, and it is a very natural thing to hand to an application. It is already the shape the application wanted.
Three rows, though, not four. The WHERE DEPT_ID IS NOT NULL in that query is doing that, and it is there only to keep the output tidy. Let's take it off and see the NULL department come back.
SELECT DEPT_ID, OBJECT_AGG(FIRST_NAME, SALARY::VARIANT) AS PAY
FROM EMPLOYEES
GROUP BY DEPT_ID
ORDER BY DEPT_ID;| DEPT_ID | PAY |
|---|---|
| 10 | { "Aisha": 118000, "Daniel": 131000, "Marcus": 96500 } |
| 20 | { "Lena": 104000, "Tomas": 87250 } |
| 30 | { "Priya": 96500, "Sofia": 71400 } |
| NULL | { "Grace": 92000 } |
Four rows now, and the NULL department is holding {"Grace": 92000}. So a NULL group is not dropped here either. Same as ARRAY_AGG above, and same as plain GROUP BY back in the GROUP BY episode.
Let's see what OBJECT_AGG does about NULLs
COMMISSION_PCT is NULL for most of these employees, and FIRST_NAME is never NULL. So if we use one as the value and the other as the key, we have isolated the question of what happens to a NULL value.
SELECT OBJECT_AGG(FIRST_NAME, COMMISSION_PCT::VARIANT) AS COMMISSIONS
FROM EMPLOYEES;| COMMISSIONS |
|---|
| { "Lena": 0.05, "Priya": 0.1, "Sofia": 0.08 } |
Three pairs. Lena, Priya and Sofia. The other five employees are not in the object at all. Not with a NULL against their name, and not with an empty value. The whole pair was dropped.
We cannot tell, from the object alone, whether a missing key means that person does not exist or that person has no commission. If that distinction matters, give the value a default with COALESCE before aggregating, so the key survives with something explicit against it.
Priya's commission is 0.10 in the table and comes back as 0.1 inside the object. The ::VARIANT cast dropped the trailing zero, because a JSON number has no scale to preserve. If a report needs two decimal places, format the value. Do not assume the object kept them.
And what about a NULL key?
The video leaves this one open, and says so honestly. The query it reaches for fails for an unrelated reason before it can answer. There is a captured answer, though. NULLIF(FIRST_NAME, 'Grace') turns exactly one key into a NULL, Grace's, and changes nothing else.
SELECT OBJECT_AGG(NULLIF(FIRST_NAME, 'Grace'), SALARY::VARIANT) AS BY_NAME
FROM EMPLOYEES;| BY_NAME |
|---|
| { "Aisha": 118000, "Daniel": 131000, "Lena": 104000, "Marcus": 96500, "Priya": 96500, "Sofia": 71400, "Tomas": 87250 } |
Seven pairs, and Grace is gone. There is no NULL key in the object and no empty key either. Her salary is fine. The NULL department's object in the section above has her at 92000. So it is the NULL key that took the pair out.
That is one captured run on one version of Snowflake, not a documented guarantee, and this page is not going to dress it up as one. Treat it as a strong hint and test it yourself if your key column is nullable, because a silently vanishing row is the worst possible way to find out.
One last thing: the keys have to be unique
Here is the query the video tried first. MANAGER_ID looks like a reasonable key. One object entry per manager, pointing at a salary.
SELECT OBJECT_AGG(MANAGER_ID::VARCHAR, SALARY::VARIANT) AS BY_MANAGER
FROM EMPLOYEES;100103 (22000): Duplicate field key '6'
It does not run. Manager 6 has more than one person reporting to them, so the key '6' would have to appear more than once in one object, and an object cannot hold the same key twice.
The behaviour worth remembering is how it fails. It raises an error rather than silently keeping one of the values and discarding the rest. A loud failure here is a gift. If we want one entry per manager, we aggregate the values first, into an array or a sum per manager, and build the object out of that.
Key points
ARRAY_AGGisLISTAGGwith a different return type. SameWITHIN GROUP (ORDER BY ...), sameDISTINCT, same rule aboutNULLs.- Without
WITHIN GROUP (ORDER BY ...)the order of elements inside the array is, in Snowflake's word, unpredictable. NULLvalues are omitted from the array: four distinct department values go in and three elements come out, and you can see which one is missing.- A
NULLvalue is dropped from the array. ANULLgroup is not dropped. It is still a row of its own. - The real difference from
LISTAGGis that an array is still data.ARRAY_SIZEcounts it, and we can index into it or pass it on. A string has to be split apart first. OBJECT_AGGtakes a key and a value and builds a JSON object. WithGROUP BYeach row becomes a small lookup table.OBJECT_AGGdrops the whole pair when the value isNULL, so a missing key is ambiguous.COALESCEthe value if that matters.- In the captured run here, a
NULLkey also drops the pair. That is evidence rather than a documented guarantee, so test it on your own data. OBJECT_AGGkeys must be unique. A duplicate key raisesDuplicate field keyrather than quietly keeping one value.
In the next post we will look at MEDIAN, STDDEV and the percentiles. The statistical aggregates, which answer questions an average cannot. We start with how spread out the numbers are and where the middle actually is.
Every query and every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the script above, including the failed one — the error pane is the real error. The EMPLOYEES data is invented demo data created by that script. No performance or benchmark claims are made anywhere in this series. The sentences quoted in italics are from the Snowflake ARRAY_AGG documentation and the OBJECT_AGG documentation.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.