views:

1908

answers:

3

I'm trying to sort some data by two columns, but it doesn't seem to be working. What I want are articles sorted by highest ratings first, then most recent date. As an example, this would be a sample output (left # is the rating, then the article title, then the article date)


50 | This article rocks          | Feb 4, 2009
35 | This article is pretty good | Feb 1, 2009
5  | This Article isn't so hot   | Jan 25, 2009

The relevant SQL I'm using is:

ORDER BY article_rating, article_time DESC

This seems to be sorting by article_time DESC. I can sort by one or the other, but not both, am I missing something obvious?

+8  A: 

Default sorting is ascending, you need to add the keyword DESC to both your orders:

ORDER BY article_rating DESC, article_time DESC
truppo
Beautiful, it's now working, thanks!
A: 

ORDER BY article_rating ASC , article_time DESC

DESC at end will sort by both columns descending. You have to specify ASC if it is otherwise

Learning
+1  A: 
ORDER BY article_rating, article_time DESC

will sort by article_time only if there are two articles with the same rating. From all I can see in your example, this is exactly what happens.

↓ primary sort                         secondary sort ↓
1.  50 | This article rocks          | Feb 4, 2009    3.
2.  35 | This article is pretty good | Feb 1, 2009    2.
3.  5  | This Article isn't so hot   | Jan 25, 2009   1.

but consider:

↓ primary sort                         secondary sort ↓
1.  50 | This article rocks          | Feb 2, 2009    3.
1.  50 | This article rocks, too     | Feb 4, 2009    4.
2.  35 | This article is pretty good | Feb 1, 2009    2.
3.  5  | This Article isn't so hot   | Jan 25, 2009   1.
Tomalak