Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql left join order by null values to the end

Tags:

mysql

mysql

SELECT * FROM media
LEFT JOIN media_priority
ON (media_priority.media_id = media.id AND media_priority.media_tag = '".$tag."')
WHERE something = 'something'
ORDER BY media_priority.media_order;

This works fine except that media_priority.media_order sometimes comes back as null and mysql puts the null values at the top.

So I was trying to figure out how to do an IS NULL AS tempcol statement with my left join so I can order by that first.....I just can't seem to get the syntax right.

Where would I put the IS NULL statement in my query above?

I was thinking something like:

LEFT JOIN media_priority
ON (media_priority.media_id = media.id AND media_priority.media_tag = '".$tag."')
media_priority.media_order IS NULL AS isnull

but that doesn't work.

like image 478
Senica Gonzalez Avatar asked Dec 01 '10 16:12

Senica Gonzalez


People also ask

How LEFT join works with NULL values?

The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.

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.

Does LEFT join match NULLs?

Left Join returns a null even when the match exists.

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

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.


2 Answers

I recommend ordering by the boolean value of media_priority.media_order IS NULL first, then the column value, in order to force the NULLs to the end.

Like this:

SELECT * FROM media
LEFT JOIN media_priority
ON (media_priority.media_id = media.id AND media_priority.media_tag = '".$tag."')
WHERE something = 'something'
ORDER BY (media_priority.media_order IS NULL) ASC, media_priority.media_order ASC;
like image 157
Ike Walker Avatar answered Oct 12 '22 23:10

Ike Walker


ORDER BY 
    CASE WHEN media_priority.media_order IS NULL THEN 1 ELSE 0 END, 
    media_priority.media_order;

Or use a magic number if you have some upper limit which media_order will never feasibly reach.

ORDER BY 
    COALESCE( media_priority.media_order,99999999);

The first approach is obviously somewhat safer!

like image 42
Martin Smith Avatar answered Oct 12 '22 23:10

Martin Smith