Preloader

ORDER BY Clause in SQL

SQL
SQL Tutorials

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

idnameagecitymarks
1Rahul20Delhi85
2Neha18Mumbai92
3Amit22Delhi78
4Priya19Pune88
5Karan21Mumbai90

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!

You may also like...

Leave a Reply

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