ORDER BY Clause in SQL
The ORDER BY clause in SQL is used to sort records in a specific order. It helps you display query results in a clean and meaningful way. When you work with large tables, sorting data becomes important because it makes results easier to read and compare.
In real world applications, developers use the ORDER BY in SQL to organize reports, rankings, and filtered data clearly.
By default, SQL sorts data in ascending order. However, you can also sort data in descending order when needed.
Sample Table Used for Sorting Data
Let us use the following table for all examples.
students
| id | name | age | city | marks |
|---|---|---|---|---|
| 1 | Rahul | 20 | Delhi | 85 |
| 2 | Neha | 18 | Mumbai | 92 |
| 3 | Amit | 22 | Delhi | 78 |
| 4 | Priya | 19 | Pune | 88 |
| 5 | Karan | 21 | Mumbai | 90 |
ORDER BY in SQL with Ascending Order
The ORDER BY in SQL sorts data in ascending order by default. You can also use the ASC keyword to make this clear.
SELECT*FROM studentsORDERBY marks ASC;
This query sorts students by marks from lowest to highest.
Sorting Records in Descending Order
To sort data from highest to lowest, use DESC.
SELECT*FROM studentsORDERBY marks DESC;
This query displays students with the highest marks first.
Sorting Text Data Like Names or Cities
You can also use sorting on text columns such as name or city.
SELECT*FROM studentsORDERBY name;
This sorts student names in alphabetical order.
Sorting by Multiple Columns
The ORDER BY clause allows sorting using more than one column.
SELECT*FROM studentsORDERBY city ASC, marks DESC;
First, students are grouped by city. Then, students in the same city are sorted by marks.
ORDER BY Clause in SQL with WHERE Condition
You can combine filtering and sorting in a single query using the ORDER BY clause in SQL.
SELECT*FROM studentsWHERE city ='Delhi'ORDERBY marks DESC;
This query filters Delhi students and then sorts them by marks.
Why ORDER BY Clause in SQL Is Important
The ORDER BY in SQL helps you
organize query results
analyze data easily
create readable reports
write better SQL queries
Summary
The ORDER BY clause in SQL is used to sort data.
ASC sorts data in ascending order.
DESC sorts data in descending order.
You can sort using one or multiple columns.
This makes the ORDER BY clause in SQL an essential part of writing effective SQL queries.
Check out our resources!
- Bootstrap Templates: Explore our Bootstrap Projects section.
- Free E-Books: Download your Free E-Books here.


