Home > Database > Mysql Tutorial > body text

How to Swap Row Values in MySQL While Respecting Unique Constraints?

Linda Hamilton
Release: 2024-10-26 14:42:02
Original
621 people have browsed it

How to Swap Row Values in MySQL While Respecting Unique Constraints?

Swapping Row Values in MySQL Without Violating Unique Constraints

In MySQL, it is often necessary to swap the values of two rows in a table while maintaining a unique constraint on a specific column. However, using the typical UPDATE statement with a CASE clause can result in a duplicate entry error if the unique constraint is violated.

The Issue

The problem arises because MySQL processes updates row by row, checking for unique constraint violations after each change. In the provided example:

UPDATE tasks
SET priority = 
CASE
    WHEN priority=2 THEN 3 
    WHEN priority=3 THEN 2 
END 

WHERE priority IN (2,3);
Copy after login

MySQL updates the first row with priority 2 to priority 3. However, when it attempts to update the second row with priority 3 to priority 2, it encounters a violation because 3 already exists as a unique value.

The Solution

Unfortunately, it is not possible to accomplish row value swapping in MySQL without using bogus values or multiple queries. This is due to MySQL's unique constraint processing behavior.

To workaround this limitation, one can utilize the following two-statement approach wrapped in a transaction:

START TRANSACTION ;
    UPDATE tasks 
    SET priority = 
      CASE
        WHEN priority = 2 THEN -3 
        WHEN priority = 3 THEN -2 
      END 
    WHERE priority IN (2,3) ;

    UPDATE tasks 
    SET priority = - priority
    WHERE priority IN (-2,-3) ;
COMMIT ;
Copy after login

This approach effectively swaps the values by assigning negative values as a temporary placeholder. Within the transaction, MySQL considers updates as a single operation, preventing the unique constraint violation.

The above is the detailed content of How to Swap Row Values in MySQL While Respecting Unique Constraints?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!