Thursday, January 2, 2025

How can you update multiple values in one column in SQL?

 In SQL, if you want to update multiple values in a single column for different rows, you can use the UPDATE statement along with a CASE expression. This allows you to conditionally update each row with a different value based on a specific condition.

Here’s a general syntax:

UPDATE table_name
SET column_name = CASE
    WHEN condition1 THEN new_value1
    WHEN condition2 THEN new_value2
    WHEN condition3 THEN new_value3
    -- Add more conditions as needed
    ELSE column_name -- Optional, if you want to retain the original value for unmatched rows
END
WHERE some_condition;

Example:

Let’s say you have a table employees with the columns employee_id and salary, and you want to update the salaries of specific employees.

UPDATE employees
SET salary = CASE
    WHEN employee_id = 1 THEN 50000
    WHEN employee_id = 2 THEN 60000
    WHEN employee_id = 3 THEN 70000
    ELSE salary  -- If employee_id is not 1, 2, or 3, retain the current salary
END
WHERE employee_id IN (1, 2, 3);

Explanation:

  • The CASE statement evaluates each row individually.
  • Based on the condition, it assigns the new value to the salary column.
  • The WHERE clause ensures that only rows with employee_id values of 1, 2, or 3 are updated.

This approach is useful when you need to update different rows with different values in a single update query.

No comments:

Post a Comment