title: DB2 SQL Statement for Inserting new data and updating existing data
body: <p>I've found a lot of near misses on this question.  So many similar, but not quite right, scenarios.  No doubt my ignorance will shine here.  </p>
  
  <p>Using DB2 and a shred of knowledge, my scenario is as follows:</p>
  
  <p>On a table, insert a row of data if a given value is not present in a given column, or update the corresponding row if the value <strong>is</strong> present.</p>
  
  <p>I have a table</p>
  
  <pre><code>id, bigint, not nullable
  ref,varchar, nullable
  </code></pre>
  
  <p>I am not sure if a MERGE is the correct path here as most examples and thorough discussions all seem to revolve around merging one table into another.  I'm simply gathering user input and either adding it or updating it.  It seems like it should be really simple.  </p>
  
  <p>I'm using jdbc and prepared statements to get this done.  </p>
  
  <p>Is MERGE the correct way to do this?  </p>
  
  <p>When testing my query in DB2 Control Center, I run up against </p>
  
  <blockquote>
    <p>"No row was found for FETCH, UPDATE or DELETE; or the result of a
    query is an empty table"</p>
  </blockquote>
  
  <p>or a variety of other errors depending on how I structure my MERGE. Here's what I have presently.</p>
  
  <pre><code>merge into table1 as t1
  using (select id from table1 group by id) as t2
  on t1.id = t2.id
  when matched then update set t1.ref = 'abc'
  when not matched then insert (t1.id, t1.ref) values (123, 'abc');
  </code></pre>
  
  <p>If I were to <em>instead</em> compose an <strong>update</strong> followed by an <strong>insert</strong>; for new data the insert runs and the update fails, and for existing data they both succeed resulting in bad data in the table, e.g. two identical rows.  </p>
  
  <p>The desired result is if on initial use with the values:</p>
  
  <pre><code>id = 1
  ref = a
  </code></pre>
  
  <p>a new row is added.  On subsequent use if the values change to:</p>
  
  <pre><code>id = 1
  ref = b
  </code></pre>
  
  <p>the row with id = 1 is updated.  Subsequent uses would follow the same rules.  </p>
  
  <p>Please let me know how I can phrase this question better.</p>
  
  <p><strong>Update</strong> id is not an automatic incrementing key.  It's an external key that will be unique but not every thing we are referencing will need a related row in the table I'm attempting to update.  This table is rather unstructured on its own but is part of a larger data model.  </p>