What is the most efficient way to store a sort-order on a group of records in a database?

Viewed 9521

Assume PHP/MYSQL but I don't necessarily need actual code, I'm just interested in the theory behind it.

A good use-case would be Facebook's photo gallery page. You can drag and drop a photo on the page, which fires an Ajax event to save the new sort order. I'm implementing something very similar.

For example, I have a database table "photos" with about a million records:

photos id : int, userid : int, albumid : int, sortorder : int, filename : varchar, title : varchar

Let's say I have an album with 100 photos. I drag/drop a photo into a new location and the Ajax event fires off to save on the server.

Should I be passing the entire array of photo ids back to the server and updating every record? Assume input validation by "WHERE userid=loggedin_id", so malicious users can only mess with the sort order of their own photos

Should I be passing the photo id, its previous sortorder index and its new sortorder index, retrieve all records between these 2 indices, sort them, then update their orders?

What happens if there are thousands of photos in a single gallery and the sort order is changed?

5 Answers
Related