tags:

views:

49

answers:

2

What's the best way to update an "order" column?

Say I have an id column with 0 to 9, and order column from 0 to 9.

Currently, it's in the database as: 0 0, 1 1, 2 2, etc

My HTML page posts what it wants as the new order: 0 8, 1 3, 2 6, etc. (This is completely random, decided by the user).

What's the best way to make the update?

I can loop through and run an update for each. I can also create a temporary table with all the pairs, and then update based on a subquery.

But I feel like I'm forgetting something trivial that will do this much faster. Any suggestions?

Thanks, Colin

+2  A: 

You have to update each row by itself, there is no way to do a "map" update in sql.

(There are some tricks but they don't really apply/help here anyway.)

Hogan
Thanks, it does seem odd that there's not a cleaner solution but no big deal.
Colin
I know what you mean, but this is the way relational databases work. There is a trick you can use on some systems, which is to pass in the "mapping" convert that to a table and then join to that table in the update. Totally not worth it in this case.
Hogan
A: 

If the user really is reordering the items at random, there isn't much you can do. But typically a user might make a small modification to an existing ordering, such as moving one item higher up in the list. In this case you can make a minor speed improvement by relaxing your constraint that the sort order column must contain sequential integers. I discussed a possible idea for this before here and you can read that suggestion if you're interested in the details of how to implement this.

But for lists of size 10 it's probably not worth the extra effort. Just do what you are doing - it'll probably be just fine in practice.

Mark Byers
Yea, these are generally going to be very short so efficiency isn't the biggest concern. I would like a cleaner option than running 10 updates, but I guess there is nothing ideal. Thanks
Colin