sqlbeginner

String Aggregation with GROUP BY

Concatenate grouped values into comma-separated strings using STRING_AGG with ordering and filtering.

sql
-- Aggregate tags per post
SELECT
  p.id,
  p.title,
  STRING_AGG(t.name, ', ' ORDER BY t.name) AS tags
FROM posts p
JOIN post_tags pt ON pt.post_id = p.id
JOIN tags t ON t.id = pt.tag_id
GROUP BY p.id, p.title;

-- With DISTINCT to remove duplicates
SELECT
  department,
  STRING_AGG(DISTINCT skill, ', ' ORDER BY skill) AS skills
FROM employees
GROUP BY department
HAVING COUNT(*) > 3;

Use Cases

  • Tag lists per item
  • Comma-separated emails
  • Report summaries

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.