Given a table that would have values like this:
name, sortval, dept
bob, 2, 1
tom, 4, 1
mary, 6, 1
sam, 8, 1
tim, 10,
A CASE
statement may help. In this example:
source
, sam, is at position 8target
, bob, is at position 2Replacing the variables with the actual values, the following statement shifts everything down 2 from the source, leaves the between members as is, sets the target equal to source, moves the rest down:
postgres=> SELECT * FROM test order by sortval;
name | sortval
------+---------
bob | 2
tom | 4
mary | 6
sam | 8
tim | 10
(5 rows)
postgres=> UPDATE test
postgres-> SET sortval = CASE WHEN sortval <= 2 THEN sortval - 2
postgres-> WHEN sortval = 8 THEN 2
postgres-> WHEN sortval >= 8 THEN sortval - 2
postgres-> ELSE sortval
postgres-> END;
UPDATE 5
postgres=> SELECT * FROM test order by sortval;
name | sortval
------+---------
bob | 0
sam | 2
tom | 4
mary | 6
tim | 8
(5 rows)
That would move something up the list. Similar logic could be applied for moving down a list. And it assumes negative numbers are fine an that just the relative ordering is of interest.