Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by clause with Union in Sql Server

I want List of party names with 1st option as 'All' from database. but i won't insert 'All' to Database, needs only retrieve time. so, I wrote this query.

Select 0 PartyId, 'All' Name
Union
select PartyId, Name
from PartyMst

This is my Result

0   All
1   SHIV ELECTRONICS
2   AAKASH & CO.
3   SHAH & CO.

when I use order by Name it displays below result.

2   AAKASH & CO.
0   All
3   SHAH & CO.
1   SHIV ELECTRONICS

But, I want 1st Option as 'All' and then list of Parties in Sorted order. How can I do this?

like image 370
Dhaval Ptl Avatar asked Aug 14 '13 07:08

Dhaval Ptl


People also ask

Can we use ORDER BY with UNION in SQL Server?

It is not possible to use two different ORDER BY in the UNION statement. UNION returns single resultsetand as per the Logical Query Processing Phases.

Can we use ORDER BY clause in UNION?

Union is a type of operator in MySQL. We can use ORDER BY with this to filter records. Use UNION if you want to select rows one after the other from several tables or several sets of rows from a single table all as a single result set. Let us see an example.

Can I use ORDER BY and UNION all?

The UNION ALL operator can use the ORDER BY clause to order the results of the query in SQL Server (Transact-SQL).


3 Answers

You need to use a sub-query with CASE in ORDER BY clause like this:

SELECT * FROM
(
  Select 0 PartyId, 'All' Name
  Union
  select PartyId, Name
  from PartyMst
) tbl
ORDER BY CASE WHEN PartyId = 0 THEN 0 ELSE 1 END
,Name

Output:

PARTYID NAME
0 All
2 AAKASH & CO.
3 SHAH & CO.
1 SHIV ELECTRONICS

See this SQLFiddle

like image 59
Himanshu Jansari Avatar answered Sep 21 '22 23:09

Himanshu Jansari


Since you are anyway hardcoding 0, All just add a space before the All

Select 0 PartyId, ' All' Name
Union
select PartyId, Name
from PartyMst
ORDER BY Name

SQL FIDDLE

Raj

like image 40
Raj Avatar answered Sep 23 '22 23:09

Raj


You can use 'order by' with the top instrucction in a union in this way:

Select 0 PartyId, 'All' Name
Union
select * from ( 
  select top (select count(*) from PartyMst) PartyId, Name
  from PartyMst
  order by Name
)
like image 34
Daniel De León Avatar answered Sep 22 '22 23:09

Daniel De León