163

I have a MySQL table with coordinates; the column names are X and Y. Now I want to swap the column values in this table, so that X becomes Y and Y becomes X. The most apparent solution would be renaming the columns, but I don't want to make structure changes since I don't necessarily have permissions to do that.

Is this possible to do with UPDATE in some way? UPDATE table SET X=Y, Y=X obviously won't do what I want.


Please note that my restriction on permissions, mentioned above, effectively prevents the use of ALTER TABLE or other commands that change the table/database structure. Renaming columns or adding new ones are unfortunately not options.

2

23 Answers 23

256

I just had to deal with the same and I'll summarize my findings.

  1. The UPDATE table SET X=Y, Y=X approach obviously doesn't work, as it'll just set both values to Y.

  2. Here's a method that uses a temporary variable. Thanks to Antony from the comments of http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/ for the "IS NOT NULL" tweak. Without it, the query works unpredictably. See the table schema at the end of the post. This method doesn't swap the values if one of them is NULL. Use method #3 that doesn't have this limitation.

    UPDATE swap_test SET x=y, y=@temp WHERE (@temp:=x) IS NOT NULL;

  3. This method was offered by Dipin in, yet again, the comments of http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/. I think it’s the most elegant and clean solution. It works with both NULL and non-NULL values.

    UPDATE swap_test SET x=(@temp:=x), x = y, y = @temp;

  4. Another approach I came up with that seems to work:

    UPDATE swap_test s1, swap_test s2 SET s1.x=s1.y, s1.y=s2.x WHERE s1.id=s2.id;

Essentially, the 1st table is the one getting updated and the 2nd one is used to pull the old data from.
Note that this approach requires a primary key to be present.

This is my test schema:

CREATE TABLE `swap_test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `x` varchar(255) DEFAULT NULL,
  `y` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

INSERT INTO `swap_test` VALUES ('1', 'a', '10');
INSERT INTO `swap_test` VALUES ('2', NULL, '20');
INSERT INTO `swap_test` VALUES ('3', 'c', NULL);
10
  • 34
    As noted in MySQL docs, It's not safe to assign and read variables in a single statement. The order of operations is not guaranteed. So the only safe method is #4
    – AMIB
    Commented Jan 27, 2013 at 10:01
  • 9
    You know, I never thought there'd be a practical use for that stupid interview question asking to swap two variables without using a temporary, but here it is, and for integers this would actually work: update swap_test set x=x+y,y=x-y,x=x-y;
    – izak
    Commented Sep 15, 2014 at 13:15
  • 24
    @Jhawins That's because beerpla.net is my blog. Commented May 26, 2015 at 21:26
  • 1
    Your answers made me know it was feasible and your approach #4 is exactly what i needed. This was more insight full then the mysql manual. Commented Feb 9, 2017 at 9:08
  • 1
    It is 22:30, I just ran a bulk product insert on a live DB serving 100K+ users. I swapped the column names around by mistake and was not happy about the fact that I had to now sit and figure out a way to fix this, so I came here instead. You just gave me exactly what I was looking for. Thank you, and the op sincerely. Commented Dec 28, 2020 at 20:29
63
+100

You could take the sum and subtract the opposing value using X and Y

UPDATE swaptest SET X=X+Y,Y=X-Y,X=X-Y;

Here is a sample test (and it works with negative numbers)

mysql> use test
Database changed
mysql> drop table if exists swaptest;
Query OK, 0 rows affected (0.03 sec)

mysql> create table swaptest (X int,Y int);
Query OK, 0 rows affected (0.12 sec)

mysql> INSERT INTO swaptest VALUES (1,2),(3,4),(-5,-8),(-13,27);
Query OK, 4 rows affected (0.08 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM swaptest;
+------+------+
| X    | Y    |
+------+------+
|    1 |    2 |
|    3 |    4 |
|   -5 |   -8 |
|  -13 |   27 |
+------+------+
4 rows in set (0.00 sec)

mysql>

Here is the swap being performed

mysql> UPDATE swaptest SET X=X+Y,Y=X-Y,X=X-Y;
Query OK, 4 rows affected (0.07 sec)
Rows matched: 4  Changed: 4  Warnings: 0

mysql> SELECT * FROM swaptest;
+------+------+
| X    | Y    |
+------+------+
|    2 |    1 |
|    4 |    3 |
|   -8 |   -5 |
|   27 |  -13 |
+------+------+
4 rows in set (0.00 sec)

mysql>

Give it a try!!!

4
54

The following code works for all scenarios in my quick testing:

UPDATE swap_test
   SET x=(@temp:=x), x = y, y = @temp
4
  • UPDATE table swap_test? Shouldn't it be UPDATE swap_test?
    – Pang
    Commented Sep 14, 2016 at 7:52
  • Thank you. This worked like a charm on MySql 8.0.23 and MySql 5.7.31 Commented Nov 4, 2021 at 18:54
  • Do the parentheses ensure that @temp is set prior to any other operations being performed? (MySQL doesn't always set variables in the order defined by the UPDATE statement, so I want to be sure).
    – pbarney
    Commented Dec 7, 2022 at 19:12
  • 1
    While a simple TEST works, you still do get a warning: "Setting user variables within expressions is deprecated and will be removed in a future release. Consider alternatives: 'SET variable=expression, ...', or 'SELECT expression(s) INTO variables(s)'.", which should not be ignored.
    – Luuk
    Commented May 9, 2023 at 13:58
14

UPDATE table SET X=Y, Y=X will do precisely what you want (in PostgreSQL, not MySQL, see below). The values are taken from the old row and assigned to a new copy of the same row, then the old row is replaced. You do not have to resort to using a temporary table, a temporary column, or other swap tricks.

@D4V360: I see. That is shocking and unexpected. I use PostgreSQL and my answer works correctly there (I tried it). See the PostgreSQL UPDATE docs (under Parameters, expression), where it mentions that expressions on the right hand side of SET clauses explicitly use the old values of columns. I see that the corresponding MySQL UPDATE docs contain the statement "Single-table UPDATE assignments are generally evaluated from left to right" which implies the behaviour you describe.

Good to know.

4
  • Thanks Greg and D4V360, good to know the differences in PostgreSQL and MySQL about the behavior of the update queries.
    – Vijay Dev
    Commented Oct 25, 2008 at 16:41
  • The "x=y, y=x" approach also works in Oracle, for what it's worth.
    – Burhan Ali
    Commented Oct 17, 2012 at 16:52
  • 2
    I used PostgreSQL and SET X=Y, Y=X saved me :)
    – Anonymous
    Commented Jun 28, 2013 at 10:00
  • 6
    IMHO this answer is a mess - bad advice with "oops never mind" appended. Half of it should be a comment and the only part of the remainder that's relevant to the question is the link to MySQL docs...
    – Air
    Commented Jan 27, 2014 at 22:57
7

Ok, so just for fun, you could do this! (assuming you're swapping string values)

mysql> select * from swapper;
+------+------+
| foo  | bar  |
+------+------+
| 6    | 1    |
| 5    | 2    |
| 4    | 3    |
+------+------+
3 rows in set (0.00 sec)

mysql> update swapper set
    -> foo = concat(foo, "###", bar),
    -> bar = replace(foo, concat("###", bar), ""),
    -> foo = replace(foo, concat(bar, "###"), "");

Query OK, 3 rows affected (0.00 sec)
Rows matched: 3  Changed: 3  Warnings: 0

mysql> select * from swapper;
+------+------+
| foo  | bar  |
+------+------+
| 1    | 6    |
| 2    | 5    |
| 3    | 4    |
+------+------+
3 rows in set (0.00 sec)

A nice bit of fun abusing the left-to-right evaluation process in MySQL.

Alternatively, just use XOR if they're numbers. You mentioned coordinates, so do you have lovely integer values, or complex strings?

The XOR stuff works like this by the way:

update swapper set foo = foo ^ bar, bar = foo ^ bar, foo = foo ^ bar;
6

As other answers point out, a simple swap won't work with MySQL because it caches the value of column 1 immediately before processing column 2, resulting in both columns being set to the value of column 2.

Given that the order of operations is not guaranteed in MySQL, using a temporary variable is also not reliable.

The only safe way to swap two columns without modifying the table structure is with an inner join, which requires a primary key (id in this case).

UPDATE mytable t1, mytable t2
SET t1.column1 = t1.column2,
    t1.column2 = t2.column1
WHERE t1.id = t2.id;

This will work without any issues.

0
6

ALTER TABLE table ADD COLUMN tmp;
UPDATE table SET tmp = X;
UPDATE table SET X = Y;
UPDATE table SET Y = tmp;
ALTER TABLE table DROP COLUMN tmp;
Something like this?

About Greg's comment: No, this doesn't work:

mysql> select * from test;
+------+------+
| x    | y    |
+------+------+
|    1 |    2 |
|    3 |    4 |
+------+------+
2 rows in set (0.00 sec)

mysql> update test set x=y, y=x;
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2  Changed: 2  Warnings: 0

mysql> select * from test;
+------+------+
| x    | y    |
+------+------+
|    2 |    2 |
|    4 |    4 |
+------+------+
2 rows in set (0.00 sec)
2
  • Just for the record: This does work in PostgreSQL while it does not work in MySQL.
    – str
    Commented Oct 19, 2011 at 22:05
  • Re "Greg's comment": Do you mean Greg's answer? Or was the comment deleted? Commented Jun 30, 2023 at 12:18
5

I believe having an intermediate exchange variable is the best practice in such way:

update z set c1 = @c := c1, c1 = c2, c2 = @c

First, it works always; second, it works regardless of data type.

In spite of both

update z set c1 = c1 ^ c2, c2 = c1 ^ c2, c1 = c1 ^ c2

and

update z set c1 = c1 + c2, c2 = c1 - c2, c1 = c1 - c2

are working usually. Only for number data type by the way, and it is your responsibility to prevent overflow. You can not use XOR between signed and unsigned, and you also can not use sum for the overflowing possibility.

And

update z set c1 = c2, c2 = @c where @c := c1

is not working if c1 is 0 or NULL or zero length string or just spaces.

We need change it to

update z set c1 = c2, c2 = @c where if((@c := c1), true, true)

Here are the scripts:

mysql> create table z (c1 int, c2 int)
    -> ;
Query OK, 0 rows affected (0.02 sec)

mysql> insert into z values(0, 1), (-1, 1), (pow(2, 31) - 1, pow(2, 31) - 2)
    -> ;
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from z;
+------------+------------+
| c1         | c2         |
+------------+------------+
|          0 |          1 |
|         -1 |          1 |
| 2147483647 | 2147483646 |
+------------+------------+
3 rows in set (0.02 sec)

mysql> update z set c1 = c1 ^ c2, c2 = c1 ^ c2, c1 = c1 ^ c2;
ERROR 1264 (22003): Out of range value for column 'c1' at row 2
mysql> update z set c1 = c1 + c2, c2 = c1 - c2, c1 = c1 - c2;
ERROR 1264 (22003): Out of range value for column 'c1' at row 3

mysql> select * from z;
+------------+------------+
| c1         | c2         |
+------------+------------+
|          0 |          1 |
|          1 |         -1 |
| 2147483646 | 2147483647 |
+------------+------------+
3 rows in set (0.02 sec)

mysql> update z set c1 = c2, c2 = @c where @c := c1;
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2  Changed: 2  Warnings: 0

mysql> select * from z;
+------------+------------+
| c1         | c2         |
+------------+------------+
|          0 |          1 |
|         -1 |          1 |
| 2147483647 | 2147483646 |
+------------+------------+
3 rows in set (0.00 sec)

mysql> select * from z;
+------------+------------+
| c1         | c2         |
+------------+------------+
|          1 |          0 |
|          1 |         -1 |
| 2147483646 | 2147483647 |
+------------+------------+
3 rows in set (0.00 sec)

mysql> update z set c1 = @c := c1, c1 = c2, c2 = @c;
Query OK, 3 rows affected (0.02 sec)
Rows matched: 3  Changed: 3  Warnings: 0

mysql> select * from z;
+------------+------------+
| c1         | c2         |
+------------+------------+
|          0 |          1 |
|         -1 |          1 |
| 2147483647 | 2147483646 |
+------------+------------+
3 rows in set (0.00 sec)

mysql>update z set c1 = c2, c2 = @c where if((@c := c1), true, true);
Query OK, 3 rows affected (0.02 sec)
Rows matched: 3  Changed: 3  Warnings: 0

mysql> select * from z;
+------------+------------+
| c1         | c2         |
+------------+------------+
|          1 |          0 |
|          1 |         -1 |
| 2147483646 | 2147483647 |
+------------+------------+
3 rows in set (0.00 sec)
1
  • +1 for finally finding a good use for the stupid interview question where you have to swap two variables without a temporary ;-)
    – izak
    Commented Sep 15, 2014 at 13:16
4

Two alternatives

  1. Use a temporary table
  2. Investigate the XOR algorithm
2

This surely works! I've just needed it to swap Euro and SKK price columns. :)

UPDATE tbl SET X=Y, Y=@temp where @temp:=X;

The above will not work (ERROR 1064 (42000): You have an error in your SQL syntax)

2

In SQL Server, you can use this query:

update swaptable 
set col1 = t2.col2,
col2 = t2.col1
from swaptable t2
where id = t2.id
0
2

I've not tried it, but

UPDATE tbl SET @temp=X, X=Y, Y=@temp

Might do it.

1

Assuming you have signed integers in your columns, you may need to use CAST(a ^ b AS SIGNED), since the result of the ^ operator is an unsigned 64-bit integer in MySQL.

In case it helps anyone, here's the method I used to swap the same column between two given rows:

SELECT BIT_XOR(foo) FROM table WHERE key = $1 OR key = $2

UPDATE table SET foo = CAST(foo ^ $3 AS SIGNED) WHERE key = $1 OR key = $2

where $1 and $2 are the keys of two rows and $3 is the result of the first query.

1

Table name is customer. fields are a and b, swap a value to b;.

UPDATE customer SET a=(@temp:=a), a = b, b = @temp

I checked this is working fine.

1

Let's say you want to swap the value of first and last name in tb_user.

The safest would be:

  1. Copy tb_user. So you will have 2 tables: tb_user and tb_user_copy
  2. Use UPDATE INNER JOIN query
UPDATE tb_user a
INNER JOIN tb_user_copy b
ON a.id = b.id
SET a.first_name = b.last_name, a.last_name = b.first_name
1

You could change column names, but this is more of a hack. But be cautious of any indexes that may be on these columns.

1

You can apply the below query. It worked perfect for me.

Table name: studentname
only single column available: name


update studentnames
set names = case names
when "Tanu" then "dipan"
when "dipan" then "Tanu"
end;

or

update studentnames
set names = case names
when "Tanu" then "dipan"
else "Tanu"
end;
0
CREATE TABLE Names
(
F_NAME VARCHAR(22),
L_NAME VARCHAR(22)
);

INSERT INTO Names VALUES('Ashutosh', 'Singh'),('Anshuman','Singh'),('Manu', 'Singh');

UPDATE Names N1 , Names N2 SET N1.F_NAME = N2.L_NAME , N1.L_NAME = N2.F_NAME 
WHERE N1.F_NAME = N2.F_NAME;

SELECT * FROM Names;
0

This example swaps start_date and end_date for records where the dates are the wrong way round (when performing ETL into a major rewrite, I found some start dates later than their end dates. Down, bad programmers!).

In situ, I'm using MEDIUMINTs for performance reasons (like Julian days, but having a 0 root of 1900-01-01), so I was OK doing a condition of WHERE mdu.start_date > mdu.end_date.

The PKs were on all 3 columns individually (for operational / indexing reasons).

UPDATE monitor_date mdu
INNER JOIN monitor_date mdc
    ON mdu.register_id = mdc.register_id
    AND mdu.start_date = mdc.start_date
    AND mdu.end_date = mdc.end_date
SET mdu.start_date = mdu.end_date, mdu.end_date = mdc.start_date
WHERE mdu.start_date > mdu.end_date;
1
  • FYI: This code updated 145 / 108,456 records in 0.203 secs. It was a one off task and so performance was not critical. Commented Sep 6, 2018 at 9:37
0

Let's imagine this table and let's try to swap the m and f from the 'sex' table:

id name sex salary
1 A m 2500
2 B f 1500
3 C m 5500
4 D f 500
UPDATE sex
SET sex = CASE sex
WHEN 'm' THEN 'f'
ELSE 'm'
END;

So the updated table becomes:

id name sex salary
1 A f 2500
2 B m 1500
3 C f 5500
4 D m 500
1
  • This allows swapping values within a column. It does not help with the question where they need to be swapped across columns.
    – rahul
    Commented Sep 29, 2020 at 22:49
0

I had to just move a value from one column to the other (like archiving) and reset the value of the original column.
The below (reference of #3 from the accepted answer) worked for me.

Update MyTable set X= (@temp:= X), X = 0, Y = @temp WHERE ID= 999;
0

Swapping of column values using a single query:

UPDATE my_table SET a=@tmp:=a, a=b, b=@tmp;
1
0

If you want to swap all the columns where x is to y and y to x, use this query:

UPDATE table_name SET column_name = CASE column_name WHERE 'value of col is x' THEN 'swap it to y' ELSE 'swap it to x' END;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.