Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch values between rows in unique column

Let's say you had a table like this:

id | name
---+---------
1  | foo
2  | bar

There is a uniqueness constraint on the name column.

How would you set the row with id=2 to foo, and the row with id=1 to bar?

I know you could probably just assign temporary names to both then stick in the desired names, but that does not seem like the simplest way.

I am using Hibernate, so any Hibernate-specific tricks would be nice. This seems like a problem that affects all RDBMSes in general though.


1 Answers

In Sql Server you could update them both at the same time:

UPDATE table
SET Name = CASE WHEN ID = 1 THEN 'bar' ELSE 'foo' END
WHERE ID IN ( 1, 2 )
like image 194
David Avatar answered Apr 21 '26 06:04

David