Question

I am trying to order by year ascending/descending however I want when the year is 0 to be treated as the newest.

For example:

 2013
 2014
 0

 ORDER BY YEAR DESC should be

 0
 2014
 2013

After some reading I thought this should work but it doesn't:

 ORDER BY CASE WHEN YEAR = 0 THEN 9999, YEAR ASC
Was it helpful?

Solution

Please try:

select  * 
from TableName
order by case YEAR when 0 then 9999 else YEAR end desc

SQL Fiddle Demo

OTHER TIPS

Try this:

SELECT * 
FROM TableName
ORDER BY CASE WHEN YEAR = 0 THEN 0 ELSE 1 END, YEAR ASC

Result:

YEAR
0
2013
2014

An example in SQL Fiddle.

Please try this

SELECT * FROM TableName ORDER BY IF( YEAR =0, 9999, YEAR ) DESC

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top