Sunday, December 29, 2024

How can you update multiple records in MySQL with one query?

 In MySQL, you can update multiple records with a single query using the CASE statement inside the UPDATE query. This allows you to update different rows with different values based on a condition. Here's a general example:

UPDATE your_table
SET column_name = CASE 
    WHEN condition1 THEN value1
    WHEN condition2 THEN value2
    WHEN condition3 THEN value3
    ELSE column_name
END
WHERE some_condition;

Example:

Suppose you have a products table and want to update the price for different products based on their product_id.

UPDATE products
SET price = CASE 
    WHEN product_id = 1 THEN 100
    WHEN product_id = 2 THEN 150
    WHEN product_id = 3 THEN 200
    ELSE price
END
WHERE product_id IN (1, 2, 3);

Explanation:

  • CASE allows setting different values for price based on the product_id.
  • The WHERE clause ensures that the update is applied only to the specified rows (product_id 1, 2, and 3).
  • This approach is efficient because it sends only one query to update multiple rows at once.

No comments:

Post a Comment