0

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!

1 Answer 1

6

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

6
  • oh, gimme a minute, will try it out!
    – iamserious
    Aug 13, 2010 at 11:31
  • hm, now it says Msg 102, Level 15, State 1, Line 7 Incorrect syntax near ')'.
    – iamserious
    Aug 13, 2010 at 11:32
  • 1
    (case when preferenceOrder is null then 0 else 1 END)
    – KM.
    Aug 13, 2010 at 11:48
  • 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
    Aug 13, 2010 at 11:53
  • thanks, I just ended up by using the modified version of your querry.
    – iamserious
    Aug 13, 2010 at 11:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.