Full answer
Test data:
sql
CREATE TABLE enrolments (student text, course text, enrolled date);
INSERT INTO enrolments VALUES
('Asha', 'SQL', '2026-03-01'), ('Asha', 'Python', '2026-01-15'), ('Asha', 'SQL', '2026-06-01'),
('Ben', 'Go', '2026-02-10'), ('Ben', 'Python', '2026-02-01');sql
SELECT student, string_agg(course, ', ' ORDER BY enrolled) AS in_order, string_agg(DISTINCT course, ' | ' ORDER BY course) AS distinct_courses, array_agg(enrolled ORDER BY enrolled DESC) AS dates FROM enrolments GROUP BY student ORDER BY student;PostgreSQL returns:
text
student | in_order | distinct_courses | dates
---------+------------------+------------------+------------------------------------
Asha | Python, SQL, SQL | Python | SQL | {2026-06-01,2026-03-01,2026-01-15}
Ben | Python, Go | Go | Python | {2026-02-10,2026-02-01}
(2 rows)For Asha, the ordered list follows enrolment dates, so Python comes before both SQL enrolments, while the DISTINCT version lists each course once in alphabetical order. When DISTINCT is used, the ORDER BY inside the aggregate must use the aggregated expression itself, which is why it sorts by course. array_agg keeps the dates as a real date array, newest first. Without an internal ORDER BY, the order depends on the plan and can change between runs or versions.
sql
CREATE TABLE enrolments (student text, course text, enrolled date);
INSERT INTO enrolments VALUES
('Asha', 'SQL', '2026-03-01'), ('Asha', 'Python', '2026-01-15'), ('Asha', 'SQL', '2026-06-01'),
('Ben', 'Go', '2026-02-10'), ('Ben', 'Python', '2026-02-01');
SELECT student, string_agg(course, ', ' ORDER BY enrolled) AS in_order, string_agg(DISTINCT course, ' | ' ORDER BY course) AS distinct_courses, array_agg(enrolled ORDER BY enrolled DESC) AS dates FROM enrolments GROUP BY student ORDER BY student;Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- string_agg joins with a separator
- array_agg builds arrays
- ORDER BY inside the call sets order
- DISTINCT removes duplicates
- Unordered aggregation has no guaranteed order
Common mistakes
- Relying on table order for list order
- Sorting by another column together with DISTINCT
Follow-ups
- How would you limit each list to three items?
- How do you split a string_agg result back into rows?
Tips
- Order inside the aggregate