Data Sorting in SQL: Ascending & Descending Order

Date Published: 14/03/2020 Published By: JaiSchool

When we want to display data in ascending or descending order, we use SORT BY in the SQL query. Use the ASC keyword for ascending order and DESC for descending order.

The data display order may be ascending & descending.

The SQL query for sorting data

SELECT column FROM table ORDER BY column;

Give column name after ORDER BY for sorting data according to.

SQL table to sorting data

Database Name = jai_school
Table Name = users

namestategendermon_income
RamUPMale50000
RahimMPMale20000
ShyamUPMale40000
AnitaUKFemale80000
JaiRJMale70000
RavinaDelhiFemale20000
AmanRJMale20000
RaviRJMale35000

Or Table Image-
sql table for sorting data

Show the table's data in ascending order by column

SELECT * FROM users ORDER BY name ASC;

Output:

order by asc

You don't always need to use ASC after the column name. By default, data is arranged in ascending order.

Descending order

SELECT * FROM users ORDER BY name DESC;

Output:

order by desc

Data sorting with where (conditional clause)

SELECT * FROM users WHERE mon_income="20000" ORDER BY name DESC;

Output:

sql sorting with where

Data sorting with a limit of rows to be displayed

SELECT * FROM users ORDER BY mon_income LIMIT 4;

Output:

sql sorting with limit

Read more about- SQL limit

Data sorting with limit and where (condition)

SELECT * FROM users WHERE state="RJ" ORDER BY mon_income LIMIT 2;

Output-

sql data sorting with where and limit

NOTE~ Sequence of writing a query that includes ORDER BY, LIMIT and WHERE (conditional clause) will be:

WHERE » ORDER BY » LIMIT


Either ASC or DESC keyword is written after the column name.

Publish A Comment

Leave a Reply

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