Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Query order by if null

Tags:

mysql

I am trying to build a MySQL query that has an order by statement. This is what I am trying to do:

SELECT * 
FROM tbl_product 
ORDER BY retail_price ONLY IF wholesale_price IS NULL OTHERWISE ORDER BY wholesale_price.

I have no idea where to start. I found an article that uses ORDER BY COALESCE but I also found that this could have performance issues.

Any advice is appreciated.

like image 934
puks1978 Avatar asked Jul 10 '11 23:07

puks1978


People also ask

How do I ORDER BY NULL last?

If you specify the ORDER BY clause, NULL values by default are ordered as less than values that are not NULL. Using the ASC order, a NULL value comes before any non-NULL value; using DESC order, the NULL comes last.

What does ORDER BY NULL mean?

using ORDER BY NULL is a workaround that satifies the syntax requirement but does not actually change the order of the data. In effect it is an instruction to not order at all. N.B.: some (myself included) prefer to use SELECT 1 instead of SELECT NULL but there is no difference in effect.

When data is sorted in ascending order NULL values appear first in the list?

SQL treats NULL values to be less than 0 so while sorting in ascending order, NULL values always appear to be at first.

When data is sorted in descending order are NULL values listed first or last?

Ordering. When you order by a field that may contain NULL values, any NULLs are considered to have the lowest value. So ordering in DESC order will see the NULLs appearing last. To force NULLs to be regarded as highest values, one can add another column which has a higher value when the main field is NULL.


1 Answers

SELECT * 
FROM tbl_product 
ORDER BY ifnull(wholesale_price, retail_price);

Note that you don't need to select the value you're ordering by - it can be any expression

like image 193
Bohemian Avatar answered Nov 24 '22 03:11

Bohemian