title: Best way to test for duplicate keys in a database
body: <p>This is more of a correctness question. Say I have a table with a primary key column in my database. In my DAO code I have a function called insertRow(string key) that will return true if the key doesn't exist in the table and insert a new row with the key. Otherwise, if a row already exists with that key it returns false.  Is it better/worse to have insertRow first check for the existence of the key or just go ahead and do the insert and catch the duplicate key error? Or is saving on a single select statement too trivial an optimization to even bother worrying about?</p>
  
  <p>So in sudo code:</p>
  
  <pre><code>boolean insertRow(String key){
      //potentially a select + insert
      if(select count(*) from mytable where key = "somekey" == 0){
         insert into mytable values("somekey")
         return true;
      }
      return false;
  }
  </code></pre>
  
  <p>or</p>
  
  <pre><code>  boolean insertRow(String key){
      try{
         //always just 1 insert
         insert into mytable values("somekey")
         return true;
      } catch (DuplicateKeyException ex){}
      return false;
    }
  </code></pre>