How to implement custom ordering functionality?

How to implement custom ordering functionality?

am 25.10.2004 10:04:22 von Tomas Eklund

Using: Classic ASP, JScript, Access or SQL Server

When implementing a system where the user should be able to rearrange (sort)
items, which are stored in a database, in a custom order (for example a number
of items to appear in the menu of a web page, or "news" on a news page), how
would you go about?

I was thinking of adding a column, "SortOrder", in the database table. It would
be an integer column and using it to display items in the custom order would be
pretty straight-forward:

SELECT ... FROM ...ORDER BY SortOrder

In the site administrator interface I could implement a "move up/down" function
that would swap values in the SortOrder fields of the chosen and the
previous/next items.

A "move to top" function would simply set SortOrder of the chosen item to 1 and
then do something like "SortOrder = SortOrder + 1" to all other items in the
table.

A "move to bottom" function could find the largest SortOrder value in the table
and set SortOrder of the chosen item to this value + 1. (Is it possible to do
this in one single SQL statement btw?)

Adding a new item could be done at the bottom or by inserting the new item
before some other item already present in the table. In the latter case,
SortOrder of the new item would take the value of the item it's placed before
and then all SortOrder values equal to or greater than this value are
incremented by 1.

Deletion of items would be straight-forward as "holes" in the SortOrder
numbering sequence wouldn't cause any trouble (?).

Here comes my question: Is this "best practice"? I would think "move to top" is
perhaps the most common admininistrator operation and it would require
"renumbering" every item in the table (on the indexed column SortOrder). Of
course, this is not something that is done all the time, just occasionally, so
perhaps it's not a big problem. I don't expect tables to grow very large either
(in which case custom ordering wouldn't make much sense anyway).

However, if there is a smarter way of doing it, I'd really like to know.

Thanks!

--
Best regards,
Tomas Eklund