BKWLD

 

Special MySQL orders

By Robert on February 28, 2008 at 10:29 am

Here’s another interesting query. Say you want to get a list of items, ordered by something, lets say date. But you want a particular row at the top, it’s special. Well check this out:

SELECT id
FROM games
ORDER BY id=5 DESC, dcreate DESC

“id=5″ converts to a 1 if true, 0 if false on all the rows that are returned. By ordering that boolean by DESC, you put the 1 at the top. The rest are all 0. Thus, you have your special row with id=5 at the top and the rest ordered by date! I’m guessing this doesn’t optimize super well, I guess we’ll see.

1 Comment »

  1. Dude. I could have used this thousands of times over the past decade. And it’s so easy.

    Comment by Mark — February 28, 2008 @ 12:57 pm


RSS feed for comments on this post. | TrackBack URI

Leave a comment