In this blog, I would like to give an example in which the Order By clause is used with the Union clause in SQL.
Sometimes we have a situation where we have to return one result set. Given below is an example where one result set is finally returned, but before that there are 3 result sets which have been combined altogether using the union clause.
Select * From
(
select Top(1) Title as TitleOption,1 sortby from Table1 where singer1='Test1' order by NEWID()
union
select top(1) Title As TitleOption,2 sortby from Table1 where year between @YearBack and @YearPost ORDER BY NEWID()
union
select top(2) Title AS TitleOption,3 sortby from Table1 where composer1='TestCompose1' order by NEWID()
) soption
order by TitleOption