Aggregating: Advanced
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.
A group in, an array out
SELECTlistener_id,ARRAY_AGG(track) AS tracksFROM playsGROUP BY listener_id
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.
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
Why collect at all
This query runs on the 8-row plays table from this section. What does it return?
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.
| listener_id | genre | play_count |
|---|---|---|
| ana | pop | 2 |
| ana | rock | 2 |
| ben | jazz | 2 |
| ben | pop | 1 |
| cy | rock | 1 |
| listener_id | plays_by_genre |
|---|---|
| ana | {pop: 2, rock: 2} |
| ben | {jazz: 2, pop: 1} |
| cy | {rock: 1} |
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.
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.
- 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
- 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
- ▸Aggregate first so each key appears once per group, then fold with MAP_AGG
- ▸Use element_at when a key may be missing; brackets fail the query
- ▸Use MULTIMAP_AGG when one key can carry several values and you need them all
- ▸Keys share one type and values share one type, as in any MAP column
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?
ARRAY_AGG accepts an ORDER BY inside its parentheses: ARRAY_AGG(track ORDER BY played_at). Before appending anything, the aggregate sorts each group's rows by that expression, so position 1 holds the earliest play, position 2 the next, and so on. The sort happens per group, after GROUP BY has split the rows and before the array is built.
Inner ORDER BY versus outer ORDER BY
A query can carry an ORDER BY in 2 places, and neither affects the other. The one inside the aggregate arranges elements within each array. The one at the end of the query arranges the output rows, as you learned with ORDER BY and LIMIT, and it runs last. Sorting rows by listener_id says nothing about the order of tracks inside each row, and sorting the tracks says nothing about which listener prints first.
- Written as ARRAY_AGG(x ORDER BY y)
- Sorts the rows of each group separately
- Decides element positions inside each array
- Runs before the array is built
- Written as ORDER BY y after GROUP BY and HAVING
- Sorts the finished output rows
- Decides which group's row prints first
- Runs after SELECT, as the final sort
On the plays table, ben's plays are Delta at 310000 ms, Ember at 9000 ms and Fjord at 12000 ms. What's the first element of ben's array?
Taking the first element
Once the order is fixed, a position means something. ARRAY_AGG(track ORDER BY ms_played DESC)[1] sorts each group longest first and keeps element 1, which is each listener's longest play. Array positions start at 1, so [1] is the first element.
When you need only that single value, MAX_BY(track, ms_played) returns the track with the largest ms_played without building the array. Reach for the ARRAY_AGG form when you want several positions or the whole list.
Ties and parallel arrays
ORDER BY inside an aggregate is still a sort, and a sort leaves tied rows in no particular order. If 2 of ana's plays shared a played_at, either could land first, and today's run could disagree with tomorrow's. A second sort key such as ORDER BY played_at, track breaks the tie and makes the array come out the same on every run.
The same rule governs 2 arrays meant to line up. With ARRAY_AGG(track ORDER BY played_at) beside ARRAY_AGG(ms_played ORDER BY played_at), position 2 of one and position 2 of the other describe the same play. Drop the ORDER BY from both and no rule guarantees that position 2 still refers to the same play in each.
> Build a query that returns, for each listener with more than 1 play, their tracks ordered from longest play to shortest, with the output rows sorted by listener. Some tiles do not belong.
COUNT_IF(condition) evaluates a true-or-false expression on every row of the group and counts the rows where it came out true. COUNT_IF(skipped) counts skipped plays; COUNT_IF(ms_played >= 30000) counts plays that ran at least 30 seconds. Rows where the condition is false are not counted, and neither are rows where it's NULL, so only a definite true adds 1.
COUNT_IF versus WHERE
WHERE can count matching rows too, but it does so by removing the others before grouping. The difference shows up at zero. cy skipped nothing, so WHERE skipped removes every one of cy's rows, and a group with no rows produces no output row. COUNT_IF keeps cy's play in the group and reports 0.
Rates need a cast
What does this query return in skip_rate for ana, who has 1 skip in 4 plays?
Conditions inside HAVING
COUNT_IF is an aggregate, so it can sit in HAVING the way COUNT(*) does. HAVING COUNT_IF(skipped) >= 2 keeps listeners with at least 2 skips; on the sample that is ben alone. The condition inside COUNT_IF looks at single rows, and HAVING then compares the finished count, so a single expression filters at both levels.
COUNT(*) FILTER (WHERE c), the standard SQL form that attaches a row condition to any aggregate. FILTER also works on SUM or AVG, for example SUM(ms_played) FILTER (WHERE skipped); COUNT_IF is the shorter spelling for counting.Each of the 3 SUMs sees all of a listener's rows. For pop_ms, a pop row contributes its ms_played and every other row contributes 0, so ana's pop column adds 200000 and 198000 into 398000 and ignores her rock plays. A single scan and a single GROUP BY have split each listener's total into 3 columns. This layout, values of a category turned into fixed columns, is called a pivot.
ELSE 0 or no ELSE
SELECTdepartment,SUM(CASEWHEN is_manager THEN salaryELSE 0END) AS manager_payroll,AVG(CASEWHEN tenure_years >= 5 THEN salaryEND) AS avg_senior_salaryFROM employee_metricsGROUP BY department
Follow Eng through the animation. Its manager earns 70000 and its other engineer 90000, so manager_payroll adds 70000 and 0 and lands on 70000. For avg_senior_salary only the 7-year engineer passes tenure_years >= 5; the 3-year manager's CASE yields NULL, which AVG skips, so the result is 90000. Had the CASE ended in ELSE 0, AVG would have averaged 90000 with 0 and reported 45000, half of what Eng's only senior earns. In Sales both employees have 5 or more years, so its average is 65000 either way.
A teammate wants each listener's number of skipped plays and writes the query below. What does skips hold for ana, who has 4 plays and 1 skip?
Buckets as rows or as columns
- A row per bucket in the output
- Buckets are values, so 10 buckets still fit in 2 columns
- Each row lands in exactly 1 bucket: the first branch it matches
- Suits a chart or a further aggregation
- A column per bucket in the output
- Each bucket is a column you write by hand
- A row can count toward several overlapping buckets
- Suits a report row beside other per-listener figures
Collecting into a bucket
CASE also works inside the aggregates from the first sections, with a trap. ARRAY_AGG(CASE WHEN skipped THEN track END) hands the array a NULL for every unskipped play, because ARRAY_AGG keeps NULLs, so ana's array would hold Basalt plus 3 NULLs. The FILTER clause from the COUNT_IF section removes rows before the aggregate sees them, which is the shape you want for collecting.
- Write ELSE 0 inside SUM so a bucket with no matching rows reads 0
- Leave ELSE out inside AVG so non-matching rows stay out of the denominator
- Count a bucket with COUNT_IF or SUM(CASE WHEN ... THEN 1 ELSE 0 END)
- Name each bucket column after its condition, such as under_30s
- Don't wrap a CASE that ends in ELSE 0 in COUNT; it counts every row
- Don't add ELSE 0 to an AVG unless zeros belong in the average
- Don't write overlapping branches in a GROUP BY CASE; the first match wins
- Don't pivot categories that change weekly into columns; collect them with MAP_AGG
> Back at Spotify, a Wrapped-style feed needs a row per listener carrying everything a set of story cards shows: their longest plays in order, a lookup of plays per genre, how many plays counted as streams, how many they skipped, and listening time split by genre. A single CTE and a GROUP BY listener_id over the year's plays can produce it: ARRAY_AGG(track ORDER BY ms_played DESC) for the ordered list, MAP_AGG over per-genre counts for the genre card, COUNT_IF(ms_played >= 30000) and COUNT_IF(skipped) for the counters, and SUM over CASE for the per-genre minutes.
Fold rows into arrays and maps, set the order inside them, and count or sum only the rows that qualify.
Aggregate into arrays, maps, and beyond
- Category
- SQL
- Difficulty
- advanced
- Duration
- 27 minutes
- Challenges
- 19 hands-on challenges
Topics covered: ARRAY_AGG for collecting values, MAP_AGG for key-value pairs, Aggregate modifiers (ORDER BY), COUNT_IF conditional counting, CASE WHEN in aggregates
Lesson Sections
- ARRAY_AGG for collecting values (concepts: Array Aggregation)
A group in, an array out What lands in the array 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
- MAP_AGG for key-value pairs (concepts: Map Aggregation)
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. 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, wh
- Aggregate modifiers (ORDER BY) (concepts: Array Aggregation)
The By time tab returns ana's morning as it happened: Aurora, Basalt, Cinder, then Aurora again. By length rearranges those 4 elements longest first: Cinder at 240000 ms, the 2 Aurora plays, then Basalt at 15000 ms. Across the 3 tabs the groups and the row count stay the same, and so does each array's length; only positions inside each array change. Inner ORDER BY versus outer ORDER BY Taking the first element When you need only that single value, MAX_BY(track, ms_played) returns the track with
- COUNT_IF conditional counting (concepts: Conditional Counting)
One pass over the table produces 3 different counts per listener, each with its own condition, and every row is read once. Counting with WHERE would take a separate query per condition, because a WHERE clause trims the rows that all aggregates see; COUNT_IF keeps all 3 counts inside one GROUP BY. The last section shows a second one-pass route. ben has 3 plays, and only 1 of them counts as a stream: Ember and Fjord, his 2 short plays, both ran under 30000 ms, and he skipped both, which gives his
- CASE WHEN in aggregates (concepts: Conditional Aggregation)
COUNT_IF counts. Most bucketed questions need more than a count: listening time per genre, the average length of full plays only, revenue split by channel. The general tool is a CASE expression inside the aggregate. CASE runs first and, for each row, turns the value into what the bucket should receive. The aggregate then does its usual work on whatever CASE handed it. ELSE 0 or no ELSE A CASE without ELSE returns NULL for rows that match no branch, and SUM and AVG skip those NULLs, as do MIN and