String Aggregation Functions: Examples
Module: Aggregate Functions & Grouping
Basic String Aggregation
basic
Create comma-separated list of employees per department
SELECT
department,
STRING_AGG(employee_name, ', ') AS employees
FROM employees
GROUP BY department;
department | employees
Engineering | Alice, Bob, Carol
Sales | Dave, Eve
Marketing | Frank
STRING_AGG concatenates employee names with comma separator. One row per department.
PostgreSQL
Ordered String Aggregation
intermediate
List products per category, alphabetically ordered
SELECT
category,
STRING_AGG(product_name, ', ' ORDER BY product_name) AS products
FROM products
GROUP BY category
ORDER BY category;
category | products
Electronics | Keyboard, Laptop, Mouse
Furniture | Chair, Desk, Table
ORDER BY inside STRING_AGG sorts values before concatenation. Results alphabetically ordered.
PostgreSQL
Product Tags Collection
intermediate
Aggregate all tags for each product
SELECT
product_id,
product_name,
STRING_AGG(tag_name, ', ' ORDER BY tag_name) AS tags
FROM products p
JOIN product_tags pt ON p.product_id = pt.product_id
GROUP BY product_id, product_name;
product_id | product_name | tags
1 | Laptop | electronics, portable, wireless