sqlbeginner
Aggregate Strings with STRING_AGG / GROUP_CONCAT
Concatenate values from multiple rows into a single string per group.
sqlPress ⌘/Ctrl + Shift + C to copy
-- PostgreSQL: STRING_AGG
SELECT
department,
STRING_AGG(first_name, ', ' ORDER BY first_name) AS team_members,
COUNT(*) AS team_size
FROM employees
GROUP BY department;
-- MySQL: GROUP_CONCAT
SELECT
order_id,
GROUP_CONCAT(product_name ORDER BY product_name SEPARATOR ', ') AS products
FROM order_items
GROUP BY order_id;
-- With DISTINCT to remove duplicates
SELECT
customer_id,
STRING_AGG(DISTINCT category, ', ') AS purchased_categories
FROM orders o
JOIN products p ON o.product_id = p.product_id
GROUP BY customer_id;Use Cases
- Comma-separated lists in reports
- Tag aggregation
- Email recipient lists
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
sqlbeginner
String Aggregation with GROUP BY
Concatenate grouped values into comma-separated strings using STRING_AGG with ordering and filtering.
Best for: Tag lists per item
#aggregation#string-agg
sqladvanced
GROUPING SETS, CUBE, and ROLLUP
Generate multiple levels of aggregation in a single query with grouping sets.
Best for: Report subtotals
#sql#grouping-sets
sqlintermediate
Conditional Aggregation with FILTER / CASE
Compute multiple conditional aggregates in a single query using FILTER or CASE.
Best for: Pivot-style reports
#sql#conditional
sqlintermediate
JSON Aggregation and Querying
Aggregate related rows into JSON arrays and query JSONB columns with PostgreSQL native JSON operators.
Best for: API response building
#json#jsonb