How to aggregate values into an array in PostgreSQL?
Here's the bread and butter of aggregating values into an array in PostgreSQL:
To bundle related values into a single array per group:
For sorted arrays that care about order:
These three code blocks are your swiss army knife for creating and organizing arrays in PostgreSQL.
Dealing with Student-Grade relationship
Suppose we have Student and Grade tables. We want student grades clumped together in an array:
Merging grades into a single array per student:
Subqueries for additional control
For times when ordinary joins don't cut it, use subqueries to assemble arrays:
This will yield only high marks. Sorry, no free passes for students!
Text Aggregation and Conversion
If you're more of a "strings attached" person, STRING_AGG()
is your buddy:
Or to ASCII-fy an array:
Different tools for different rules!
Keeping Order with Data
The ORDER BY
clause within array_agg()
maintains sequence:
Handling Nulls and Duplicates in Style
Null values and duplicates - the necessary evils. PostgreSQL's array_agg()
includes them by default. However, you can give them a slip:
Getting rid of sneaky duplicates:
A clean array is a contributor to peaceful data mining!
Was this article helpful?