Pregunta

I need to have a conditional ORDER BY statement. In layman's terms it would be like this:

IF index_order IS NULL ORDER BY id ASC ELSE ORDER BY index_order ASC.

So basically, it'll start by ordering by the ID for all rows with a NULL index_order value, then it'll order the rest by index_order.

Any help here would be much appreciated.

¿Fue útil?

Solución

Just use:

ORDER BY index_order, id

Because NULL always sorts lower than any other value. So all your rows where index_order is NULL will be grouped first. Then their order will be resolved by id.


Re your comment:

I tried it out.

mysql> create table foo (id int auto_increment primary key, index_order int);
mysql> insert into foo values (1, 2), (2, 1), (3, null), (4, null);
mysql> select * from foo order by index_order, id;
+----+-------------+
| id | index_order |
+----+-------------+
|  3 |        NULL |
|  4 |        NULL |
|  2 |           1 |
|  1 |           2 |
+----+-------------+

It orders where index_order is null first, and resolves the tie with id sorted ascending. Then it orders by non-null index_order ascending.

I'm not sure I understand from your description how you would want it sorted differently.

Otros consejos

yo can use COALESCE and NULLIF :

ORDER BY COALESCE(NULLIF(id, ''), index_order), index_order

to more info click here and here

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top