sqlbeginner

Aggregate Strings with STRING_AGG / GROUP_CONCAT

Concatenate values from multiple rows into a single string per group.

sql
-- 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.