Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL UPDATE statement to switch two values in two rows

I'm using SQL Server to swap two values in two rows. Let me show:

[ord] [name]
1     John
4     Jack
7     Pete
9     Steve
11    Mary

Say, I need to swap [ord] numbers for "Pete" and "Steve" to make this table to be like so:

[ord] [name]
1     John
4     Jack
9     Pete
7     Steve
11    Mary

This seems like a trivial task but I can't seem to write an SQL UPDATE statement for it.

like image 850
ahmd0 Avatar asked Nov 13 '11 01:11

ahmd0


People also ask

Can we update multiple rows in a single update statement?

Column values on multiple rows can be updated in a single UPDATE statement if the condition specified in WHERE clause matches multiple rows. In this case, the SET clause will be applied to all the matched rows.

Can we update two values in SQL?

Can we UPDATE multiple tables with a single SQL query? No, only 1 table can be updated with an UPDATE statement.


2 Answers

If 'Peter' and 'Steve' are unique in your table, this will do:

UPDATE TableX
SET ord = ( SELECT MIN(ord) + MAX(ord) 
            FROM TableX 
            WHERE name IN ('Peter', 'Steve')
          ) - ord
WHERE name IN ('Peter', 'Steve')

or (improved by @Erwin):

UPDATE TableX
SET ord = ( SELECT SUM(ord) 
            FROM TableX 
            WHERE name IN ('Peter', 'Steve')
          ) - ord
WHERE name IN ('Peter', 'Steve')
like image 152
ypercubeᵀᴹ Avatar answered Oct 29 '22 20:10

ypercubeᵀᴹ


Use a CASE expression:

UPDATE yourtable
SET [ord] = CASE [ord] WHEN 9 THEN 7
                       WHEN 7 THEN 9 END
WHERE [ord] IN (7, 9)
like image 25
Mark Byers Avatar answered Oct 29 '22 20:10

Mark Byers