Ever thought of how can we arrange our columns in some particular order? Or thought of how to get random information?
If the answer to these questions is NO then this is the right article for you.
In this article, we'll be discussing,
- When to use order by clause?
- Syntax of order by clause
- Sorting a column using order by
- Getting random information using order by
- Sorting multiple columns using order by
Let's begin.
When to use order by clause
Order by clause is used to sort the fetched data either in ascending or descending order. When we execute our select statement we get unsorted results as our output. In order to arrange them in a sorted way - order by comes in picture.
Syntax of Order by clause
SELECT * FROM table_name ORDER BY column_name
- * = It is used for all columns in your table.
- table_name = name of your table where the information is stored in form of rows and columns
- Order By = Clause used to sort your column
- column_name = Name of your column which you want to sort
By Default Order by sorts the column in ascending order. If you want to sort your column in descending order then you have to explicitly use the keyword "DESC".
Sorting a column using order by
Consider you have student table of a particular standard say 7th having columns as roll no, name, city, Marks
| Roll_No | Name | State | Marks |
| 101 | Akanksha | Punjab | 95 |
| 102 | Isha | Haryana | 80 |
| 103 | Amit | MP | 100 |
| 104 | Rajat | UP | 89 |
| 105 | Amit | Punjab | 97 |
This is our student of standard 7th data. Now we want to fetch student data in terms of their highest marks score.
Then,
SELECT NAME FROM STUDENT ORDER BY MARKS DESC;
Result
| Roll_No | Name | State | Marks out of 100 |
| 103 | Amit | MP | 100 |
| 105 | Amit | Punjab | 97 |
| 101 | Akanksha | Punjab | 95 |
| 104 | Rajat | UP | 89 |
| 102 | Isha | Haryana | 80 |

Join the conversation! Your thoughts help the community grow.