ARRAY_AGG for collecting values

Concepts covered: Array Aggregation

Every aggregate you have used so far reduces a group to a single number: COUNT says how many rows, SUM gives a total, MAX picks the largest value. ARRAY_AGG(column) also reduces each group to a single value, and that value is an array holding every input value from the group. A listener with 4 plays becomes 1 output row carrying a 4-element array, and the individual values survive inside it.

The examples in this lesson run on a plays table with a row for every time a listener started a track. ms_played is how long the track ran before it ended or was cut off, skipped is true when the listener moved on early, and played_at holds the start time as HH:MM text, so it sorts in time order.

Schema
  • plays: listener_id VARCHAR, track VARCHAR, genre VARCHAR, played_at VARCHAR, ms_played INTEGER, skipped BOOLEAN

A group in, an array out

SELECT
  listener_id,
  ARRAY_AGG(track) AS tracks
FROM plays
GROUP BY listener_id
plays
listener_idtrack
anaAurora
anaBasalt
anaCinder
anaAurora
benDelta
benEmber
benFjord
cyBasalt

Watch the animation in 2 moves. GROUP BY sorts the 8 rows into a pile per listener: 4 for ana, 3 for ben, 1 for cy. ARRAY_AGG then walks each pile and appends each row's track to that pile's array. The output has 3 rows because there are 3 groups, the same rule that governs COUNT and SUM. The new part is the shape of the value: each array has exactly as many elements as its group has rows.

What lands in the array

ARRAY_AGG keeps every value it receives. ana played Aurora twice, so Aurora appears twice in her array. Put DISTINCT inside the parentheses and each value appears once per group, the same way COUNT(DISTINCT track) counts each value once. NULLs are kept as well: a row whose track is NULL adds a NULL element, where COUNT(track) would have passed over it.

plays
listener_idtrackgenreplayed_atms_playedskipped
anaAurorapop08:102000000
anaBasaltrock08:14150001
anaCinderrock08:202400000
anaAurorapop09:021980000
benDeltajazz07:453100000
benEmberpop07:5190001
benFjordjazz08:30120001
cyBasaltrock10:002300000

All values

Every play contributes an element, so ana's array repeats Aurora and matches her play count of 4.

SELECT
  listener_id,
  ARRAY_AGG(track) AS tracks,
  COUNT(*) AS play_count
FROM plays
GROUP BY listener_id
ORDER BY listener_id
Result
listener_idtracksplay_count
ana["Aurora","Basalt","Cinder","Aurora"]4
ben["Delta","Ember","Fjord"]3
cy["Basalt"]1

DISTINCT

Repeats collapse: ana's array drops to 3 tracks, matching COUNT(DISTINCT track).

SELECT
  listener_id,
  ARRAY_AGG(DISTINCT track) AS distinct_tracks,
  COUNT(DISTINCT track) AS distinct_count
FROM plays
GROUP BY listener_id
ORDER BY listener_id
Result
listener_iddistinct_tracksdistinct_count
ana["Aurora","Basalt","Cinder"]3
ben["Delta","Ember","Fjord"]3
cy["Basalt"]1

Put the array beside a count of the same rows and the 2 always agree. In the first tab ana has 4 elements and a play_count of 4; the second tab shows 3 of each. That agreement doubles as a check. When an array is longer than you expected, the group holds rows you didn't expect, and reading the array shows you which ones.

The order inside is not fixed yet

Look at the order of ana's tracks in either tab. It follows the sequence in which rows reached the aggregate, which depends on how the table was split across workers and which worker finished first. On a large table the same query can return the same elements in a different order on the next run, with no change to the data. Until you set the order explicitly, read an array from ARRAY_AGG as a collection: fine for checking what's in it or how many, wrong for asking which came first. The ORDER BY modifier, 2 sections ahead, sets that order.

Why collect at all

This query runs on the 8-row plays table from this section. What does it return?

SELECT
  genre,
  ARRAY_AGG(DISTINCT listener_id) AS listeners
FROM plays
GROUP BY genre

About this lesson

This section is part of the Aggregating: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.