Russbear
Russbear

Reputation: 1261

Does MySQL maintain the order of the table you are querying

I'm using MySQL and I have a table that holds player scores, with a single player being able to log multiple scores. I'm trying to find the best way to rank the players using the MySQL ORDER BY keyword.

Right now what I'm doing is:

SELECT DISTINCT t.userName FROM (SELECT userName, score FROM scoreTable ORDER BY score DESC) t;

To use this for ranking it I'm assuming that the order from the sub-query is maintained by the main query.

Is this assumption correct? All my testing so far maintains the order properly. Is there a situation where it will not work?

Upvotes: 0

Views: 137

Answers (2)

Tim Dearborn
Tim Dearborn

Reputation: 1177

Would the below work for you?

SELECT userName, MAX(score) AS max_score 
FROM scoreTable GROUP BY username 
ORDER BY max_score DESC

Upvotes: 2

Indigenuity
Indigenuity

Reputation: 9740

I don't believe this is guaranteed behavior, but generally yes. It may be better to have the ORDER BY on the outer query if you want the final results ordered that way.

Upvotes: 1

Related Questions