views:

36

answers:

2

I have a column of states, and, depending on the query, I want to order by results by a particular state, then by id (Asc or Desc, depending). For instance, I might want to show all rows with state "HI", sorted by ID desc, and then all the other rows, sorted by id desc.

I was hoping I could do this in one query, rather than getting all my favored state results, and then getting the rest. Can I?

+1  A: 

You have two options:

  • do a union
  • write a function and use it to order rows by

In the first case, you could do something like

select 1 as res_order, ...
  ...
  where state like 'hi%'
union
select 2 as res_order, ...
  ...
  where state not like 'hi%'
order by res_order asc, id desc

In the second case, you could do something like

select my_function(state, "hi") as row_order, ...
  ...
  order by row_order

where the function returns lower values for matching states.

The code is off the top of my head: it might need some tweaking to make it runnable.

Tomislav Nakic-Alfirevic
It's easier and quicker to use a case or if statement in the order by clause.
ar
It's always a pleasure to see someone offer a better idea, you've got a point, ar. :)
Tomislav Nakic-Alfirevic
+1  A: 

How about:

SELECT id, state
FROM sometable
ORDER BY IF(state = 'HI', 0, 1) ASC, id DESC;

This will sort 'HI' rows first. If you want them last, change the ASC to DESC.

Marc B