I have an SQL table with two fields: id and order.
CREATE TABLE IF NOT EXISTS article (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`order` INT(11) UNIQUE,
PRIMARY KEY (`id`)
);
In this table I have some items:
+----+-------+
| id | order |
+----+-------+
| 1 | 0 |
| 2 | 1 |
| 3 | 2 |
| 4 | 3 |
| 5 | 4 |
| 6 | 5 |
| 7 | 6 |
| 8 | 7 |
| 9 | 8 |
| 10 | 9 |
+----+-------+
Now I want to change order position of one item: element with id 3 (order position 2) will move into position 6. Thus, the elements between position 4 and 6 (this last one included)
will have to decrease their order field.
The result should be this:
+----+-------+
| id | order |
+----+-------+
| 1 | 0 |
| 2 | 1 |
| 4 | 2 | ⌉
| 5 | 3 | |
| 6 | 4 | | Updated items
| 7 | 5 | |
| 3 | 6 | ⌋
| 8 | 7 |
| 9 | 8 |
| 10 | 9 |
+----+-------+
Of course the first update —update item with id 3 with order field 6— is easy:
UPDATE article
SET article.order = 6
WHERE id = 1;
Then I can decrease the items between positions greater than 2 and lower or euql than 6:
UPDATE article
SET article.order = article.order -1
WHERE
article.order > 2
AND
article.order <= 6
;
But here there is a problem: order field is UNIQUE. So I have to first set it to NULL for the item I want to move:
UPDATE article
SET article.order = NULL
WHERE id = 3;
UPDATE article
SET article.order = article.order -1
WHERE
article.order > 2
AND
article.order <= 6
;
UPDATE article
SET article.order = 6
WHERE id = 3;
Is there a way to avoid setting this NULL?
Here is a fiddle: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=342d714e88e68d3c4c6e0ca1ec8efa6c