Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder integer except for value 0 with sql

I'm trying to get an ordered list of rows out of my MYSQL database table based upon an integer value 'place'.

SELECT * FROM mytable
ORDER BY place;

This works okay, except that all rows with value place=0 should appear at the end of the table.

So if my table is:

name place
---- -----
John 1
Do   2
Eric 0
Pete 2

it should become:

name place
---- -----
John 1
Do   2
Pete 2
Eric 0
like image 385
Roalt Avatar asked Feb 07 '10 19:02

Roalt


People also ask

How do I reorder data in SQL?

The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some databases sort the query results in an ascending order by default.

How do I sort by numerical order in SQL?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.

What is ORDER BY 0 in SQL?

The order statement generates a 'virtual field' that contains NULL or 0 based on the case condition. The ORDER BY is applied based on that virtual field. The zero value in the order by precedes the NULL value. That's all, it's a way to set NULLs of the field1 at the end of the order list.

How do you order from least to greatest in SQL?

The SQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.


2 Answers

order by case when place = 0 then 1 else 0 end asc, place asc

that way you get all the non-zeroes ordered first.

like image 84
davek Avatar answered Oct 13 '22 11:10

davek


SELECT *
FROM myTable
ORDER BY place>0 DESC, place

is a solution without CASE

like image 26
True Soft Avatar answered Oct 13 '22 12:10

True Soft