MySQL ORDER BY

ORDER BY sorts the result. The default is ascending (ASC): A to Z and small to big. Use DESC for the opposite.

SELECT name, marks FROM students ORDER BY marks DESC;
Result
name marks
Maria 92
Asha 88
Robin 85
John 78
Vikram 65
Neha 45

SELECT name FROM students ORDER BY name;
Result
name
Asha
John
Maria
Neha
Robin
Vikram


Sort by more than one column

If two rows have the same value in the first column, MySQL looks at the second one.

SELECT name, city, marks FROM students
ORDER BY city ASC, marks DESC;
Result
name city marks
Robin Delhi 85
Vikram Delhi 65
Asha Jaipur 88
Maria Mumbai 92
Neha Mumbai 45
John Pune 78

The cities are in A to Z order, and inside each city the highest marks come first.


With WHERE

ORDER BY comes after WHERE.

SELECT name, marks FROM students WHERE marks > 60 ORDER BY marks;
Result
name marks
Vikram 65
John 78
Robin 85
Asha 88
Maria 92

Note: Without ORDER BY MySQL does not promise any order of rows. If the order matters, always write it.

Summary

  • ORDER BY column ASC|DESC sorts the result.
  • Many columns are separated by commas.
  • Next: LIMIT.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a query to get data of selected columns from a table
Write a query to select the student with the maximum marks
Write a query to select top 3 students by marks
Write a query to select the rows if a column has no value
Write a query to find the names of students that begin with ‘A’
Write a query to fetch the top 2 records
Interview Questions & Answers
How to select Top 10 records in MySQL?
Write a MySQL query to select students with less than 50% marks
Write a MySQL query to select students with marks between 70 and 80
Write a query to fetch top N records
Write a query to find the names of employees that begin with ‘S’
Write a query to select if column has no/empty value
What is NULL in MySQL? Is NULL the same as 0 or an empty string?