sql server union order by clause

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:
[sql]
select 1 AS Column1,’c’ AS Column2
union
select 2,’b’
union
select 3,’a’
ORDER BY Column2
[/sql]
result:
Column1 Column2
———– ——-
3 a
2 b
1 c

(3 row(s) affected)

with out order by claues:
[sql]
select 1 AS Column1,’c’ AS Column2
union
select 2,’b’
union
select 3,’a’
[/sql]
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

Leave a Reply

Your email address will not be published. Required fields are marked *