89 points · by latch · 15y ago · 12 comments
There are several ways you can calculate a rank, and some (e.g. self join) are inherently slow. Maybe the problem is as simple as not having the right clustered index? Or maybe sql dbs can do more optimization if you tell them to use their rank function instead of selecting out a rownum? Postgres 8.4+, sql server 2005+, and Oracle all have rank functions (one of the 'window functions' in the SQL:2003 standard http://en.wikipedia.org/wiki/Window_function_(SQL)#Window_fu... )
In general I agree though. If you relax the consistency requirement slightly you can get away with regenerating the rank table every minute or so. It takes ~500ms on my machine to generate the ranked table for 500k rows on PG9. Unlogged tables in 9.1 would probably make it faster.
1) On get_rank() do a count(*) where score < users_score;
2) Store row_number() over() [...] order by score in a lookup table and refresh every so often. Use this for get_rank() lookups.
The problem I have is that you either have to calculate the rank on read using a linear-time count() or on write which means updating n/2 rows on average with their new position.
edited formatting
We don't have very high traffic though--we manage roughly 3000 games/hour at our peak times with our one DB server.
The approach has worked well.