Skip to content

Oracle MERGE Statement (Upsert) πŸ”€ΒΆ

Prerequisites: INSERT, UPDATE Statements

Mentor's Note: MERGE is one of the most powerful DML commands. It means: "If the record exists, UPDATE it. If not, INSERT it." It's commonly known as an Upsert. πŸ’‘


🌟 The Scenario: The Daily Price Update πŸ’°ΒΆ

You have a PRODUCTS table and a NEW_PRICES table from a supplier. - If a product already exists, you want to update its price. - If it's a brand new product, you want to add it. - The Solution: Use MERGE to sync the two tables.


πŸ’» 1. The Basic SyntaxΒΆ

MERGE INTO target_table T
USING source_table S
ON (T.id = S.id)
WHEN MATCHED THEN
    UPDATE SET T.value = S.value
WHEN NOT MATCHED THEN
    INSERT (id, value) VALUES (S.id, S.value);

πŸ’» 2. Real-World ExampleΒΆ

MERGE INTO products P
USING (SELECT 101 id, 500 price FROM dual) S
ON (P.product_id = S.id)
WHEN MATCHED THEN
    UPDATE SET P.current_price = S.price
WHEN NOT MATCHED THEN
    INSERT (product_id, current_price) VALUES (S.id, S.price);

πŸ—οΈ Architect's Note: Consistency πŸ›‘οΈΒΆ

MERGE ensures that your logic is consistent and avoids the "Race Condition" where two separate commands (Update then Insert) might fail if data changes in between. - The Architect's Secret: Oracle makes the MERGE operation atomic. It is highly optimized for Data Warehousing where millions of rows are synced nightly.


πŸ“ˆ Learning PathΒΆ