Write a query to show the count of students by city

Description: Show the number of students in each city.

Tables: the exercises use the students (id, name, city, marks, course_id) and courses (id, course_name) tables, with the data from our MySQL INSERT chapter. The students are: Robin (Delhi, 85), Maria (Mumbai, 92), John (Pune, 78), Asha (Jaipur, 88), Vikram (Delhi, 65), Neha (Mumbai, 45).

Hint:

  • Use COUNT(*).
  • Group the rows with GROUP BY city.

MySQL query for the count of students by city

SELECT city, COUNT(*) AS total_students
FROM students
GROUP BY city
ORDER BY city;

Output:

Tutorials Class - Output Window
city total_students
Delhi 2
Jaipur 1
Mumbai 2
Pune 1

How it works

  • GROUP BY city makes one group for each city.
  • COUNT(*) counts the rows of each group.

Read GROUP BY and HAVING.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.