InterviewPrepKit

Home / SQL / Advanced Patterns

Comma-Separated Course List Per Student

medium 00:00
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

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug