Mysql

UPDATE multiple rows with different values in one query in MySQL

25 September 2026 · 11 min read

UPDATE multiple rows with different values in one query in MySQL

Imagine needing to update a database table with a substantial number of rows, each requiring a unique set of changes. Manually executing individual UPDATE statements would be incredibly time-consuming and inefficient. Fortunately, MySQL provides powerful techniques to UPDATE multiple rows with different values in one query. This approach not only streamlines the update process but also significantly improves performance, especially when dealing with large datasets. This article explores the various methods available, providing you with practical examples and best practices to efficiently manage bulk updates in your MySQL databases. We’ll delve into using the CASE statement, temporary tables, and other advanced techniques to optimize your database operations. This guide provides a complete guide to efficiently update several rows in MySQL at once.

Understanding the Need for Bulk Updates

In many real-world scenarios, database administrators and developers frequently encounter situations where multiple rows need updating simultaneously with different values. Consider an e-commerce platform where product prices change based on promotional campaigns, or a content management system where multiple articles need to be assigned to different categories. Performing these updates one row at a time is not only tedious but also resource-intensive. Each individual UPDATE statement requires a separate database connection and execution, leading to significant overhead and slower performance. According to a study by Percona, bulk updates using a single query can improve performance by up to 80% compared to individual updates Percona Website. Therefore, mastering the techniques for UPDATE multiple rows with different values in one query is crucial for efficient database management.

Choosing the right method for bulk updates depends on factors such as the complexity of the updates, the size of the dataset, and the database server’s resources. For simple updates, the CASE statement might suffice, while more complex scenarios might require temporary tables or stored procedures. It’s also essential to consider the potential impact on database performance and implement appropriate indexing and optimization strategies. Incorrectly implemented bulk updates can lead to table locks and performance bottlenecks, affecting the overall responsiveness of the application. Therefore, a thorough understanding of the available techniques and their implications is essential for effective database management.

Before diving into specific techniques, it’s important to understand the ACID properties of database transactions: Atomicity, Consistency, Isolation, and Durability. When performing bulk updates, ensuring that these properties are maintained is crucial. Transactions provide a mechanism to group multiple UPDATE statements into a single logical unit of work. If any of the updates fail, the entire transaction can be rolled back, ensuring that the database remains in a consistent state. This is particularly important when dealing with critical data where data integrity is paramount.

Using the CASE Statement for Conditional Updates

The CASE statement is a powerful construct in SQL that allows for conditional logic within a query. When it comes to updating multiple rows with different values, the CASE statement can be used to specify different update values based on certain conditions. This approach is particularly useful when the update values are based on existing data within the table or on specific criteria that can be evaluated within the query. The basic syntax involves using the CASE statement within the SET clause of the UPDATE statement. Each WHEN clause specifies a condition, and the corresponding THEN clause specifies the value to be assigned if the condition is met. The ELSE clause (optional) provides a default value if none of the conditions are met.

Here’s an example of how to use the CASE statement to update the price column in a products table based on the product category:

UPDATE products SET price = CASE WHEN category = 'Electronics' THEN price  1.10 WHEN category = 'Clothing' THEN price  0.90 ELSE price END; 

In this example, electronic products will have their prices increased by 10%, clothing products will have their prices decreased by 10%, and the prices of products in other categories will remain unchanged. This demonstrates how the CASE statement allows for flexible and conditional updates within a single query. This method is generally suitable for scenarios where the number of distinct update values is relatively small and the conditions are straightforward. For more complex scenarios involving a large number of distinct values or more intricate conditions, other techniques might be more appropriate.

The CASE statement can also be combined with other SQL functions and operators to create more complex update logic. For example, you can use the IN operator to specify multiple values within a WHEN clause, or you can use the BETWEEN operator to specify a range of values. Furthermore, you can nest CASE statements within each other to create more intricate conditional logic. While the CASE statement provides a powerful and flexible way to UPDATE multiple rows with different values in one query, it’s important to ensure that the query remains readable and maintainable. Overly complex CASE statements can be difficult to understand and debug, so it’s often a good idea to break down complex logic into smaller, more manageable components.

Leveraging Temporary Tables for Complex Updates

When dealing with more complex update scenarios, such as those involving calculations based on data from multiple tables or a large number of distinct update values, temporary tables can provide a more efficient and manageable solution. A temporary table is a table that exists only for the duration of the current database session. You can create a temporary table, populate it with the data you need for the updates, and then use it to update the target table. This approach allows you to pre-calculate the update values and store them in a temporary table, making the final UPDATE statement simpler and more efficient.

Here’s an example of how to use a temporary table to update the order_status column in an orders table based on data from an order_items table:

CREATE TEMPORARY TABLE temp_order_status AS SELECT order_id, CASE WHEN SUM(CASE WHEN shipped = 0 THEN 1 ELSE 0 END) > 0 THEN 'Pending' ELSE 'Shipped' END AS new_status FROM order_items GROUP BY order_id; UPDATE orders INNER JOIN temp_order_status ON orders.order_id = temp_order_status.order_id SET orders.order_status = temp_order_status.new_status; DROP TEMPORARY TABLE IF EXISTS temp_order_status; 

In this example, we first create a temporary table called temp_order_status that contains the order_id and the calculated new_status for each order. We then use an UPDATE statement with an INNER JOIN to update the order_status column in the orders table based on the data in the temporary table. Finally, we drop the temporary table to clean up the database. This approach is particularly useful when the update logic involves complex calculations or aggregations that would be difficult to perform directly within the UPDATE statement. Temporary tables allow you to break down the update process into smaller, more manageable steps, improving readability and maintainability.

When using temporary tables, it’s important to consider the potential impact on database performance. Creating and populating a temporary table can be resource-intensive, especially for large datasets. Therefore, it’s essential to optimize the queries used to populate the temporary table and to ensure that the temporary table is properly indexed. Additionally, it’s important to drop the temporary table after it’s no longer needed to avoid cluttering the database and consuming unnecessary resources. Temporary tables are a powerful tool for UPDATE multiple rows with different values in one query but should be used judiciously and with careful consideration of their potential impact on database performance. Always remember to drop the temporary table after the updates are complete. MySQL Temporary Tables Documentation

Optimizing Performance for Bulk Updates

While the techniques discussed above provide effective ways to UPDATE multiple rows with different values in one query, it’s crucial to optimize the performance of these updates, especially when dealing with large datasets. Several factors can impact the performance of bulk updates, including indexing, transaction size, and query optimization. Implementing appropriate optimization strategies can significantly reduce the execution time of bulk updates and minimize their impact on overall database performance. Here are some key optimization techniques:

  • Indexing: Ensure that the columns used in the WHERE clause of the UPDATE statement and in the JOIN conditions (if any) are properly indexed. Indexes allow the database server to quickly locate the rows that need to be updated, avoiding a full table scan.
  • Transaction Size: For very large updates, it’s often beneficial to break the updates into smaller batches within a transaction. This reduces the risk of long-running transactions that can lock the table and block other operations.
  • Query Optimization: Use the EXPLAIN statement to analyze the query execution plan and identify potential performance bottlenecks. Optimize the query by rewriting it, adding indexes, or using hints.

Another important aspect of performance optimization is minimizing the number of rows that are actually updated. If possible, add conditions to the WHERE clause to only update rows that need to be changed. This reduces the amount of data that needs to be written to disk, improving performance. Furthermore, consider using the SQL_SAFE_UPDATES mode to prevent accidental updates that could affect a large number of rows. This mode requires you to specify a WHERE clause with a key column, preventing updates that could potentially modify the entire table unintentionally. “Proper indexing is crucial for efficient UPDATE operations,” says database expert, Sarah Jones.

Finally, monitoring the performance of bulk updates is essential for identifying and addressing potential issues. Use database monitoring tools to track query execution time, resource utilization, and locking activity. This allows you to proactively identify performance bottlenecks and implement appropriate optimization strategies. Effective performance optimization is an ongoing process that requires continuous monitoring and tuning. By implementing the techniques discussed above, you can ensure that your bulk updates are performed efficiently and with minimal impact on overall database performance. Efficiently update database rows.

Real-World Examples and Use Cases

To further illustrate the practical applications of UPDATE multiple rows with different values in one query, let’s consider some real-world examples and use cases. These examples demonstrate how the techniques discussed above can be applied to solve common database update problems in various industries and applications.

  • E-commerce: Updating product prices based on promotional campaigns or competitor pricing. This can be achieved using the CASE statement to apply different discounts or markups based on product category or other criteria.
  • Content Management Systems (CMS): Assigning multiple articles to different categories or updating the publication status of multiple articles simultaneously. Temporary tables can be used to pre-calculate the new category or status based on complex criteria.
  • Financial Systems: Updating account balances based on transactions. Bulk updates can be used to apply interest payments or fees to multiple accounts simultaneously.

Consider a scenario where you need to update the shipping status of multiple orders in an e-commerce system. You can use a temporary table to store the order IDs and their corresponding shipping statuses, and then use an UPDATE statement with an INNER JOIN to update the orders table. This approach allows you to efficiently update the shipping status of multiple orders in a single query, improving performance and reducing the load on the database server. Another common use case is updating customer loyalty points based on their purchase history. You can use a temporary table to calculate the new loyalty points for each customer and then use an UPDATE statement to update the customers table. These examples demonstrate the versatility and practicality of the techniques discussed in this article.

Infographic here
These real-world examples highlight the importance of mastering the techniques for **UPDATE multiple rows with different values in one query**. By understanding the available methods and their respective strengths and weaknesses, you can choose the most appropriate approach for your specific use case and optimize the performance of your database updates. Whether you're managing an e-commerce platform, a content management system, or a financial system, the ability to efficiently update multiple rows with different values is crucial for maintaining data integrity and ensuring optimal performance. Always remember to test your update queries thoroughly before deploying them to a production environment to avoid unintended consequences.

FAQ

What is the best way to update multiple rows with different values in MySQL?

The best approach depends on the complexity of the updates. For simple conditional updates, the CASE statement is often sufficient. For more complex scenarios involving calculations or data from multiple tables, temporary tables may be more appropriate.

How can I optimize the performance of bulk updates in MySQL?

Ensure that the columns used in the WHERE clause and JOIN conditions are properly indexed. Break large updates into smaller batches within a transaction. Use the EXPLAIN statement to analyze the query execution plan and identify potential performance bottlenecks Question & Answer :

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, three updates into 1 query:

UPDATE table_users SET cod_user = '622057' , date = '12082014' WHERE user_rol = 'student' AND cod_office = '17389551'; UPDATE table_users SET cod_user = '2913659' , date = '12082014' WHERE user_rol = 'assistant' AND cod_office = '17389551'; UPDATE table_users SET cod_user = '6160230' , date = '12082014' WHERE user_rol = 'admin' AND cod_office = '17389551'; 

I read an example, but I really don’t understand how to make the query. i.e:

UPDATE table_to_update SET cod_user= IF(cod_office = '17389551','622057','2913659','6160230') ,date = IF(cod_office = '17389551','12082014') WHERE ?? IN (??) ; 

I’m not entirely clear how to do the query if there are multiple condition in the WHERE and in the IF condition..any ideas?

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.