Search code examples
oracle-databasemerge

Merge statement not inserting records


I have four columns in a table. If given value for those columns do not exist in that table, I have to insert those records. So, logic I need will be -

  • If all values exist in that table, do not do anything,
  • If any one of the values do not exist, insert.

TO accomplish this, I am using Merge statement in ORACLE but it is always showing 0 row merged.

  MERGE INTO AVAILABLE_VALUES V1
  USING 
      (SELECT YEAR1, MONTH1, DATE1, VAL FROM AVAILABLE_VALUES
       WHERE YEAR1 = 2026 AND MONTH1 = 11 AND DATE1 = <<SOME DATE>> AND VAL = 1000  
       ) V2 
  ON (
          V1.YEAR1 = V2.YEAR1 AND
          V1.MONTH1 = V2.MONTH1 AND
          V1.DATE1 = V2.DATE1
          V1.VAL = V2.VAL 
      )                                       
  WHEN NOT MATCHED THEN
  INSERT (V1.YEAR1 ,V1.MONTH1 , V1.DATE1, V1.VAL )
  VALUES (2026, 11, current_date, 1200)

Is this query incorrect?


Solution

  • Is this query incorrect?

    Yes, it has syntax errors from missing commas and ANDs

    Yes (assuming that you fix the syntax errors), it also appears to be logically incorrect. You are selecting values from AVAILABLE_VALUES and then comparing them with values in AVAILABLE_VALUES and seeing if they do not exist and, if they don't, INSERTing them but they wont exist to be able to insert them. If you want to insert new values then don't SELECT from the table you are trying to INSERT into to try to locate the new values because they will not exist.


    You want to use something like:

    MERGE INTO AVAILABLE_VALUES dst
    USING (
      SELECT 2026 AS year,
             11   AS month,
             1000 AS value
      FROM   DUAL 
    ) src
    ON (
          src.year  = dst.year1
      AND src.month = dst.month1 
      AND src.value = dst.val
    )
    WHEN NOT MATCHED THEN
      INSERT (dst.YEAR1, dst.MONTH1, dst.DATE1, dst.VAL)
      VALUES (src.year, src.month, CURRENT_DATE, src.value);
    

    (Note: I have omitted the DATE1 column from the comparison as that appears, based on your final INSERT statement, to be a timestamp corresponding to the time-of-insertion so it doesn't appear to be something the business logic should want to compare - however, your question is lacking on explanation of what the columns mean so you may want to compare on that column if the business logic does require it.)