views:

59

answers:

1

Hi,

I am trying to sort my database in some particular order, but I want all null's at the end, so I am selecting all values with not null, and then selecting all values WITH null, and trying to join them with Union.. like:

SELECT * FROM preferences WHERE preferenceOrder IS NOT NULL 
                               ORDER BY preferenceOrder ASC
UNION

SELECT * FROM preferences WHERE preferenceOrder IS NULL 
                               ORDER BY preferences ASC

but the server throws an error:

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'union'.

I cant find out what the error is though.. what is wrong with the sentence above?

thanks!

+5  A: 

i think you should order by (case when preferenceOrder is null then 0 else 1 end), preferenceOrder instead of this union.

tenfour
oh, gimme a minute, will try it out!
iamserious
hm, now it says Msg 102, Level 15, State 1, Line 7Incorrect syntax near ')'.
iamserious
(case when preferenceOrder is null then 0 else 1 **END**)
KM
yup, END fixed it, but doesnt sort the way i want it to, unless i do this: <b>select * From countries order by (case when preferenceOrder is null then 999999 else preferenceOrder end), preferenceOrder</b> is it better to use this: <b>SELECT * FROM countries ORDER BY COALESCE(sortOrder,999999) ASC</b> ? I dint want to use it because of the 999999.. what if my table goes over that number?
iamserious
how do you make it bold btw?
iamserious
thanks, I just ended up by using the modified version of your querry.
iamserious
oops, corrected - thanks
tenfour
Something a little shorter is to use the ISNULL operator thus you could just have ISNULL(PreferenceOrder,0) - this is logically equivalent to:order by (case when preferenceOrder is null then 0 else preferenceOrder end) which I think is what you are after
Joel Mansford