Aggregate modifiers (ORDER BY)

Concepts covered: Array Aggregation

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.

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

No ORDER BY

Elements follow the order rows reached the aggregate, which no part of the query controls.

SELECT
  listener_id,
  ARRAY_AGG(track) AS tracks
FROM plays
GROUP BY listener_id
ORDER BY listener_id
Result
listener_idtracks
ana["Aurora","Basalt","Cinder","Aurora"]
ben["Delta","Ember","Fjord"]
cy["Basalt"]

By time

Each array is a listening session in sequence, earliest play first.

SELECT
  listener_id,
  ARRAY_AGG(track ORDER BY played_at) AS tracks
FROM plays
GROUP BY listener_id
ORDER BY listener_id
Result
listener_idtracks
ana["Aurora","Basalt","Cinder","Aurora"]
ben["Delta","Ember","Fjord"]
cy["Basalt"]

By length

Each array runs from the longest play to the shortest.

SELECT
  listener_id,
  ARRAY_AGG(track ORDER BY ms_played DESC) AS tracks
FROM plays
GROUP BY listener_id
ORDER BY listener_id
Result
listener_idtracks
ana["Cinder","Aurora","Aurora","Basalt"]
ben["Delta","Fjord","Ember"]
cy["Basalt"]

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

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.

Inside the aggregate
  • 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
At the end of the query
  • 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?

SELECT
  listener_id,
  ARRAY_AGG(track ORDER BY ms_played) AS tracks
FROM plays
GROUP BY listener_id
ORDER BY listener_id DESC

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.

SELECT
  listener_id,
  ARRAY_AGG(track ORDER BY ms_played DESC)[1] AS longest_track,
  MAX(ms_played) AS longest_ms
FROM plays
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_idlongest_tracklongest_ms
anaCinder240000
benDelta310000
cyBasalt230000

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.

SELECT
  listener_id,
  ARRAY_AGG(track ORDER BY played_at) AS tracks,
  ARRAY_AGG(ms_played ORDER BY played_at) AS durations
FROM plays
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_idtracksdurations
ana["Aurora","Basalt","Cinder","Aurora"][200000,15000,240000,198000]
ben["Delta","Ember","Fjord"][310000,9000,12000]
cy["Basalt"][230000]

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.

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.