MAP_AGG for key-value pairs
Concepts covered: Map Aggregation
An array answers the question 'which values does this group hold?'. A map answers a different one: 'for this key, what's the value?'. MAP_AGG(key, value) builds a map from each group, turning every row into an entry whose key is the first argument and whose value is the second. You met MAP as a column type that arrives already built; MAP_AGG is how you construct one from ordinary rows.
Most real uses stack 2 GROUP BY levels. The inner query computes a number per listener and genre, so each genre appears once per listener. The outer query folds those rows into a map per listener.
WITH genre_counts AS (
SELECT
listener_id,
genre,
COUNT(*) AS play_count
FROM plays
GROUP BY
listener_id,
genre
)
SELECT
listener_id,
MAP_AGG(genre, play_count) AS plays_by_genre
FROM genre_counts
GROUP BY listener_id
ORDER BY listener_id| listener_id | track | genre | played_at | ms_played | skipped |
|---|---|---|---|---|---|
| ana | Aurora | pop | 08:10 | 200000 | 0 |
| ana | Basalt | rock | 08:14 | 15000 | 1 |
| ana | Cinder | rock | 08:20 | 240000 | 0 |
| ana | Aurora | pop | 09:02 | 198000 | 0 |
| ben | Delta | jazz | 07:45 | 310000 | 0 |
| ben | Ember | pop | 07:51 | 9000 | 1 |
| ben | Fjord | jazz | 08:30 | 12000 | 1 |
| cy | Basalt | rock | 10:00 | 230000 | 0 |
| listener_id | plays_by_genre |
|---|---|
| ana | {"pop":2,"rock":2} |
| ben | {"jazz":2,"pop":1} |
| cy | {"rock":1} |
The 5 inner rows become 3 outer rows. What's missing matters as much as what is there: ana has no jazz key and ben has no rock key. A map holds only the keys that occurred in the group, so the output follows the data. A genre that first appears next month becomes a new key with no edit to the query, where a design with a column per genre would need a new column every time.
Reading a value back out
Square brackets read a key: plays_by_genre['rock'] is 2 for ana. For ben the same expression stops the whole query with a key-not-present error, because his map never got a rock key. element_at(plays_by_genre, 'rock') reads the same value and returns NULL when the key is missing, which is what a report across many listeners needs.
WITH genre_counts AS (
SELECT
listener_id,
genre,
COUNT(*) AS play_count
FROM plays
GROUP BY
listener_id,
genre
),
listener_maps AS (
SELECT
listener_id,
MAP_AGG(genre, play_count) AS plays_by_genre
FROM genre_counts
GROUP BY listener_id
)
SELECT
listener_id,
element_at(plays_by_genre, 'rock') AS rock_plays,
element_at(plays_by_genre, 'jazz') AS jazz_plays
FROM listener_maps
ORDER BY listener_id| listener_id | track | genre | played_at | ms_played | skipped |
|---|---|---|---|---|---|
| ana | Aurora | pop | 08:10 | 200000 | 0 |
| ana | Basalt | rock | 08:14 | 15000 | 1 |
| ana | Cinder | rock | 08:20 | 240000 | 0 |
| ana | Aurora | pop | 09:02 | 198000 | 0 |
| ben | Delta | jazz | 07:45 | 310000 | 0 |
| ben | Ember | pop | 07:51 | 9000 | 1 |
| ben | Fjord | jazz | 08:30 | 12000 | 1 |
| cy | Basalt | rock | 10:00 | 230000 | 0 |
| listener_id | rock_plays | jazz_plays |
|---|---|---|
| ana | 2 | NULL |
| ben | NULL | 2 |
| cy | 1 | NULL |
ana reads 2 and NULL, and ben reads the reverse. cy reads 1 and NULL. Each NULL marks a genre that listener never played, and the query finishes for all 3 listeners.
Keys must be unique within a group
MAP_AGG assumes each key arrives once per group. Feed it raw plays with MAP_AGG(genre, track) and ana sends pop twice with Aurora both times. She also sends rock twice, once with Basalt and once with Cinder. A map can hold rock only once, so MAP_AGG keeps one of the 2 values and discards the other without raising an error. Which value survives depends on the order the rows arrive, the same unstable order ARRAY_AGG showed. To keep everything, collect before you fold: an inner GROUP BY on listener and genre builds an array of tracks per genre, and MAP_AGG then maps each genre to its array. MULTIMAP_AGG(key, value) builds that same map of arrays in a single call.
| listener_id | track | genre | played_at | ms_played | skipped |
|---|---|---|---|---|---|
| ana | Aurora | pop | 08:10 | 200000 | 0 |
| ana | Basalt | rock | 08:14 | 15000 | 1 |
| ana | Cinder | rock | 08:20 | 240000 | 0 |
| ana | Aurora | pop | 09:02 | 198000 | 0 |
| ben | Delta | jazz | 07:45 | 310000 | 0 |
| ben | Ember | pop | 07:51 | 9000 | 1 |
| ben | Fjord | jazz | 08:30 | 12000 | 1 |
| cy | Basalt | rock | 10:00 | 230000 | 0 |
MAP_AGG
One value per key: ana's rock entry keeps Basalt or Cinder and silently drops the other.
SELECT
listener_id,
MAP_AGG(genre, track) AS track_by_genre
FROM plays
GROUP BY listener_id
ORDER BY listener_id| listener_id | track_by_genre |
|---|---|
| ana | {"pop":"Aurora","rock":"Basalt"} |
| ben | {"jazz":"Delta","pop":"Ember"} |
| cy | {"rock":"Basalt"} |
Arrays first
Each genre's tracks are collected into an array first, so ana's rock entry holds both Basalt and Cinder.
WITH genre_tracks AS (
SELECT
listener_id,
genre,
ARRAY_AGG(track) AS tracks
FROM plays
GROUP BY
listener_id,
genre
)
SELECT
listener_id,
MAP_AGG(genre, tracks) AS tracks_by_genre
FROM genre_tracks
GROUP BY listener_id
ORDER BY listener_id| listener_id | tracks_by_genre |
|---|---|
| ana | {"pop":["Aurora","Aurora"],"rock":["Basalt","Cinder"]} |
| ben | {"jazz":["Delta","Fjord"],"pop":["Ember"]} |
| cy | {"rock":["Basalt"]} |
- ARRAY_AGG
- Answers: which values does the group hold?
- Keeps repeats, and each element has a position
- Read by position, with [1] for the first element
- Position means something only with ORDER BY inside the call
- MAP_AGG
- Answers: what value goes with this key?
- Holds each key once; a repeated key loses a value
- Values are read by key through element_at or square brackets
- The order of keys carries no meaning
An order_events table has a row per status change: order_id, status, changed_at. One order went 'placed', then 'shipped', then 'placed' again after a failed delivery. Grouped by order_id, what does MAP_AGG(status, changed_at) give for that order?
- A map with 2 keys, where 'placed' holds one of its 2 timestamps and the query does not control which
- A map with 3 keys, because each of the 3 status rows adds its own entry to the map
- An error, because the key 'placed' arrives twice within the same order_id group
- A map with 2 keys, where 'placed' holds an array containing both of its timestamps
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.