views:

70

answers:

2

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 #2's name to foo, and #1's name 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.

+4  A: 

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 )
David
+1, I didn't think this would work, but I tried it out (created a table, constraint, etc) and it does work
KM
+4  A: 

In SQL Server and Oracle, constraints are deferred, that's why you just issue this query:

UPDATE  mytable
SET     name = CASE name WHEN 'foo' THEN 'bar' ELSE 'foo' END
WHERE   name IN ('foo', 'bar')

As suggested in comments, it seems that you are using this in MySQL to maintain an ordered list (that was last time I encountered this problem).

In this case you may want to read the series of articles in my blog on how to do it in MySQL more efficiently:

Quassnoi
+1. Hibernate supports CASE statement in HQL: http://docs.jboss.org/hibernate/stable/core/reference/en/html/queryhql.html#queryhql-expressions
ChssPly76