SQL ORDER BY Clause
The ORDER BY clause is used to sort the result of a SELECT query. By default, SQL does not guarantee any particular order for rows — they may appear in any sequence. ORDER BY allows specifying how the results should be arranged.
Think of it like sorting a list of student names alphabetically, or arranging exam scores from highest to lowest.
The Reference Table
| StudentID | StudentName | Age | City |
|---|---|---|---|
| 1 | Ravi Sharma | 20 | Delhi |
| 2 | Priya Mehta | 22 | Mumbai |
| 3 | Arjun Nair | 19 | Chennai |
| 4 | Sneha Kapoor | 21 | Pune |
| 5 | Rohit Das | 23 | Kolkata |
Syntax
SELECT column1, column2
FROM table_name
ORDER BY column_name ASC | DESC;ASC stands for ascending order (smallest to largest, A to Z). DESC stands for descending order (largest to smallest, Z to A). If neither is specified, ASC is the default.
Sorting by a Numeric Column
SELECT * FROM Students
ORDER BY Age ASC;Result: Students sorted from youngest to oldest.
| StudentID | StudentName | Age | City |
|---|---|---|---|
| 3 | Arjun Nair | 19 | Chennai |
| 1 | Ravi Sharma | 20 | Delhi |
| 4 | Sneha Kapoor | 21 | Pune |
| 2 | Priya Mehta | 22 | Mumbai |
| 5 | Rohit Das | 23 | Kolkata |
Sorting in Descending Order
SELECT * FROM Students
ORDER BY Age DESC;Result: Students sorted from oldest to youngest (23, 22, 21, 20, 19).
Sorting by a Text Column (Alphabetical)
SELECT StudentName, City FROM Students
ORDER BY StudentName ASC;Result: Names sorted A to Z — Arjun, Priya, Ravi, Rohit, Sneha.
Sorting by Multiple Columns
When two rows have the same value in the first sort column, the second column breaks the tie.
SELECT StudentName, Age, City FROM Students
ORDER BY City ASC, Age DESC;This sorts first by City alphabetically, and within the same city, sorts by Age from highest to lowest.
Combining ORDER BY With WHERE
SELECT StudentName, Age FROM Students
WHERE Age > 19
ORDER BY Age ASC;This filters students older than 19 and then sorts them by age in ascending order.
Key Points to Remember
ASCis ascending (default),DESCis descending.- Multiple columns can be used for sorting — separate them with commas.
ORDER BYalways comes afterWHEREin the query.
