sql server union order by clause

Posted on : 27-04-2012 | By : Devi Prasad | In : SQL Server Basics, T-SQL Code Examples

Share:

0


using union/union all with order by clause in sql server.

In order to order the results of a union statement add order by clause with the column names corresponding to first select statement.
If you are using alias names use the alias column names used in the first select statement

Below example shows how to use union with order by clause in sql server:

select 1 AS Column1,'c' AS Column2
union
select 2,'b'
union
select 3,'a'
ORDER BY Column2

result:
Column1 Column2
———– ——-
3 a
2 b
1 c

(3 row(s) affected)

with out order by claues:

select 1 AS Column1,'c' AS Column2
union
select 2,'b'
union
select 3,'a'

result:
Column1 Column2
———– ——-
1 c
2 b
3 a

(3 row(s) affected)

Applicable to: SQL Server 2000, SQL Server 2005, SQL Server 2008, SQL Server 2008 r2, SQL Server 2012

(Visited 33 times, 1 visits today)



References : Devi Prasad (sqlserverlearner.com)

Need Help On SQL Server?

Cannot Find Solution to your problem (or) If you are looking for some help on SQL Server. Dont worry Click Here to Post your question and solve your issue.


Do you like my blog?

If you liked reading this blog, please help spread the word by sharing this blog with your friends.




Write a comment



Tags: , , , , , , , , ,