Ordered aggregation
Overview
Order-sensitive aggregates combine values in a chosen sequence. Put ORDER BY inside the aggregate call when supported, rather than relying on the order of stored rows or an outer ORDER BY. A unique tie breaker makes the sequence deterministic.
First example
SELECT STRING_AGG(name, ', ' ORDER BY price_cents ASC, id) FROM products;Observed SQLite result (rows in JSON):
[ [ "Pencil, Pen, Notebook, Bag" ]]How it works
STRING_AGG(name, separator ORDER BY key) is supported by PostgreSQL 17 and the tested SQLite 3.46.1 build. The SQLite alias GROUP_CONCAT supports this ordering too. Both examples order by price with id as a tie breaker. NULL string inputs are skipped. Ordered-set percentiles use a different PostgreSQL syntax: PERCENTILE_CONT(fraction) WITHIN GROUP (ORDER BY value). The continuous median may interpolate between observations, while the discrete version chooses an observed value.
Practical example
SELECT GROUP_CONCAT(name, ' | ' ORDER BY price_cents DESC, id) FROM products;Observed SQLite result (rows in JSON):
[ [ "Bag | Notebook | Pen | Pencil" ]]Practice and mistakes
Outer ORDER BY sorts result rows, not the elements inside a concatenated string. Practice: change ASC to DESC for price in the first example; predict Bag, Notebook, Pen, Pencil. Do not use a delimited string as a substitute for relational data. The local SQLite build has no median function; newer SQLite versions or extensions may provide one.
PostgreSQL 17 — not executed
SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY score), PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY score) FROM sort_scores;Expected result: 5, 0