Unique Course Enrollments
An educational platform wants to identify all the unique courses offered that have at least one student enrolled. This will help them understand course popularity.
Tables:
students:student_id(integer, PRIMARY KEY),name(varchar(50))enrollments:enrollment_id(integer, PRIMARY KEY),student_id(integer),course_id(varchar(10))
Return the course_id of all distinct courses that appear in the enrollments table. The results should be ordered by course_id in ascending order.
Handle ties by ordering alphabetically. NULL course_id values should not be included in the result. An empty result set is possible if no enrollments exist.
Tables
CREATE TABLE students ( student_id integer PRIMARY KEY, name varchar(50) ); CREATE TABLE enrollments ( enrollment_id integer PRIMARY KEY, student_id integer REFERENCES students(student_id), course_id varchar(10) );
Example data
INSERT INTO students (student_id, name) VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie'), (4, 'David'); INSERT INTO enrollments (enrollment_id, student_id, course_id) VALUES (101, 1, 'CS101'), (102, 2, 'CS101'), (103, 1, 'MA202'), (104, 3, 'PH101'), (105, 4, 'CS101'), (106, 3, 'MA202'), (107, 2, 'CS303');
Your query is also checked on hidden datasets with different data.
Hints
-- Select all distinct course IDs
SELECT course_id
FROM enrollments
Your query runs on the example tables shown with the problem, then on hidden datasets when you submit.
Write standard SQL. MySQL habits work too: IFNULL, IF, YEAR(), DATE_FORMAT, GROUP_CONCAT, `backticks` and LIMIT 5, 10. It runs on PostgreSQL, so integer division keeps whole numbers (5 / 2 = 2): write 5.0 / 2 for 2.5.