InterviewPrepKit

Home / SQL / Advanced Patterns

Comma-Separated Course List Per Student

medium
Solving tips
  • Collapsing many rows into one delimited string is `STRING_AGG(value, delimiter)` in PostgreSQL.
  • Sort the concatenation deterministically with `STRING_AGG(course, ', ' ORDER BY course)` — the ORDER BY goes inside the aggregate's parentheses.
  • GROUP BY the key you want one string per (student), and remember STRING_AGG skips NULLs silently.

Enrollments store one row per student-course pair. Produce a single alphabetized, comma-separated course list for each student.

Schema

CREATE TABLE enrollments (
  student  TEXT,
  course   TEXT
);

Sample data:

studentcourse
AlicePhysics
AliceMath
AliceChemistry
BobMath
BobBiology

Task

Return one row per student with columns student and courses, where courses is that student’s courses joined into one string, sorted alphabetically and separated by ", " (comma and a space). Order by student ascending.

Expected output

studentcourses
AliceChemistry, Math, Physics
BobBiology, Math
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.