Order By

If we want to sort the data on the particular column in that case we use order by command. We can sort data either in ascending order or in descending order. By default order by command sorts data in ascending order.

Example of Order By

Check the data of following table:-

		
order by example

		Figure 1

		

Suppose I want to sort data according to the gender then I will use the following query:-

		
		select * from Enqdata order by gender
		Note:-by default it sorts data in ascending order.
		
		

After running this query it will show result as follows:-

		
order by output

		Figure 2
		
		

If we want to sort data in descending order then we run the following query:-

		
select * from Enqdata order by gender desc
		
		

sorting on the basis of more than one column

suppose if you want to sort the data on more than one column then we run the following query:-

		
select * from Enqdata order by gender, name

select * from Enqdata order by gender desc, name

		
		

In the query it will first sort data on gender basis in ascending order and after that it will sort it according to name.

But in second query it will first sort data on gender basis in descending order and after that it will sort it according to name in ascending order.

After running these queries you will see the difference.

Sorting by passing number instead of column name

Sql server also supports column count in sorting. It means instead of passing column name to the order by we can pass number of column.

For example

If we run following query we will get complete data

		
Select * from enqdata

		
		
		
order by by column number

		Figure 3
		
		

In this result id column number is 1, name is 2, gender is 3 and enq_type is 4.

So let’s say I need to sort data by name so I can use following query

		
select * from enqdata order by 2

		
		

now execute it and you will find following output: -

		
		
order by by column number output

		Figure 4
		
		

Email Address

For any query you can send mail at info@techaltum.com
Thanks