Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Priority Ordering

I have a table that contains tasks and I want to give these an explicit ordering based on the priority of the task. The only way I can think to do this is via an unique int column that indexes where the task is in term of the priority (i.e. 1 is top 1000 is low).

The problem is that say I wanted to update task and set its priority to a lower value , I would have to update all the other rows between its current value and its new value.

Can anyone suggest a better way of implementing this?

like image 503
Corin Blaikie Avatar asked Sep 21 '08 23:09

Corin Blaikie


People also ask

How do you order from highest to lowest 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.

Does WHERE order matter in SQL?

No, the order of the WHERE clauses does not matter. The optimizer reviews the query & determines the best means of getting the data based on indexes and such.

Why do we use ORDER BY 1 in SQL?

it simply means sorting the view or table by 1st column of the query's result.

Does SQL automatically order in ascending?

In this case, SQL Server uses BusinessEntityID and returns all of the records and it will order the result set based on that specific field. Note: The default ORDER is ascending order and result-set is sorted in ascending order based on the field that is specified in the SQL query.


2 Answers

Use a real number value as the priority. You can always slide in a value between two existing values with something like newPri = task1Pri + (task2Pri - task1Pri)/2 where Task1 has the lower priority numeric value (which is probably the higher piority).

Corin points out that min and max priorities would have to be calculated for tasks inserted at the top or bottom of the priority list.

And joelhardi reminds us that a reorder process is a good idea to clean up the table from time to time.

like image 198
Doug L. Avatar answered Oct 24 '22 07:10

Doug L.


Instead of creating an numbered column like you said, create a field called something like parent. Each row contains the pk of its parent item. When you want to move one item down just change its parent pk to the new one and the item(s) which reference it in their parent pk. Think singly linked lists.

like image 28
kemiller2002 Avatar answered Oct 24 '22 07:10

kemiller2002