Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting and ordering rows with value greater than zero then rows with value zero

Tags:

sql

mysql

I have a table like this

id    title    display_order
1     t1       3
2     t2       1
3     t3       5
4     t4       4
5     t5       2
6     t6       0
7     t7       7
8     t8       6
9     t9       0
10    t10      0

What I need is to have results like this

id    title    display_order
2     t2       1
5     t5       2
1     t1       3
4     t4       4
3     t3       5
8     t8       6
7     t7       7
...order of the rest is not important but should be in the result
6     t6       0
9     t9       0
10    t10      0

I can get this result with two SQL queries and then combine them.

Is there a way to do this with one SQL?

Thanks

like image 822
Ergec Avatar asked Oct 03 '11 07:10

Ergec


People also ask

What does order by 0 mean 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 highest to lowest 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.

What is the significance of using a number in an order by clause in mysql?

The rule checks for ORDER BY clauses that reference select list columns using the column number instead of the column name. The column numbers in the ORDER BY clause impairs the readability of the SQL statement.


1 Answers

SELECT *
FROM atable
ORDER BY
  display_order = 0,
  display_order

When display_order is 0, the first sorting term, display_order = 0, evaluates to True, otherwise it evaluates to False. True sorts after False – so, the first sorting criterion makes sure that rows with the display_order of 0 are sorted at the end of the list.

The second ORDER BY term, display_order, additionally specifies the order for rows with the non-zero order values.

Thus, the two criteria give you the desired sorting order.

like image 184
Andriy M Avatar answered Oct 31 '22 10:10

Andriy M