Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a particular, mutable "order" into a database

Suppose I have some objects, and I want the user to be able to reorder them in any way they wish, say, by dragging them around. So I'd have

  • Cheese
  • Muffins
  • Milk

And then the user drags 'milk' to the top, making the new order

  • Milk
  • Cheese
  • Muffins

Is there a best practice how to store the order of these objects in a database? The naive approach would probably be to just store a numerical value called "order" for each object, but this seems like too much hassle to me, because you'd have to shuffle the order-values around most of the time.

like image 677
winsmith Avatar asked Jan 31 '09 12:01

winsmith


People also ask

How do I change the order of data in MySQL?

An "ALTER TABLE ORDER BY" statement exist in the syntaxes accepted by MySQL. According to the documentation, this syntax: - only accept *one* column, as in "ALTER TABLE t ORDER BY col;" - is used to reorder physically the rows in a table, for optimizations.

How do you sort records in DBMS?

Sorting helps to sort the records that are retrieved. By default, it displays the records in ascending order of primary key. If we need to sort it based on different columns, then we need to specify it in ORDER BY clause. If we need to order by descending order, then DESC keyword has to be added after the column list.


2 Answers

The best way I've found to handle this is to have a floating point order field. When you move something between two other items, set that field to halfway between its neighbors.

This is cheap on both reads and writes. The only downside is the floats keep getting longer :)

like image 169
Sean Clark Hess Avatar answered Sep 28 '22 09:09

Sean Clark Hess


The "naive" approach you suggest is also the best practice!

like image 28
Tony Andrews Avatar answered Sep 28 '22 07:09

Tony Andrews