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

StudentIDStudentNameAgeCity
1Ravi Sharma20Delhi
2Priya Mehta22Mumbai
3Arjun Nair19Chennai
4Sneha Kapoor21Pune
5Rohit Das23Kolkata

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.

StudentIDStudentNameAgeCity
3Arjun Nair19Chennai
1Ravi Sharma20Delhi
4Sneha Kapoor21Pune
2Priya Mehta22Mumbai
5Rohit Das23Kolkata

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

  • ASC is ascending (default), DESC is descending.
  • Multiple columns can be used for sorting — separate them with commas.
  • ORDER BY always comes after WHERE in the query.

Leave a Comment

Your email address will not be published. Required fields are marked *