Oracle
UPSERT
In Oracle, an UPSERT operation allows you to either insert new rows or update existing rows in a table based on whether the data already exists. This is typically done using the MERGE statement. The MERGE statement checks for matching conditions between source and target data, then inserts or updates the target table as necessary. It’s a powerful way to synchronize data, ensuring no duplicates are created.
Here’s a breakdown of how the UPSERT operation works:
Steps to Perform UPSERT in Oracle
Identify Target Table and Source Data
- Determine the target table where you want to update or insert data.
- Identify the source data that will be used to perform the UPSERT.
Use the
MERGEStatement- The
MERGEstatement is used to perform the UPSERT operation.MERGE INTO library_books lb USING (SELECT '001' AS book_id, 'New Author' AS author_name FROM dual) src ON (lb.book_id = src.book_id) WHEN MATCHED THEN UPDATE SET lb.author_name = src.author_name WHEN NOT MATCHED THEN INSERT (lb.book_id, lb.author_name) VALUES (src.book_id, src.author_name); - Explanation:
- Target Table:
library_booksis the table you want to upsert data into. - Source Data: The
USINGclause selects data to check against the target table. - Matching Condition: The
ONclause checks if thebook_idfrom the source matches thebook_idin the target table. - UPDATE Operation: If a match is found (
WHEN MATCHED), the existing row is updated. - INSERT Operation: If no match is found (
WHEN NOT MATCHED), a new row is inserted.
- Target Table:
- The
Breakdown of the
MERGEStatement- ON clause: Specifies the condition for matching rows between the source and target.
- WHEN MATCHED: If the matching condition is true, update the existing rows.
- Bullet points under this:
- This clause modifies rows that already exist in the table.
- You can update one or more columns based on the source data.
- Bullet points under this:
- WHEN NOT MATCHED: If no matching rows are found, insert new rows into the target table.
- Bullet points under this:
- New records are inserted only if no matching records exist.
- You must specify the columns and the values to be inserted.
- Bullet points under this:
Advantages of UPSERT
- Prevents Duplicates: Ensures that the same data is not inserted multiple times.
- Efficiency: Combines update and insert operations into one, reducing the need for separate queries.
- Data Synchronization: Useful for keeping two tables or datasets synchronized.
Best Practices
- Always make sure your matching condition in the
ONclause is precise to avoid unwanted updates or inserts. - Test the
MERGEstatement with a smaller dataset first to ensure it behaves as expected.
- Always make sure your matching condition in the
This approach allows you to efficiently handle situations where data either needs to be updated or inserted based on its existence in the target table.
To gain complete access, login with gmail or outlook, no need of signup. click here


Comments Not Found