tags:

views:

124

answers:

5

For clarification, are you able to use MySQL this way to sort?

ORDER BY CompanyID = XXX DESC

What I am trying to do is use one sql query to sort everything where X = Y, in this case, where CompanyID = XXX. All values where CompanyID is not XXX should come after all the results where CompanyID = XXX.

I don't want to limit my query but I do want to sort a particular company above other listings.

+2  A: 

You could probably fake it out

SELECT CompanyID, IF(CompanyID = XXX, -1, CompanyID) AS sortby
FROM companies
ORDER BY sortby DESC
Daniel
+1 Use 4 spaces or Ctrl-K to make code appear as code :)
Andomar
+6  A: 

You can use a case in an order by, like:

order by case when CompanyID = XXX then 1 else 2 end
Andomar
CASE eh? Learn something new everyday.
Kevin
+1  A: 

You might want to try using a CASE statement in your order by expression. When the company id matches your preferred company, return 0, else return 1. Then order by company name like usual in a secondary order by column.

 order by case when CompanyID = XXX then 0 else 1 end, CompanyName

That way you have your preferred company at the top, then all of the rest order alphabetically by name (or however you want it ordered).

tvanfosson
I'll give this a try.
Kevin
+5  A: 
ORDER BY FIELD(CompanyID, 'google', 'apple', 'microsoft') ASC

Google = first
Microsft = third
The rest = last

Coronatus
+1 Interesting, but the field function would return 3 for Microsoft and you're sorting descending, so Microsoft would be first
Andomar
@Andomar - Oops, copy-paste error. :) Fixed
Coronatus
But if you sort ascending, the rest will be first!
Andomar
+1  A: 

Your query is fine. CompanyID = xxx yields 1 on a match, and 0 otherwise. Just add the CompanyID column as the secondary order column.

ORDER BY CompanyID = XXX DESC, CompanyID ASC

This way, you get records where the CompanyID matches your constant first, then the rest are in order.

Alternatively, you could do this:

ORDER BY CompanyID <> XXX ASC, CompanyID ASC
Marcus Adams
Of course, why didn't that occur to me. So simple. Will that work with LIKE too? CompanyID LIKE %%, CompanyID = Y ASC
Kevin
@Kevin, yes, you can do that with LIKE as well.
Marcus Adams
Thanks, this worked for me short term. With the added answers here I think I can come up with a more flexible solution in the long run but this got me back on track.
Kevin