In Oracle SQL, you can use the CASE statement within an UPDATE statement to conditionally update rows based on specific criteria. Here's a basic syntax example:
UPDATE table_name
SET column_name =
CASE
WHEN condition1 THEN value1
WHEN condition2 THEN value2
...
ELSE default_value
END
WHERE condition;
Let's break down the components:
table_name: The name of the table you want to update.
column_name: The name of the column you want to update.
condition1, condition2, etc.: Conditions that evaluate to either true or false. These conditions determine which rows will be updated.
value1, value2, etc.: The values to set for the column if the corresponding condition is true.
default_value: The value to set if none of the conditions are true.
WHERE condition: An optional condition that further filters the rows to be updated. If omitted, all rows in the table will be updated.
Here's a concrete example:
Let's say we have a table called employees with columns salary and department. We want to give a 10% salary increase to employees in the "IT" department and a 5% increase to employees in the "HR" department.
UPDATE employees
SET salary =
CASE
WHEN department = 'IT' THEN salary * 1.1
WHEN department = 'HR' THEN salary * 1.05
ELSE salary
END
WHERE department IN ('IT', 'HR');
In this example:
- If an employee is in the "IT" department, their salary is increased by 10%.
- If an employee is in the "HR" department, their salary is increased by 5%.
- Employees in other departments remain unchanged.
Always ensure your UPDATE statements are well-tested and verified before running them, especially if they affect a large number of rows or critical data.