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
plays
listener_idtrackgenreplayed_atms_playedskipped
anaAurorapop08:102000000
anaBasaltrock08:14150001
anaCinderrock08:202400000
anaAurorapop09:021980000
benDeltajazz07:453100000
benEmberpop07:5190001
benFjordjazz08:30120001
cyBasaltrock10:002300000
Result
listener_idplays_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
plays
listener_idtrackgenreplayed_atms_playedskipped
anaAurorapop08:102000000
anaBasaltrock08:14150001
anaCinderrock08:202400000
anaAurorapop09:021980000
benDeltajazz07:453100000
benEmberpop07:5190001
benFjordjazz08:30120001
cyBasaltrock10:002300000
Result
listener_idrock_playsjazz_plays
ana2NULL
benNULL2
cy1NULL

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.

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

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
Result
listener_idtrack_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
Result
listener_idtracks_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?

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.