Okay, you want to update rows in an Oracle table (target_table) using data derived from a SELECT statement (which might involve joins to other tables). There are several common ways to achieve this in Oracle, each with its own syntax, performance characteristics, and ideal use cases.
Here are the main methods:
-
Using a Correlated Subquery in the SET Clause:
-
Using the MERGE Statement:
- The
MERGE statement is specifically designed for combining INSERT, UPDATE, and DELETE operations based on whether rows from a source match rows in a target. It's excellent for "upsert" scenarios but is also very powerful and often the most performant way to do a bulk update from a source query.
- Syntax:
MERGE INTO target_table tt
USING (
SELECT join_column, source_column_1, source_column_2 -- Select all needed columns from source
FROM source_table st
-- You can join multiple tables here within this subquery
WHERE ... -- Filter source data if needed
) source
ON (tt.join_column = source.join_column) -- Join condition between target and source results
WHEN MATCHED THEN
UPDATE SET
tt.column_to_update_1 = source.source_column_1,
tt.column_to_update_2 = source.source_column_2
-- You can add a WHERE clause here to conditionally update
-- WHERE tt.some_column <> source.some_column -- Example: only update if values differ
;
- Explanation:
MERGE INTO target_table tt: Specifies the table to merge into.
USING (SELECT ...) source: This defines the source data. It can be a table, view, or most commonly, a SELECT statement (inline view). Alias the source data (here, source).
ON (condition): This is the join condition that links rows from target_table (tt) with rows from the source results.
WHEN MATCHED THEN UPDATE SET ...: This block executes for every row in target_table that finds a match in the source results based on the ON condition. You list the columns to update and their new values from the source.
- (Optional)
WHEN NOT MATCHED THEN INSERT ...: You can include this clause if you want to insert rows from the source that don't have a match in the target. Omit it if you only want to update existing rows.
- (Optional)
WHEN MATCHED THEN DELETE WHERE condition: You can add a DELETE clause to remove matching target rows based on a specific condition after the UPDATE (or instead of the UPDATE).
- Pros: Often the most efficient method for bulk updates and merges. Explicit join condition. Can update multiple columns easily. Handles complex source queries well within the clause.
-
Using an Updatable Join View (Inline View):
- Oracle allows updating certain "updatable views", including simple join views that meet specific criteria (often referred to as key-preserved tables). You can use this concept with an inline view.
- Syntax:
UPDATE (
SELECT tt.column_to_update_1, tt.column_to_update_2,
st.source_column_1, st.source_column_2
FROM target_table tt
JOIN source_table st ON tt.join_column = st.join_column
WHERE ... -- Add any filtering conditions for the rows to consider
) joined_data
SET
joined_data.column_to_update_1 = joined_data.source_column_1,
joined_data.column_to_update_2 = joined_data.source_column_2;
- Explanation:
- You create an inline view (the
SELECT statement in parentheses) that joins your target_table with the source_table. This view selects the target columns you want to update and the source columns containing the new values.
- You then
UPDATE this inline view, setting the selected target columns (joined_data.column_to_update_1) to the values from the selected source columns (joined_data.source_column_1).
- Important: This method only works if the inline view is updatable according to Oracle's rules. Generally, this means that the join must be simple and the columns being updated must belong to a "key-preserved" table within the join (meaning the join doesn't create multiple rows in the view for a single row in the base table being updated). Aggregate functions, distinct, group by, etc., make a view non-updatable.
- Pros: Can be concise for simple joins. Direct join syntax.
- Cons: Limited by updatable view rules. Less flexible than
MERGE for complex scenarios or when source rows might not have a target match (as it will only update rows that do match in the join).
-
Using PL/SQL with a Cursor (Generally Not Recommended for Bulk Updates):
- You can write a PL/SQL block to loop through the results of your
SELECT statement and execute an individual UPDATE statement for each row.
- Syntax (Example):
DECLARE
CURSOR c_data IS
SELECT tt.rowid AS target_rowid, st.source_column_value
FROM target_table tt
JOIN source_table st ON tt.join_column = st.join_column
WHERE ... -- Filter for rows to update
;
-- Optional: Bulk collect for better performance than row-by-row
TYPE data_aat IS TABLE OF c_data%ROWTYPE INDEX BY PLS_INTEGER;
l_data data_aat;
l_limit CONSTANT PLS_INTEGER := 1000; -- Process in batches
BEGIN
OPEN c_data;
LOOP
FETCH c_data BULK COLLECT INTO l_data LIMIT l_limit;
FOR i IN 1..l_data.COUNT LOOP
-- Update the target table using ROWID for efficiency
UPDATE target_table
SET column_to_update = l_data(i).source_column_value
WHERE rowid = l_data(i).target_rowid;
END LOOP;
EXIT WHEN c_data%NOTFOUND;
END LOOP;
CLOSE c_data;
-- COMMIT; -- Remember to commit the transaction
EXCEPTION
WHEN OTHERS THEN
-- ROLLBACK; -- Handle errors
RAISE;
END;
/
- Explanation:
- A cursor selects the data needed from the source and identifies the corresponding rows in the target (using
ROWID is a common optimization within loops).
- A loop fetches data from the cursor. Bulk collection (
BULK COLLECT and LIMIT) is used to fetch multiple rows at once, which is much more efficient than fetching one row at a time.
- Inside the loop, for each fetched row, an individual
UPDATE statement is executed.
- Pros: Allows for complex row-by-row logic that might not be possible purely in SQL. Gives fine-grained control.
- Cons: Generally much less performant than set-based operations (
MERGE, Updatable View, sometimes Subquery) for large volumes of data. Executing individual UPDATE statements within a loop ("slow-by-slow processing") incurs significant overhead. Use BULK COLLECT and FORALL (if updating from an array of data) to mitigate this, but it's still often outperformed by MERGE. Avoid if a set-based solution is possible.
Summary and Recommendation:
- For most bulk update scenarios from a
SELECT statement in Oracle, the MERGE statement (Method 2) is generally the most recommended approach due to its power, clarity, and excellent performance for large datasets.
- The Correlated Subquery (Method 1) is suitable for simpler cases where you're updating a single column based on a single lookup value and are confident the subquery will return at most one row.
- The Updatable Join View (Method 3) works well for simple, direct joins where the view meets the updatability criteria.
- PL/SQL with a Cursor (Method 4) should typically be avoided for bulk updates unless you have complex procedural logic that must be applied on a row-by-row basis and cannot be expressed in SQL. Even then, prioritize
BULK COLLECT and FORALL.
Always test your chosen method on a representative volume of data to ensure it meets your performance requirements. Remember that these are DML operations, so they should be executed within a transaction (COMMIT or ROLLBACK).