Write a query to fetch the top 2 records

Description: Fetch the 2 students with the highest marks. Then think how to fetch the top N.

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:

  • Sort first, then limit.

MySQL query for the top 2 records

SELECT * FROM students
ORDER BY marks DESC
LIMIT 2;

Output:

Tutorials Class - Output Window
id name city marks course_id
2 Maria Mumbai 92 2
4 Asha Jaipur 88 3

How it works

  • Change the number after LIMIT to get the top N.
  • Without ORDER BY the rows are not guaranteed to be the “top” ones.

Read MySQL LIMIT.


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