I have the following table (mariaDB):
+----+--------------+-------------+-------------+
| id | content_type | sort_number | document_id |
+----+--------------+-------------+-------------+
| 1 | text | 1 | 1 |
| 2 | table | 2 | 1 |
| 3 | text | 3 | 1 |
| 4 | image | 4 | 1 |
+----+--------------+-------------+-------------+
The combination of sort_number
and document_id
is unique.
Now when i want to add a new entry at position 2, I need to increment the sort_number
of all entries where the sort_number >= 2
by one step.
To achieve this, i use the following query:
update `table_name` set `sort_number` = sort_number +1 where `sort_number` > ? and `document_id` = ?
But because of the unique key (sort_number
and document_id
) i get an error:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '3' for key 'table_name_sort_number_document_id_unique'
I tired to avoid the error with SET unique_checks=0;
but still get the error...
Is there a (better) way to update the sort_number
in one query?