What if you could turn many rows of text into one neat list with just one simple command?
Why String aggregation with STRING_AGG in PostgreSQL? - Purpose & Use Cases
Imagine you have a list of friends and their favorite fruits stored in a table. You want to see all the fruits each friend likes in one single line, separated by commas.
Doing this manually means writing lots of code to loop through each friend's fruits and join them together.
Manually combining strings from multiple rows is slow and complicated. You might write long, repetitive code or use multiple queries. It's easy to make mistakes, like missing commas or extra spaces.
This wastes time and makes your code hard to read and maintain.
STRING_AGG lets you combine multiple strings from different rows into one string easily. It automatically adds separators like commas, so you get a clean list in one step.
This makes your queries shorter, faster, and less error-prone.
SELECT friend, fruit FROM favorites;
-- Then manually combine fruits in your application codeSELECT friend, STRING_AGG(fruit, ', ') AS fruits FROM favorites GROUP BY friend;With STRING_AGG, you can quickly create neat, readable lists from many rows, making your data summaries clear and concise.
A teacher wants to see all subjects each student is enrolled in, listed in one row per student. STRING_AGG helps show "Math, Science, History" instead of many separate rows.
Manually joining strings from rows is slow and error-prone.
STRING_AGG combines multiple strings into one with a separator.
This makes queries simpler and results easier to read.