Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reordering an ordered list

I have a following SQL table with data

ProductList 
id  order productname
79   1     name1
42   2     name2
67   3     somename
88   4     othername
99   5     XYZ
66   6     ABC

Display order is very volatile, it will change frequently, users will add or remove items and reorder the items.

How should i handle this situation without updating multiple records. Example: if user enters a new product between 1 and 2 order, i do not want to update the order of all the records beneath 2 and if someone switch order 3 to 4 i don't want to update every record under 3.

like image 600
nin Avatar asked Jul 31 '10 18:07

nin


People also ask

How do you reorder a list in Python?

You can sort a list in Python using the sort() method. The method accepts two optional arguments: reverse : which sorts the list in the reverse order (descending) if True or in the regular order (ascending) if False (which it is by default)

Can we reorder columns in SQL?

Using SQL Server Management StudioIn Object Explorer, right-click the table with columns you want to reorder and select Design. Select the box to the left of the column name that you want to reorder. Drag the column to another location within the table.

How do you sort rows in SQL?

The SQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.


2 Answers

Use the 'orrible old trick made famous(?) by old BASIC coders - set your orders to be 100, 200, 300, 400 etc. and then you can pick an order 'inbetween' when you need to. This could get messy - and if you're anticipating a lot of reordering then I'd recommend that you have a scheduled task to 'reorder' the order values every now and then for the entire table.

like image 57
Will A Avatar answered Oct 04 '22 08:10

Will A


You have two options:

  • Iterate over the rows, using an UPDATE statement with a function/etc to generate the updated order value
  • Scorched Earth: You delete the existing records, and insert identical ones save the corrected order value

There's no SQL functionality to make this easier, and no real option that is simplistic.

like image 38
OMG Ponies Avatar answered Oct 04 '22 07:10

OMG Ponies