You can do it this way:

UPDATE table_users
    SET cod_user = (case when user_role = 'student' then '622057'
                         when user_role = 'assistant' then '2913659'
                         when user_role = 'admin' then '6160230'
                    end),
        date = '12082014'
    WHERE user_role in ('student', 'assistant', 'admin') AND
          cod_office = '17389551';

I don't understand your date format. Dates should be stored in the database using native date and time types.

Answer from Gordon Linoff on Stack Overflow
🌐
Medium
medium.com › geekculture › update-multiple-rows-in-sql-with-different-values-at-once-7d2eddb0b85f
Update multiple rows in SQL with different values at once | by Tadej Golobic | Geek Culture | Medium
June 12, 2021 - let sql = 'UPDATE users u JOIN ('; for(let i = 0; i < res.length; i+=BATCH_SIZE) { let nestedSql = ''; for(let j = 0; i < BATCH_SIZE; j++) { const userData = res[i+j]; if (!userData) { break; } if (j != 0) { nestedSql += 'UNION ALL '; } nestedSql += `SELECT \"${data.id}\" as id, \"${data.firstName}\" as firstName `; } sql += `${nestedSql}) a on u.id = a.id SET u.firstName = a.firstName;`; await trx.raw(sql); } Now we can run this and it will do a bulk update of 3000 rows.
Discussions

sqlite - Update multiple rows with different values in a single SQL query - Stack Overflow
I have a SQLite database with table myTable and columns id, posX, posY. The number of rows changes constantly (might increase or decrease). If I know the value of id for each row, and the number o... More on stackoverflow.com
🌐 stackoverflow.com
mysql - Updating multiple rows with different values in one query - Database Administrators Stack Exchange
I am trying to understand how to UPDATE multiple rows with different values and I just don't get it. The solution is everywhere but to me it looks difficult to understand. For instance, two update... More on dba.stackexchange.com
🌐 dba.stackexchange.com
June 28, 2014
update statement: one target row, multiple source rows. What are the rules?
It may be 9,999,999,999 it results ... do it a different way and it results "blue" and you will pull your hair out for days to trying to figure out why. ... Welcome to MS Q&A and thank you for asking this question. In my understanding, if there is no OrderBy in the SQL Query (like your example here), after Inner-Join (Inner Join compares and finds all the matching rows in the table c), update query will always update the value of table t1 with the first ... More on learn.microsoft.com
🌐 learn.microsoft.com
5
0
Multiple rows updation in sql server
Hi experts , Below is the database which i have created in sql server . I have a datagridview in a form where a user in , column0 writes the productnames and in column2 writes the consumed quantity . The problem is that i dont know how to update… More on learn.microsoft.com
🌐 learn.microsoft.com
2
0
October 14, 2023
🌐
GeeksforGeeks
geeksforgeeks.org › sql › how-to-update-multiple-records-using-one-query-in-sql-server
How to Update Multiple Records Using One Query in SQL Server? - GeeksforGeeks
To update multiple records of a table based on a single condition in an SQL server, use this syntax: UPDATE table_name SET column_name = value WHERE condition; As you can see, we can update multiple values of a column in SQL server using an ...
Published   July 23, 2025
🌐
DEV Community
dev.to › chidioguejiofor › scenario-1-making-updates-to-multiple-fields-56hl
Scenario 1: When You Need to Update Multiple Rows with Different Values – The Smart Way! - DEV Community
September 30, 2024 - Here's an example of the generated SQL: UPDATE tickets SET amount = CASE WHEN id = :ticket_id_0 THEN :ticket_value_0 WHEN id = :ticket_id_1 THEN :ticket_value_1 WHEN id = :ticket_id_2 THEN :ticket_value_2 WHEN id = :ticket_id_3 THEN :ticket_value_3 ELSE amount END WHERE id IN (:ticket_ids);...
🌐
Baeldung
baeldung.com › home › sql queries › update multiple rows with different values with single query
Update Multiple Rows With Different Values With Single Query Baeldung on SQL
June 20, 2025 - However, when this code sets user_type, the CASE statement returns the different values of “ADULT” or “JUNIOR” based on the value of the age column in the row being updated. This alleviates the concerns of transactions and repetitive code, as mentioned in the previous section. This technique can be used for many different cases, simply by adding a new WHEN clause with the required condition and value. In this article, we’ve covered two ways of solving the problem of updating multiple fields in SQL with different values.
Top answer
1 of 8
45

There's a couple of ways to accomplish this decently efficiently.

First -
If possible, you can do some sort of bulk insert to a temporary table. This depends somewhat on your RDBMS/host language, but at worst this can be accomplished with a simple dynamic SQL (using a VALUES() clause), and then a standard update-from-another-table. Most systems provide utilities for bulk load, though

Second -
And this is somewhat RDBMS dependent as well, you could construct a dynamic update statement. In this case, where the VALUES(...) clause inside the CTE has been created on-the-fly:

WITH Tmp(id, px, py) AS (VALUES(id1, newsPosX1, newPosY1), 
                               (id2, newsPosX2, newPosY2),
                               ......................... ,
                               (idN, newsPosXN, newPosYN))

UPDATE TableToUpdate SET posX = (SELECT px
                                 FROM Tmp
                                 WHERE TableToUpdate.id = Tmp.id),
                         posY = (SELECT py
                                 FROM Tmp
                                 WHERE TableToUpdate.id = Tmp.id)


WHERE id IN (SELECT id
             FROM Tmp)

(According to the documentation, this should be valid SQLite syntax, but I can't get it to work in a fiddle)

2 of 8
28

One way: SET x=CASE..END (any SQL)

Yes, you can do this, but I doubt that it would improve performances, unless your query has a real large latency.

If the query is indexed on the search value (e.g. if id is the primary key), then locating the desired tuple is very, very fast and after the first query the table will be held in memory.

So, multiple UPDATEs in this case aren't all that bad.

If, on the other hand, the condition requires a full table scan, and even worse, the table's memory impact is significant, then having a single complex query will be better, even if evaluating the UPDATE is more expensive than a simple UPDATE (which gets internally optimized).

In this latter case, you could do:

 UPDATE table SET posX=CASE
      WHEN id=id[1] THEN posX[1]
      WHEN id=id[2] THEN posX[2]
      ...
      ELSE posX END [, posY = CASE ... END]
 WHERE id IN (id[1], id[2], id[3]...);

The total cost is given more or less by: NUM_QUERIES * ( COST_QUERY_SETUP + COST_QUERY_PERFORMANCE ). This way, you knock down on NUM_QUERIES (from N separate id's to 1), but COST_QUERY_PERFORMANCE goes up (about 3x in MySQL 5.28; haven't yet tested in MySQL 8).

Otherwise, I'd try with indexing on id, or modifying the architecture.

This is an example with PHP, where I suppose we have a condition that already requires a full table scan, and which I can use as a key:

// Multiple update rules 
$updates = [
   "fldA='01' AND fldB='X'" => [ 'fldC' => 12, 'fldD' => 15 ],
   "fldA='02' AND fldB='X'" => [ 'fldC' => 60, 'fldD' => 15 ],
   ...
];

The fields updated in the right hand expressions can be one or many, must always be the same (always fldC and fldD in this case). This restriction can be removed, but it would require a modified algorithm.

I can then build the single query through a loop:

$where = [ ];
$set   = [ ];
foreach ($updates as $when => $then) {
    $where[] = "({$when})";
    foreach ($then as value) {
       if (!array_key_exists(set)) {
           fld] = [ ];
       }
       fld][] = $value;
    }
}

$set1 = [ ];
foreach (fld => $values) {
    $set2 = "{$fld} = CASE";
    foreach ($values as value) {
        $set2 .= " WHEN {$where[$i]} THEN {$value}";
    }
    $set2 .= ' END';
    $set1[] = $set2;
}

// Single query
$sql  = 'UPDATE table SET '
      . implode(', ', $set1)
      . ' WHERE '
      . implode(' OR ', $where);

Another way: ON DUPLICATE KEY UPDATE (MySQL)

In MySQL I think you could do this more easily with a multiple INSERT ON DUPLICATE KEY UPDATE, assuming that id is a primary key keeping in mind that nonexistent conditions ("id = 777" with no 777) will get inserted in the table and maybe cause an error if, for example, other required columns (declared NOT NULL) aren't specified in the query:

INSERT INTO tbl (id, posx, posy, bazinga)
     VALUES (id1, posY1, posY1, 'DELETE'),
     ...
ON DUPLICATE KEY SET posx=VALUES(posx), posy=VALUES(posy);

DELETE FROM tbl WHERE bazinga='DELETE';

The 'bazinga' trick above allows to delete any rows that might have been unwittingly inserted because their id was not present (in other scenarios you might want the inserted rows to stay, though).

For example, a periodic update from a set of gathered sensors, but some sensors might not have been transmitted:

INSERT INTO monitor (id, value)
VALUES (sensor1, value1), (sensor2, 'N/A'), ...
ON DUPLICATE KEY UPDATE value=VALUES(value), reading=NOW();

(This is a contrived case, it would probably be more reasonable to LOCK the table, UPDATE all sensors to N/A and NOW(), then proceed with INSERTing only those values we do have).

A third way: CTE (Any SQL)

This is conceptually almost the same as the INSERT MySQL trick. As written, it works in PostgreSQL 9.6:

WITH updated(id, posX, posY) AS (VALUES
    (id1, posX1, posY1), 
    (id2, posX2, posY2),
    ...
)
UPDATE myTable
    SET 
    posX = updated.posY,
    posY = updated.posY
FROM updated
WHERE (myTable.id = updated.id);
Find elsewhere
🌐
DataCamp
datacamp.com › tutorial › update-multiple-columns-sql
How to Update Multiple Columns in SQL | DataCamp
November 8, 2024 - My writing bridges technical depth ... and accuracy. Yes, you can update multiple rows with different values by using conditions in the WHERE clause or applying logic within the CASE statement....
🌐
w3tutorials
w3tutorials.net › blog › update-multiple-rows-with-different-values-in-a-single-sql-query
How to Update Multiple Rows with Different Values in a Single SQL Query (SQLite Example) — w3tutorials.net
This sets salary to NULL for employees not in the CASE UPDATE employees SET salary = CASE WHEN id = 1 THEN 75000 END; ... Problem: Using VALUES with older SQLite versions (pre-3.33.0). Fix: Use UNION ALL instead (see Older SQLite Versions).
Top answer
1 of 5
1

Hi @vy ,

Welcome to the Microsoft SQL Server Q&A Forum!

Regarding your question, I checked some documents.The conclusion drawn from my own perspective is as follows:

When describing the contents of a table, most people usually display the rows in a specific order. But the table actually represents a collection, and the collection has no order. (Tables with clustered index added are stored in the order of the clustered index columns).

The virtual table(there is no order like a normal table) returned by the inner join operator is as follows:

    id  color   id  color  
    1 NULL 1 red  
    1 NULL 1 blue  

The update statement returns a row from the virtual table to update the t1.color column. The column that satisfies the condition t1.id = c.id has two columns. It is uncertain which column is returned.SQL Server will return the row that happened to be accessed first.Therefore, different results may be produced, but they can all be considered correct. If you want to ensure the certainty of the results, you can choose to include a unique order by list.

Take the select statement as an example:

select top(1) *  
from c   
order by color  

The above select statement specifies a unique order by list (the color field is unique), so the returned result is certain.

The result returned by the following statement is not certain (of course they are all considered correct):

select top(1) *  
from c   
order by id  
  
select top(1) *  
from c   

In short, SQL Server will return the row that happens to be accessed first, and which row is accessed first is up to the developer.

If you have any question, please feel free to let me know.
If the response is helpful, please click "Accept Answer" and upvote it.

Regards
Echo


If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

2 of 5
1

It's not deterministic. Tom said "random", but that's inexact. As long as the query plan is the same, it is very likely that you will get the same value every time. At least if the plan is serial. But if the plan changes - you could also get a different value.

The important thing is that you cannot rely on anything here. Not even the value being randomly chosen.

🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 1391320 › multiple-rows-updation-in-sql-server
Multiple rows updation in sql server - Microsoft Q&A
October 14, 2023 - Use EF Core, for example in the following I take the liberty to change column names. Not sure why CurrentQuantity is a decimal and not an int but left it as is. CREATE TABLE [dbo].[Products]( [Id] [INT] IDENTITY(1,1) NOT NULL, [ProductName] [NVARCHAR](MAX) NULL, [CurrentQuantity] [DECIMAL](10, 2) NULL, CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
🌐
W3Schools
w3schools.com › sql › sql_update.asp
SQL UPDATE Statement
SQL Examples SQL Editor SQL Quiz ... is used to update or modify one or more records in a table. UPDATE table_name SET column1 = value1, column2 = value2, ......
🌐
Quora
quora.com › How-do-you-update-multiple-values-in-SQL
How to update multiple values in SQL - Quora
Use a single UPDATE with multiple column assignments. Syntax: UPDATE table SET col1 = expr1, col2 = expr2, col3 = expr3 WHERE condition; Example: UPDATE employees SET salary = sala ...
🌐
DbSchema
dbschema.com › blog › tutorials › sql update statement – syntax, examples, and best practices | dbschema
SQL UPDATE Statement – Syntax, Examples, and Best Practices | DbSchema
August 23, 2025 - Let's say we want to update the Name of Alice to 'Alicia' and her Age to 24. The query would be: UPDATE Students SET Name = 'Alicia', Age = 24 WHERE StudentID = 2; ... In this case, both the Name and Age of the record with StudentID 2 were updated.
🌐
DEV Community
dev.to › azophy › how-to-update-multiple-rows-based-on-list-of-key-val-pairs-in-mysql-mariadb-postgresql-4lpp
How to update multiple rows based on list of key-val pairs (in MySQL, MariaDB, & PostgreSQL) - DEV Community
September 29, 2023 - MariaDB's VALUES clause is shorter as it doesn't use the ROW keyword at all · UPDATE table_name SET changed_col = temp_data.column1 FROM (VALUES ('key1', 'val1'), ('key2', 'val2'), .... ) as temp_data WHERE comparison_col = temp_data.column0 ...
Top answer
1 of 2
8

Couldn't find a SQL Server 2008 fiddle engine so I had to opt for a SQL Server 2014 ... so not sure if the following will work in SQL Server 2008, but fwiw ...

Setup some sample data:

create table Table1(id int, Date datetime null);
create table Table2(id int, Date datetime);

insert Table1 values (1,null)
insert Table1 values (1,null)
insert Table1 values (2,null)
insert Table1 values (2,null)
insert Table1 values (2,null);

insert Table2 values (1,'2013-01-29 08:50:00.000')
insert Table2 values (1,'2013-01-29 15:28:00.000')
insert Table2 values (2,'2013-01-31 11:56:00.000')
insert Table2 values (2,'2013-03-11 16:08:00.000')
insert Table2 values (2,'2013-01-31 14:04:00.000');

Keeping in mind that we haven't been provided (yet) with any means to determine which rows to match between Table1 and Table2 for a given id value, I'll just let row_number() generate a 'matching' rowid.

And then we'll make use of SQL Server's ability to update Table1 via a derived table definition:

update T1 
set    T1.Date=T2.Date

from   (select row_number() over(partition by id order by Date) as rowid,
               id,
               Date
        from   Table1 
        where  Date is NULL) T1

join   (select row_number() over(partition by id order by Date) as rowid,
               id,
               Date
        from   Table2) T2

on      T1.id    = T2.id
and     T1.rowid = T2.rowid;

And the results:

select * from Table1;

id  Date
--- --------------------
1   2013-01-29T08:50:00Z
1   2013-01-29T15:28:00Z
2   2013-01-31T11:56:00Z
2   2013-01-31T14:04:00Z
2   2013-03-11T16:08:00Z

And here's a SQL Fiddle for the above.

2 of 2
3

You stated that the order of the matching matters but it seems like you don't have anything to ORDER BY in table 1 to create a guaranteed order to match the other table and there is no way in SQL Server to order the rows after insertion date, because information about that is not stored. With this in mind it’s not possible to do a matching with the result you want. There is a solution to update the rows with an arbitrary match within each id. If that would be good enough.

UPDATE t 
SET    t.[date] = tt.[date] 
FROM   (SELECT *, 
               Row_number() 
                 OVER ( 
                   partition BY id 
                   ORDER BY [date]) AS rno 
        FROM   Table1) AS t 
       INNER JOIN (SELECT *, 
                          Row_number() 
                            OVER ( 
                              partition BY id 
                              ORDER BY [date]) AS rno 
                   FROM   Table2) AS tt 
               ON t.id = tt.id 
                  AND t.rno = tt.rno 

This solution will match all rows individually but can't guarantee the order.

DB Fiddle