SQL ORDER BY Clause | Complete Guide, Syntax, Examples and Practice

SQL ORDER BY Clause

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.


What is the ORDER BY Clause?

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.


Why Do We Need ORDER BY?

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.


Basic Syntax of ORDER BY

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.


ORDER BY Syntax with Sorting Direction

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.


Sample Student Table

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

Sorting Records in Ascending Order

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.

Example

SELECT *
FROM Student
ORDER BY Marks ASC;

The result will arrange students according to their marks, beginning with the lowest mark.

Expected Output

StudentName Marks
Amit 75
Rahul 82
Neha 88
Priya 91

Sorting Records in Descending Order

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.

Example

SELECT *
FROM Student
ORDER BY Marks DESC;

Expected Output

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.


Sorting Names Alphabetically

ORDER BY can be applied to character columns. For example, student names can be arranged alphabetically.

SELECT StudentName
FROM Student
ORDER BY StudentName ASC;

Output

StudentName
Amit
Neha
Priya
Rahul

The exact ordering of text can depend on the database's collation and character comparison rules.


Sorting Names in Reverse Alphabetical Order

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.


Sorting Numeric Columns

ORDER BY is frequently applied to numeric columns such as age, salary, marks, quantity, and price.

Example

SELECT StudentName, Age
FROM Student
ORDER BY Age ASC;

This query displays students from the youngest to the oldest according to the Age column.


Sorting Date Values

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

Example

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;

Sorting a Selected Set of Columns

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.


Sorting Using a Column Position

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;

ORDER BY with WHERE Clause

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.

Example

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.


ORDER BY with DISTINCT

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.


ORDER BY with Multiple Columns

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.

Example Output

StudentName Course Marks
Neha BCA 88
Rahul BCA 82
Priya B.Tech 91
Amit MCA 75

Using Different Directions for Multiple Columns

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.


ORDER BY with GROUP BY

GROUP BY creates groups of related rows. ORDER BY can then arrange the resulting groups according to a column or aggregate expression.

Example

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.


ORDER BY with Aggregate Functions

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.


ORDER BY with COUNT()

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.


ORDER BY with SUM()

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 with JOIN

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.


ORDER BY with Column Aliases

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.


ORDER BY with Calculated Expressions

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.


ORDER BY and NULL Values

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 with LIMIT

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.


ORDER BY with TOP in SQL Server

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.


ORDER BY with OFFSET and FETCH

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.


ORDER BY in Pagination

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.


ORDER BY with CASE Expression

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.


ORDER BY and Duplicate Values

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.


Practical Example: Employee Management System

EmployeeID EmployeeName Department Salary
1 Amit HR 40000
2 Neha IT 65000
3 Rohan Finance 55000

Query

SELECT EmployeeName, Salary
FROM Employee
ORDER BY Salary DESC;

The employee with the highest salary appears first.


Practical Example: Product Database

SELECT ProductName, Price
FROM Products
ORDER BY Price ASC;

This query creates a price-based listing beginning with the least expensive product.


Practical Example: Student Ranking

SELECT StudentName, Marks
FROM Student
ORDER BY Marks DESC;

The result can be used as the basic ordering for a marks-based ranking report.


Real-World Use of ORDER BY in Banking

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.


Real-World Use of ORDER BY in E-Commerce

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.


Real-World Use of ORDER BY for Recent Records

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.


ORDER BY Execution and Query Processing

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.


Performance Considerations for ORDER BY

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.


How to Improve ORDER BY Performance?


Common Mistakes While Using ORDER BY


ORDER BY vs WHERE

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 vs GROUP BY

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.

Advantages of ORDER BY


Limitations and Considerations of ORDER BY


Best Practices for ORDER BY


SQL ORDER BY Interview Questions and Answers

1. What is ORDER BY in SQL?

ORDER BY is a SQL clause used to arrange the rows in a query result according to one or more expressions.

2. What is the default direction of ORDER BY?

When no direction is specified, ascending order is normally used.

3. Which keyword is used for ascending order?

ASC.

4. Which keyword is used for descending order?

DESC.

5. Can ORDER BY sort text?

Yes. Text values can be sorted according to the database's collation rules.

6. Can ORDER BY sort numbers?

Yes. Numeric columns can be arranged from low to high or high to low.

7. Can dates be sorted using ORDER BY?

Yes. Date and time columns can be ordered chronologically.

8. Can multiple columns be used in ORDER BY?

Yes. Multiple sorting expressions can be separated with commas.

9. What happens when two rows have the same sorting value?

The database may not provide a predictable relative order unless an additional sorting expression is supplied.

10. Can ORDER BY be used with WHERE?

Yes. WHERE can filter the rows and ORDER BY can arrange the remaining results.

11. Can ORDER BY be used with GROUP BY?

Yes. Grouped results can be sorted using ORDER BY.

12. Can ORDER BY work with aggregate functions?

Yes. Results generated by COUNT(), SUM(), AVG(), MIN(), and MAX() can be sorted.

13. Can ORDER BY be used with JOIN?

Yes. A result produced from multiple joined tables can be sorted.

14. Can an alias be used in ORDER BY?

In many SQL implementations, SELECT-list aliases can be referenced by ORDER BY.

15. Can calculated values be sorted?

Yes. ORDER BY can sort using expressions and calculated values.

16. What is the use of ORDER BY with LIMIT?

It can be used to obtain a limited number of rows after arranging them according to a desired order.

17. What is TOP?

TOP is a SQL Server feature used to restrict the number of rows returned by a query.

18. Does ORDER BY change the data stored in a table?

No. It changes the order of the query result, not the stored data itself.

19. Can ORDER BY affect query performance?

Yes. Sorting a large number of rows can require additional processing and resources.

20. Why should WHERE sometimes be used before ORDER BY?

Filtering unnecessary rows before sorting can reduce the amount of data that needs to be ordered.

21. Can ORDER BY use column numbers?

Some SQL systems allow ordinal positions such as ORDER BY 2, although explicit column names are generally clearer.

22. How can equal values be given a predictable order?

Add one or more secondary columns to ORDER BY.

23. Does every database handle NULL values in the same way?

No. The position of NULL values in sorted output can differ between database systems.

24. Is ORDER BY mandatory with SELECT?

No. It is optional unless a specific ordering of the result is required.

25. What is a common use of ORDER BY?

Common uses include rankings, price sorting, alphabetical lists, date-based reports, salary reports, and pagination.


Complete Practical Example

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.


Conclusion

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.


Quick Revision

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
← Previous: WHERE Clause Next: GROUP BY →
Home Visit Our YouTube Channel