There are times when developer want top and bottom query of
the UNION ALL resultset sorted independently, like this
select Columns from table1 order by Columns
union all
select Columns from tabbe2 order by Columns
However the above query will fail and give the output as
Msg 156, Level 15,
State 1, Line 2
Incorrect syntax near the keyword
'union'.
NOTE :It is not
possible to have two different order by in the UNION statement
because UNION returns single resultant.
However if your requirement is saying to sort top and bottom
query independently then how to do?
Let’s create a scenario, by taking two tables TABLE1 and
TABLE2
create table table1
(id int,
name varchar(15)
)
Command(s) completed
successfully.
create table table2
(id int,
name varchar(15)
)
Command(s) completed
successfully.
insert into table1(id,name)
select 1,'Ananya_Tab1'
union all
select 2,'Abhiroop_Tab1'
union all
select 3,'Gunjal_Tab1'
(3 row(s) affected)
insert into table2(id,name)
select 3,'Bikshapati_Tab2'
union all
select 2,'Sanjana_Tab2'
union all
select 1,'Akshit_Tab3'
(3 row(s) affected)
Now our tables are in place let’s do proceed to stimulate
our requirement, we want like this
select id,name, 'tab1' as odrCol from table1
order by id
union all
select id,name, 'tab2' as odr1 from table2
order by id
But firing the above script on
ssms, gives error
Msg 156, Level 15,
State 1, Line 3
Incorrect syntax near the keyword
'union'.
And if we execute the
select UNION without order by
select id,name from table1
union all
select id,name from table2
id name
----------- ---------------
1 Ananya_Tab1
2 Abhiroop_Tab1
3 Gunjal_Tab1
3 Bikshapati_Tab2
2 Sanjana_Tab2
1 Akshit_Tab3
(6 row(s) affected)
However our requirement
is like this
id name
----------- ---------------
1 Ananya_Tab1
2 Abhiroop_Tab1
3 Gunjal_Tab1
1 Akshit_Tab3
2 Sanjana_Tab2
3 Bikshapati_Tab2
So to get the output as
required, lets add a additional column ordCol and use it in order by clause
select id,name, 'tab1' as odrCol from table1
union all
select id,name, 'tab2' as odrCol from table2
order by odrCol,id
id name odrCol
----------- ---------------
------
1 Ananya_Tab1 tab1
2 Abhiroop_Tab1 tab1
3 Gunjal_Tab1 tab1
1 Akshit_Tab3 tab2
2 Sanjana_Tab2 tab2
3 Bikshapati_Tab2 tab2
(6 row(s) affected)
Now we can see we achieved our desired requirement of
independent sorting of select query in UNION ALL.
Code exercises your creative instincts; do code n enjy J
Post Reference: Vikram Aristocratic Elfin Share