Consider the following table structure:
id name rank position
-------------------------------
1 Steve 5 0
2 David 3 0
3 Helen 9 0
4 Mark 15 0
I need a fast algorithm to rate these rows by rank column and store the “position” of each row in position field in realtime.
Now I have a brutal solution:
SELECT * FROM table ORDER BY rank DESC
And then fetch the result in a loop and update every row filling the position column. But what If I’d have thousands of entries? How can I optimize it?
I answered a very similar question specific to MySQL a few days ago:
Automate MySQL fields (like Excel)
The trick is not to store the column in the database but to calculate it dynamically when you fetch the results. Alternatively you could use triggers to update the column every time you make an insert, update or delete.