Introduction

This article mainly explains the ORDER BY clause present in MySQL. ORDER BY clause is generally used to sort the fetched data from the query in ascending or descending order for one or more columns from the database table.

The default order used in the ORDER BY clause is Ascending order, if you want to sort the data in descending order, then the keyword DESC is used while using the ORDER BY clause.

ORDER BY clause can be used on one or more than one columns in the database table. To understand more about the ORDER BY clause, let's look at the below examples:

Example 1

This example explains  the ORDER BY clause is used on a single column in the database table:

Consider the below table of information on Student's data:

The query is to arrange the names of students according to the ascending order of the S-Name( Student’s Name):

The fetched data is arranged according to ascending order and the output is shown below:

Output:


Example 2

This example explains the sorting of more than one column using the ORDER BY clause:

The information of students is given below:

The query is to fetch the data of the student’s alphabetical order and by having the highest marks in Physics subject:

The fetched data is shown below:

Output:

In the above output, we can observe that first the result is sorted in ascending order according to S-Name. There are multiple rows of the same Phy_Marks. Now, these are sorted further according to descending order of Physics marks.  

Data sorting can be done using the column name or attribute name from the database table but can also be done by specifying a column number instead of a column name.

Example 3

The below-mentioned example clearly explains the usage of column numbers.

The information about the Department is shown below:

The query is to sort the data in the database table according to the Dep_ID:

The output obtained is as follows:

write your code here: Coding Playground

Conclusion

SQL ORDER BY clause is used to sort the particular column of the table in increasing or decreasing order by using ASC and DESC keywords in the syntax of ORDER BY clause.