String Aggregation with GROUP BY
Concatenate grouped values into comma-separated strings using STRING_AGG with ordering and filtering.
-- 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.
Pandas GroupBy Aggregation Examples
GroupBy operations with multiple aggregations, named aggregations, and transform for DataFrame analysis.
JSON Aggregation and Querying
Aggregate related rows into JSON arrays and query JSONB columns with PostgreSQL native JSON operators.
Generate Series Calendar Table
Create a date calendar using generate_series for gap-free time series reporting and joins.
SQL Window Functions for Analytics
Advanced SQL window functions for running totals, rankings, moving averages, and gap analysis.