When a SQL query retrieves records from a table, the database does not promise that the rows will appear in a particular order unless the query specifically requests sorting. The ORDER BY clause is used when the result needs to be presented in a meaningful sequence.
For example, a college application may need to display students according to their marks, an online shopping website may arrange products from the lowest price to the highest price, and an employee portal may list workers alphabetically by name. SQL ORDER BY makes these types of arrangements possible.
ORDER BY can sort values in ascending or descending order and can also use several columns when a single sorting rule is not enough. It is therefore an important part of SQL reporting, data analysis, dashboards, and database applications.
The ORDER BY clause tells the database how the rows returned by a query should be arranged. It is generally used with SELECT statements and can sort the result according to one or more columns.
For numeric values, ascending order normally moves from the smaller value to the larger value. For text values, it generally follows the database's configured collation rules. Descending order reverses the requested sequence.
It is important to understand that ORDER BY changes the order of the result set; it does not rearrange the physical records stored inside the table.
Database tables can contain a large number of records. Presenting those records without a meaningful order can make the result difficult to read or analyze. ORDER BY allows applications and users to control how retrieved information is presented.
The general form of the ORDER BY clause is:
SELECT column_name FROM table_name ORDER BY column_name;
If neither ASC nor DESC is written, most SQL implementations treat the ordering as ascending.
SELECT column_name FROM table_name ORDER BY column_name ASC;
For descending order:
SELECT column_name FROM table_name ORDER BY column_name DESC;
Here, ASC means ascending and DESC means descending.
Throughout this tutorial, we will use a simple Student table to understand different ORDER BY examples.
| StudentID | StudentName | Course | Age | Marks |
|---|---|---|---|---|
| 101 | Rahul | BCA | 20 | 82 |
| 102 | Priya | B.Tech | 21 | 91 |
| 103 | Amit | MCA | 22 | 75 |
| 104 | Neha | BCA | 19 | 88 |
Ascending sorting arranges values from lower to higher or, for many text values, from A toward Z. The keyword ASC is used to explicitly request this order.
SELECT * FROM Student ORDER BY Marks ASC;
The result will arrange students according to their marks, beginning with the lowest mark.
| StudentName | Marks |
|---|---|
| Amit | 75 |
| Rahul | 82 |
| Neha | 88 |
| Priya | 91 |
Descending sorting reverses the sequence. Numeric values generally move from larger to smaller, while text values are arranged according to the reverse of the applicable collation order.
SELECT * FROM Student ORDER BY Marks DESC;
| StudentName | Marks |
|---|---|
| Priya | 91 |
| Neha | 88 |
| Rahul | 82 |
| Amit | 75 |
This type of sorting is useful when the highest values should appear first, such as when preparing a student ranking.
ORDER BY can be applied to character columns. For example, student names can be arranged alphabetically.
SELECT StudentName FROM Student ORDER BY StudentName ASC;
| StudentName |
|---|
| Amit |
| Neha |
| Priya |
| Rahul |
The exact ordering of text can depend on the database's collation and character comparison rules.
To display names in descending alphabetical order, use DESC.
SELECT StudentName FROM Student ORDER BY StudentName DESC;
The result will start with names that occur later in the applicable sorting order.
ORDER BY is frequently applied to numeric columns such as age, salary, marks, quantity, and price.
SELECT StudentName, Age FROM Student ORDER BY Age ASC;
This query displays students from the youngest to the oldest according to the Age column.
Date columns can also be ordered chronologically. This is useful for invoices, registrations, transactions, appointments, and orders.
| OrderID | OrderDate |
|---|---|
| 1 | 2026-07-10 |
| 2 | 2026-07-15 |
| 3 | 2026-07-05 |
SELECT * FROM Orders ORDER BY OrderDate ASC;
The oldest date will appear before later dates.
To see the newest records first:
SELECT * FROM Orders ORDER BY OrderDate DESC;
ORDER BY does not require every selected column to be displayed. A query can return only the information required by the user while sorting the result using another selected column.
SELECT StudentName, Marks FROM Student ORDER BY Marks DESC;
Here, only StudentName and Marks are shown, and the marks determine the order.
Some SQL systems allow the position of a selected column to be used in ORDER BY.
SELECT StudentID, StudentName, Marks FROM Student ORDER BY 3 DESC;
The number 3 refers to the third expression in the SELECT list, which is Marks.
Although this technique may work, using the actual column name is usually easier to read and maintain:
SELECT StudentID, StudentName, Marks FROM Student ORDER BY Marks DESC;
WHERE and ORDER BY are commonly combined. WHERE first limits the rows that are relevant to the query, and ORDER BY arranges those returned rows.
SELECT StudentName, Marks FROM Student WHERE Marks >= 80 ORDER BY Marks DESC;
The query first selects students with at least 80 marks and then places the highest marks first.
DISTINCT eliminates duplicate result values. ORDER BY can then be used to arrange those unique values.
SELECT DISTINCT Course FROM Student ORDER BY Course ASC;
The result contains each course only once and displays the course names in sorted order.
A single sorting column may not always provide enough control. SQL allows multiple expressions in ORDER BY.
SELECT StudentName, Course, Marks FROM Student ORDER BY Course ASC, Marks DESC;
The database first compares Course values. If two or more rows have the same course, their Marks values are then compared according to the second sorting rule.
| StudentName | Course | Marks |
|---|---|---|
| Neha | BCA | 88 |
| Rahul | BCA | 82 |
| Priya | B.Tech | 91 |
| Amit | MCA | 75 |
Every ORDER BY expression can have its own direction.
SELECT EmployeeName, Department, Salary FROM Employee ORDER BY Department ASC, Salary DESC;
In this example, departments are arranged alphabetically. Employees belonging to the same department are then ordered from the highest salary to the lowest salary.
GROUP BY creates groups of related rows. ORDER BY can then arrange the resulting groups according to a column or aggregate expression.
SELECT Course, COUNT(*) AS TotalStudents FROM Student GROUP BY Course ORDER BY TotalStudents DESC;
The course with the largest number of students will appear first.
Aggregate functions such as COUNT(), SUM(), AVG(), MIN(), and MAX() produce calculated values. ORDER BY can sort the resulting summaries.
SELECT Department,
AVG(Salary) AS AverageSalary
FROM Employee
GROUP BY Department
ORDER BY AverageSalary DESC;
This query places departments with higher average salaries before departments with lower average salaries.
SELECT Course,
COUNT(*) AS StudentCount
FROM Student
GROUP BY Course
ORDER BY StudentCount DESC;
This is useful when a report needs to show the most populated courses first.
SELECT Department,
SUM(Salary) AS TotalSalary
FROM Employee
GROUP BY Department
ORDER BY TotalSalary DESC;
Departments are arranged according to their total salary expenditure.
ORDER BY can also organize results produced by JOIN operations. This is useful when information is collected from related tables.
SELECT Student.StudentName,
Course.CourseName
FROM Student
INNER JOIN Course
ON Student.CourseID = Course.CourseID
ORDER BY Student.StudentName ASC;
The joined records are displayed according to the student name.
An alias can provide a convenient name for a selected expression. In database systems that permit it in the query context, the alias can also be referenced by ORDER BY.
SELECT StudentName,
Marks AS Score
FROM Student
ORDER BY Score DESC;
The result is sorted according to the calculated output column named Score.
SQL can sort results according to a calculated expression rather than a stored column.
SELECT ProductName,
Price,
Quantity,
Price * Quantity AS TotalValue
FROM Products
ORDER BY TotalValue DESC;
Products with a greater calculated inventory value appear first.
NULL represents the absence of a known value. When a column contains NULL values, their position in an ordered result can differ between database systems.
SELECT EmployeeName, Bonus FROM Employee ORDER BY Bonus ASC;
The database determines where NULL values appear according to its SQL implementation and ordering rules. When NULL placement matters, use the database-specific features available for controlling it.
ORDER BY is especially useful when combined with LIMIT because it can identify the highest or lowest records before restricting the number of rows returned.
SELECT StudentName, Marks FROM Student ORDER BY Marks DESC LIMIT 5;
In systems supporting LIMIT, this query returns the five highest-scoring students.
SQL Server commonly uses TOP when a query needs a limited number of rows.
SELECT TOP 5 StudentName, Marks FROM Student ORDER BY Marks DESC;
The sorting is performed according to Marks, and the query returns the top five rows.
Some database systems support OFFSET and FETCH for pagination. They are useful when an application needs to display records page by page.
SELECT StudentName, Marks FROM Student ORDER BY Marks DESC OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY;
The exact pagination syntax can vary between database systems, so the documentation of the selected database should be consulted.
Pagination is commonly used in websites where displaying thousands of records on a single page would be inconvenient. A stable ORDER BY condition helps maintain a predictable sequence while pages are retrieved.
SELECT StudentID, StudentName, Marks FROM Student ORDER BY StudentID ASC LIMIT 10 OFFSET 20;
In databases supporting this syntax, the query skips the first 20 rows and returns the next 10 according to StudentID order.
A CASE expression can be used when records need a custom business-defined priority instead of normal alphabetical or numerical sorting.
SELECT StudentName, Course
FROM Student
ORDER BY
CASE
WHEN Course = 'B.Tech' THEN 1
WHEN Course = 'MCA' THEN 2
WHEN Course = 'BCA' THEN 3
ELSE 4
END;
This example places B.Tech students first, followed by MCA and then BCA students.
When multiple records have the same value in the primary sorting column, their relative order may not be predictable unless an additional sorting expression is supplied.
For example:
SELECT StudentName, Marks FROM Student ORDER BY Marks DESC;
If several students have identical marks, add another column to establish a secondary order.
SELECT StudentName, Marks FROM Student ORDER BY Marks DESC, StudentName ASC;
Now equal marks are further ordered by student name.
| EmployeeID | EmployeeName | Department | Salary |
|---|---|---|---|
| 1 | Amit | HR | 40000 |
| 2 | Neha | IT | 65000 |
| 3 | Rohan | Finance | 55000 |
SELECT EmployeeName, Salary FROM Employee ORDER BY Salary DESC;
The employee with the highest salary appears first.
SELECT ProductName, Price FROM Products ORDER BY Price ASC;
This query creates a price-based listing beginning with the least expensive product.
SELECT StudentName, Marks FROM Student ORDER BY Marks DESC;
The result can be used as the basic ordering for a marks-based ranking report.
A banking application may need to display accounts according to their current balance.
SELECT CustomerName, Balance FROM Accounts ORDER BY Balance DESC;
Accounts with larger balances are displayed first.
An online shopping application may offer users options such as "Price: Low to High" or "Price: High to Low".
SELECT ProductName, Price FROM Products ORDER BY Price ASC;
The query implements the low-to-high price ordering.
Applications often need the newest records first, such as recently created orders or latest transactions.
SELECT OrderID, OrderDate FROM Orders ORDER BY OrderDate DESC;
More recent dates appear before older dates.
In a simplified view of query processing, filtering and grouping are handled before the final result is sorted. The exact internal execution plan is chosen by the database optimizer and may vary according to indexes, statistics, query structure, and the database engine.
For learning purposes, a common logical order of SQL clauses is:
FROM WHERE GROUP BY HAVING SELECT ORDER BY LIMIT / FETCH
This logical sequence helps students understand why ORDER BY operates on the result produced by earlier stages of the query.
Sorting can require significant processing when a query works with a large number of rows. The database may need to compare many values before producing the final ordered result.
The actual performance depends on the database engine, indexes, query structure, available memory, data distribution, and the number of rows being processed.
| ORDER BY | WHERE |
|---|---|
| Sorts the result. | Filters rows. |
| Controls output sequence. | Controls which rows qualify. |
| Uses ASC or DESC. | Uses conditions and operators. |
| Does not normally remove rows by itself. | Can exclude rows from the result. |
| ORDER BY | GROUP BY |
|---|---|
| Arranges result rows. | Creates groups of rows. |
| Used mainly for sorting. | Often used with aggregate functions. |
| Supports ASC and DESC. | Organizes records according to grouping expressions. |
ORDER BY is a SQL clause used to arrange the rows in a query result according to one or more expressions.
When no direction is specified, ascending order is normally used.
ASC.
DESC.
Yes. Text values can be sorted according to the database's collation rules.
Yes. Numeric columns can be arranged from low to high or high to low.
Yes. Date and time columns can be ordered chronologically.
Yes. Multiple sorting expressions can be separated with commas.
The database may not provide a predictable relative order unless an additional sorting expression is supplied.
Yes. WHERE can filter the rows and ORDER BY can arrange the remaining results.
Yes. Grouped results can be sorted using ORDER BY.
Yes. Results generated by COUNT(), SUM(), AVG(), MIN(), and MAX() can be sorted.
Yes. A result produced from multiple joined tables can be sorted.
In many SQL implementations, SELECT-list aliases can be referenced by ORDER BY.
Yes. ORDER BY can sort using expressions and calculated values.
It can be used to obtain a limited number of rows after arranging them according to a desired order.
TOP is a SQL Server feature used to restrict the number of rows returned by a query.
No. It changes the order of the query result, not the stored data itself.
Yes. Sorting a large number of rows can require additional processing and resources.
Filtering unnecessary rows before sorting can reduce the amount of data that needs to be ordered.
Some SQL systems allow ordinal positions such as ORDER BY 2, although explicit column names are generally clearer.
Add one or more secondary columns to ORDER BY.
No. The position of NULL values in sorted output can differ between database systems.
No. It is optional unless a specific ordering of the result is required.
Common uses include rankings, price sorting, alphabetical lists, date-based reports, salary reports, and pagination.
The following example combines filtering, multiple selected columns, sorting, and a secondary ordering rule.
SELECT StudentName,
Course,
Marks
FROM Student
WHERE Marks >= 70
ORDER BY Marks DESC, StudentName ASC;
First, the query keeps students whose marks are at least 70. The qualifying students are then arranged from the highest marks to the lowest. If two students have the same marks, their names are used as the secondary sorting rule.
The SQL ORDER BY clause provides control over the sequence in which query results are presented. It can arrange numbers, text, dates, calculated expressions, grouped results, and data obtained through joins. Ascending and descending directions make it possible to create reports and application screens that match the user's requirements.
ORDER BY becomes even more useful when combined with WHERE, GROUP BY, aggregate functions, JOIN, DISTINCT, LIMIT, TOP, and pagination techniques. For large databases, thoughtful filtering, suitable indexing, and efficient query design can help reduce unnecessary sorting work.
For SQL learners, understanding ORDER BY is an important step toward writing practical database queries. It is widely used in academic projects, interviews, reporting systems, websites, business applications, and data analysis.
| Concept | Purpose |
|---|---|
| ORDER BY | Sorts query results |
| ASC | Ascending order |
| DESC | Descending order |
| Multiple Columns | Provides primary and secondary sorting |
| WHERE + ORDER BY | Filters and then sorts records |
| GROUP BY + ORDER BY | Groups data and sorts grouped results |
| LIMIT + ORDER BY | Returns a limited portion of an ordered result |
| TOP + ORDER BY | Returns selected top rows in SQL Server |