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|DESCsorts the result.- Many columns are separated by commas.
- Next: LIMIT.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |