Phoenix
Phoenix

Reputation: 263

Can we perform order by on more than 2 columns in SQL Server

Bit confused if we can perform order by on more than two columns.

Here is the result:-

Select * 
from orderbytest 
order by FName desc, LName desc, YearOfBirth desc

Resulting output:

FName     LName         YearOfBirth
------------------------------------
Thomas    More          1478
Thomas    Jefferson     1826
Thomas    Alva Edison   1847
Benjamin  White         1600
Benjamin  Franklin      1706

Upvotes: 1

Views: 408

Answers (4)

Ashish Kumar
Ashish Kumar

Reputation: 157

Yes you can. try this query for understanding order by more then one column:

select *
from
(
    select 'ashish' col1,1 col2
    union all
    select 'ashish',3
)base
order by col1 asc, col2 desc

Upvotes: 0

Tharif
Tharif

Reputation: 13971

This will group in Descending order of FName , LName , YearOfBirth

SELECT        FName, LName, YearOfBirth
FROM            orderbytest
ORDER BY FName DESC, LName DESC, YearOfBirth DESC

For ascending order :

SELECT        FName, LName, YearOfBirth
FROM            orderbytest
ORDER BY FName , LName , YearOfBirth 

Upvotes: 0

sulhadin
sulhadin

Reputation: 516

Yes you can perform however you like Just like Grouping.

here;

Select * from orderbytest order by FName ,LName asc,YearOfBirth desc

Not that, when you do not write any keyword after a field the result will list in the default order.

Upvotes: 0

Mureinik
Mureinik

Reputation: 311418

Short answer - yes.

When applying multiple order by expressions the results are sorted by the first one. When multiple rows have the same value in the first order by expression, they are sorted internally by the second one. When multiple rows have the same value in the first and second order by expressions they are sorted by the third one, and so on.

Here, all your rows have a unique combination of the first two expressions, so the third one, while still valid, is inconsequential.

Upvotes: 1

Related Questions