PostgreSQL STRING_AGG Function
intermediateaggregation
2 min read
What is STRING_AGG?
STRING_AGG concatenates values from multiple rows into a single string, separated by a delimiter. It is PostgreSQL's equivalent of MySQL's GROUP_CONCAT.
Syntax
SELECT STRING_AGG(column, delimiter ORDER BY column)
FROM table_name;When to Use
- Creating comma-separated lists (all course names for a student)
- Building display-friendly summaries
- Generating CSV-like output within a query
Key Points
- Delimiter — The second argument is the separator string (commonly
', '). - ORDER BY — You can order the concatenated values:
STRING_AGG(name, ', ' ORDER BY name). - DISTINCT —
STRING_AGG(DISTINCT category, ', ')removes duplicates before concatenating. - NULLs — NULL values are automatically skipped.
- With GROUP BY — Most commonly used with GROUP BY to aggregate per group.
Guided Practice
Solve the challenge below. Use hints when stuck and check your answer for instant feedback.
Practice challengeGuided learning mode
PostgreSQL STRING_AGG Function Challenge
Write a query that solve this task: show each student with a comma-separated list of their courses.
Expected result
Each student name with a single string listing all their courses, e.g., "Algebra, Biology, Chemistry".
Hidden checks
- Returned rows and values
- Output columns and result shape
- Final database state after the query runs
Lesson guidance
What is STRING_AGG?
Initializing database...Each run starts from fresh sample data.
More Examples
Departments as a list
Get all unique department names as a single string.
Initializing database...Each run starts from fresh sample data.
Frequently Asked Questions
What is the difference between STRING_AGG and ARRAY_AGG?
STRING_AGG returns a single concatenated string. ARRAY_AGG returns a PostgreSQL array. Use STRING_AGG for display and ARRAY_AGG for array data.
Does STRING_AGG work in MySQL?
No. STRING_AGG is PostgreSQL-specific. The MySQL equivalent is GROUP_CONCAT.