Groups | Blog | Home
all groups > sql server programming > april 2004 >

sql server programming : Order of results in Union


Thomas Scheiderich
4/11/2004 11:04:44 PM
I am trying to use a union and get the first select statement to show
before the second select.

In the following I have only 1 row. It consists of one word "ALL" that
I want to show first as it is going into a web drop down control. The
problem is that in Sql Server 6.5, it puts the "ALL" insided the second
select in alpha order. In Sql Server 7, it puts it at the end. Why do
they act differently and how can I force the 1st select to show first.

****************************************************************
select 'ALL' as carrier,'ALL' as carrierCode union select
name,carrier_code from carrier where default_class is not null
*****************************************************************

Thanks,

Tom.
Aaron Bertrand [MVP]
4/12/2004 2:14:03 AM
SELECT ...
UNION
SELECT ...
ORDER BY CASE WHEN carrier = 'ALL' THEN 1 ELSE 2 END

--
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/





[quoted text, click to view]

Anith Sen
4/12/2004 9:11:04 AM
Aaron,

Since carrier is just an alias for the column, the statement will not
compile using CASE having a reused alias. One workaround is to make the
whole UNION query as derived table construct & apply the ORDER BY on the
outer query.

SELECT *
FROM ( < union query > ) T
ORDER BY CASE WHEN carrier = 'ALL' THEN 1 ELSE 2 END ;

--
Anith

Gert-Jan Strik
4/12/2004 11:38:21 AM
Tom,

without an explicit ORDER BY, there is no guarantee that the rows will
be returned in any specific order. So you could use Aaron's solution, or
something like

select 'ALL' as carrier, 'ALL as carrierCode, 1 as sortcolumn
union
select name, carrier_code, 2 from carrier where default_class is not
null
order by sortcolumn, carrier

Hope this helps,
Gert-Jan


[quoted text, click to view]

--
Thomas Scheiderich
4/12/2004 12:40:14 PM
[quoted text, click to view]


Both the sort and your query worked fine:

***********************************************************************
select * from (select 'ALL' as carrier,'ALL' as carrierCode union select
name,carrier_code from carrier where default_class is not null) T
ORDER BY CASE WHEN carrier = 'ALL' THEN 1 ELSE 2 END
*************************************************************************

Why does the T have to follow derived table? I noticed (when I
accidently left it off) that it didn't work. Worked fine when I added it.

Also, which would be more efficient - the sort or the derived table - or
would it matters. Is there a way to tell?

Thanks,

Tom.

[quoted text, click to view]
Anith Sen
4/12/2004 2:38:41 PM
[quoted text, click to view]

That is the required syntax in SQL. An alias is mandatory.

[quoted text, click to view]
would it matters. Is there a way to tell? <<

In most cases it should be the same, better to test & compare them.

--
Anith

AddThis Social Bookmark Button