MySQL Forums
Forum List  »  Newbie

Re: Order by two columns
Posted by: Peter Brawley
Date: October 30, 2014 12:29PM

drop table t;
create table t(aid smallint,bid smallint);
insert into t values (1,1),(1,2),(2,1),(2,null),(2,3),(3,null);

Given tbl(aid,bid), the query ...

select aid,bid
from t
order by aid asc,ifnull(bid,0) desc;

will return ...

+------+------+
| aid  | bid  |
+------+------+
|    1 |    2 |
|    1 |    1 |
|    2 |    3 |
|    2 |    1 |
|    2 | NULL |
|    3 | NULL |
+------+------+

To put the nulls at the top of each sublist, change the Order By clause to something like...

order by aid asc,ifnull(bid,999999) desc

Options: ReplyQuote


Subject
Written By
Posted
October 30, 2014 11:21AM
Re: Order by two columns
October 30, 2014 12:29PM
October 30, 2014 12:45PM
October 30, 2014 12:59PM
October 30, 2014 01:41PM
October 30, 2014 09:22PM
October 31, 2014 01:40AM
October 31, 2014 04:26AM
October 31, 2014 08:24AM
October 31, 2014 11:05AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.