Katkat

Rank Departments by Student Count

OracleSoftware Engineer · Onsite

Last updated

Tests SQL proficiency in outer joins, aggregation with null handling, and deterministic multi-column sorting.

Rank Departments by Student Count

In a university management system, you need to generate a report showing the number of enrolled students per department. The report must be comprehensive, listing all registered departments regardless of whether they currently have enrolled students.

Schema

You are provided with two tables: departments and students.

-- Table: departments
-- dept_id: Primary key uniquely identifying each department
-- dept_name: Name of the department
CREATE TABLE departments (
    dept_id INT PRIMARY KEY,
    dept_name VARCHAR(100) NOT NULL
);

-- Table: students
-- student_id: Primary key uniquely identifying each student
-- student_name: Name of the student
-- dept_id: Foreign key referencing departments(dept_id)
CREATE TABLE students (
    student_id INT PRIMARY KEY,
    student_name VARCHAR(100) NOT NULL,
    dept_id INT
);

Task

Write a SQL query that returns the department ID, department name, and total count of enrolled students for every department.

  • The output columns must be named: dept_id, dept_name, and student_count.
  • Departments with zero students must be included and display a student_count of 0.
  • Results must be ordered:
    1. student_count in descending order
    2. dept_name in ascending order (alphabetical)
    3. dept_id in ascending order (numeric tie-breaker)

Example

Input:

departments

dept_iddept_name
1Computer Science
2Mathematics
3Philosophy
4Physics

students

student_idstudent_namedept_id
101Alice1
102Bob1
103Charlie2
104Diana4
105Evan1

Output:

dept_iddept_namestudent_count
1Computer Science3
2Mathematics1
4Physics1
3Philosophy0

Explanation:

  • Computer Science has 3 students.
  • Mathematics and Physics both have 1 student, so they are ordered alphabetically by dept_name ('Mathematics' before 'Physics').
  • Philosophy has no students and correctly shows a count of 0.

Hints

Hint 1

Use a LEFT JOIN starting from the departments table to ensure departments without students are preserved.

Hint 2

Be careful when using COUNT(*): aggregating over an outer join with COUNT(*) will count NULL rows as 1, so count a non-null column from the students table instead.

Hint 3

Include dept_id and dept_name in your GROUP BY clause, and explicitly list all three criteria in your ORDER BY clause.

Follow-up questions

  • How would you assign an explicit ranking (e.g., DENSE_RANK or RANK) to each department based on the student count?
  • What indexes would you create on both tables to optimize query performance at scale?
  • How would the query change if students could be enrolled in multiple departments via a many-to-many relationship table?