tags:

views:

45

answers:

3

I have a column called "menu_order" which has no default value. When I select the contents of this column using the following select statement:

SELECT * FROM categories ORDER BY menu_order ASC

It lists the category items that have nothing as their menu order first and then the one's that have 1's and 2's and 3's. Is there any way to prevent SQL from take nothing to come before numbers when I am trying to list things in order?

So for example, if I have:

cat_name | menu_order
----------------------
Lunch    | 1
Dinner   | 

And I perform my query, the output should be:

Lunch Dinner

Not:

Dinner Lunch
+6  A: 

This will put the null values last:

SELECT *
FROM categories
ORDER BY menu_order IS NULL ASC, menu_order ASC
Mark Byers
I must have made a mistake trying to explain my problem, all the code given here still makes the null values show up first, I want those to show up at the end AFTER the ones that have been assigned numeric values. So even is the assigned value is 1000000 - I want it to come before the one that has a null value.
RailsRor
RailsRor: Sorry, the solution is to use ASC instead of DESC. I've edited my answer.
Mark Byers
The accepted answer is fine but I find this one clearer. I can't understand why some users hurry up to accept answers before the community has time to provide helpful replies.
Álvaro G. Vicario
+1  A: 

You can use the IFNULL function in the order by with a large number

ORDER BY IFNULL(menu_order, 1000) ASC 

You can even try using a case statement

ORDER BY 
CASE 
    WHEN menu_order IS NULL THEN 1
    ELSE 0
END ASC,
menu_order ASC
astander
A: 
ORDER BY IFNULL(menu_order, 99999999) ASC
Ignacio Vazquez-Abrams
Yay. More downvotes for a correct answer.
Ignacio Vazquez-Abrams