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
name | state | gender | mon_income |
---|---|---|---|
Ram | UP | Male | 50000 |
Rahim | MP | Male | 20000 |
Shyam | UP | Male | 40000 |
Anita | UK | Female | 80000 |
Jai | RJ | Male | 70000 |
Ravina | Delhi | Female | 20000 |
Aman | RJ | Male | 20000 |
Ravi | RJ | Male | 35000 |
Or Table Image-
Show the table's data in ascending order by column
SELECT * FROM users ORDER BY name ASC;
Output:

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:

Data sorting with where (conditional clause)
SELECT * FROM users WHERE mon_income="20000" ORDER BY name DESC;
Output:

Data sorting with a limit of rows to be displayed
SELECT * FROM users ORDER BY mon_income LIMIT 4;
Output:

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-

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