tags:

views:

161

answers:

4

Hi,

I have a SQL table like this.

id          Order
======== =========
1                4
2                3
3                5
4                1
5                2

Is it possible to update multiple rows in 1 sql statement? i.e. I want to update id = 3, order = 1 and id = 5, order = 4 and id = 1, order = 1

I know how to do that in 3 update statements. But I would like to know if I can update 3 rows in 1 sql update statement.

Thank you.

A: 

You can use CASE if your DBMS supports it.

Marius Burz
A: 

Try something like this:

update Orders
set 
  Order = (
    case 
      when id = 3 then 1
      when id = 5 then 4
      when id = 1 then 1
where id in (3, 5, 1)

Depends on your database though.

Lance Fisher
+4  A: 

You can do this with a single UPDATE statement, but I wouldn't bother.

It makes more sense to use three separate updates in this situation. Trying to do it with one statement makes your code less readable and more error-prone.

But if you really want the single statement, here you go:

UPDATE your_table
SET order = CASE id
                WHEN 3 THEN 1
                WHEN 5 THEN 4
                WHEN 1 THEN 1
            END
WHERE id IN (3, 5, 1)
LukeH
+2  A: 

Why do you want to update three rows in one statement?

If the rows must all be in sync with one another, you can do:

BEGIN TRANSACTION;
UPDATE... ;
UPDATE... ;
UPDATE... ;
COMMIT

That way, all work between the begin and commit, is either all completed or none of it is done. This is a key feature of SQL-based relational databases. Even SQLITE has this capability.

Michael Dillon
Right. Unless you go deeper down the rabbit hole and discover that those two things are not necessarily identical. See transaction isolation levels.
Marius Burz