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 - Well, first, I started googling a little bit and i found this SQL solution: UPDATE users SET firstName = (case when id = 1 then 'encryptedFirstName1' when id = 2 then 'encryptedFirstName2' when id = 3 then 'encryptedFirstName3' end) WHERE id in (1, 2, 3); Looks nice doesn’t it? But one senior developer at my first job, always asked me, can we do it differently?
Discussions

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
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
sqlite - Update multiple rows with different values in a single SQL query - Stack Overflow
Doesn´t make sense to me as you would need multiple where conditions to match each row. Could you please elaborate? 2021-01-12T12:09:56.443Z+00:00 ... To update a table with different values for a column1, given values on column2, one can do as follows for SQLite: More on stackoverflow.com
🌐 stackoverflow.com
Updating multiple rows with different values – SQLServerCentral Forums
Unfortunately many employees have ... with SQL statements. I have already developed the Query to pull all the necessary information should someone accidently make a mistake (EX: writing an UPDATE statement without specifying a WHERE clause --which has happened many times before), but now I am trying to write a script that will use the information I pulled from above and RE-INSERT the old value back into the appropriate table. The problem is that I am going to need to update multiple rows with DIFFERENT ... More on sqlservercentral.com
🌐 sqlservercentral.com
September 22, 2007
🌐
Edureka Community
edureka.co › home › community › categories › web development › php › mysql - update multiple rows with different...
MySQL - UPDATE multiple rows with different values in one query | Edureka Community
June 1, 2020 - Hello, I wanted to know how to UPDATE multiple rows with different values and I just don't get it ... in the WHERE and in the IF condition.Any ideas?
🌐
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 - To do this, we can use a SQL CASE statement to allow us to provide multiple values for a range of conditions, all within a single query: UPDATE users SET user_type = (CASE WHEN age >= 18 THEN 'ADULT' WHEN age < 18 THEN 'JUNIOR' END);
🌐
TablePlus
tableplus.com › blog › 2018 › 11 › how-to-update-multiple-rows-at-once-in-mysql.html
How to update multiple rows at once in MySQL? | TablePlus
November 12, 2018 - INSERT INTO students (id, score1, score2) VALUES (1, 5, 8), (2, 10, 8), (3, 8, 3), (4, 10, 7) ON DUPLICATE KEY UPDATE score1 = VALUES(score1), score2 = VALUES(score2); Need a good GUI Tool for MySQL? TablePlus is a modern, native tool with an elegant UI that allows you to simultaneously manage ...
Find elsewhere
🌐
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
In this case, we can use the CASE ... syntax: UPDATE table_name SET column_value = CASE column_name WHEN 'column_name1' THEN column_value1 WHEN 'column_name2' THEN column_value2 ELSE column_value END WHERE column_name IN('column_name1', 'column_name2');...
Published   July 23, 2025
🌐
Quora
quora.com › How-do-you-update-multiple-values-in-SQL
How to update multiple values in SQL - Quora
Use a WHERE clause that targets multiple rows. Example: UPDATE orders SET status = 'cancelled' WHERE order_date < '2024-01-01' AND status = 'pending'; 3) Update many rows with different values (row-specific)
🌐
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 - In this article, we’ll explore how to efficiently update multiple rows with different values in a single query to minimize database overhead and improve performance.
🌐
Quora
quora.com › How-do-I-update-multiple-rows-of-a-single-column-in-SQL
How to update multiple rows of a single column in SQL - Quora
Answer: Actually that’s real easy. The problem is trying NOT to update the rows you don’t want updated. Let’s assume that you have a column where a few, many or all of the values have a NULL value, but, for whatever reason they should have a value like true or false.
🌐
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....
🌐
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 - So I'll just write my findings here. as this version doesn't support VALUES clause yet, our only choice is to use the ugly CASE-WHEN syntax: UPDATE table_name SET changed_col = CASE comparison_col WHEN 'key1' THEN 'value1' WHEN 'key2' THEN 'value2' ...
🌐
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 - The SubmitButton_Click function saves the changed rows. ... It looks like you can pass the DataTable as a parameter and update it in bulk.
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 $fld => $value) {
       if (!array_key_exists($fld, $set)) {
           $set[$fld] = [ ];
       }
       $set[$fld][] = $value;
    }
}

$set1 = [ ];
foreach ($set as $fld => $values) {
    $set2 = "{$fld} = CASE";
    foreach ($values as $i => $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);
🌐
W3Schools
w3schools.com › sql › sql_update.asp
SQL UPDATE Statement
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition; Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE statement. The WHERE clause specifies which record(s) that should be updated.
🌐
SQLServerCentral
sqlservercentral.com › forums › topic › updating-multiple-rows-with-different-values
Updating multiple rows with different values – SQLServerCentral Forums
September 22, 2007 - Unfortunately many employees have ... with SQL statements. I have already developed the Query to pull all the necessary information should someone accidently make a mistake (EX: writing an UPDATE statement without specifying a WHERE clause --which has happened many times before), but now I am trying to write a script that will use the information I pulled from above and RE-INSERT the old value back into the appropriate table. The problem is that I am going to need to update multiple rows with DIFFERENT ...
🌐
SitePoint
sitepoint.com › databases
Multiple UPDATE, same column, different values, different WHERE conditions - Databases - SitePoint Forums | Web Development & Design Community
August 9, 2008 - I’ve found plenty of info around about updating multiple rows with the same value using “WHERE columname IN”, and I’ve got that down. But, I’m needing to UPDATE a column in multiple rows with a different value for each WHERE condition. My updates are being done as individual queries like this: UPDATE tablename SET widget='zamu-xxx' WHERE widget='zamu'; UPDATE tablename SET widget='flabu-yyy' WHERE widget='flabu'; Is there any way to do something like this in a single query?
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.