title: mysql insert race condition
body: <p>How do you stop race conditions in MySQL? the problem at hand is caused by a simple algorithm:</p>
  
  <ol>
  <li>select a row from table</li>
  <li>if it doesn't exist, insert it</li>
  </ol>
  
  <p>and then either you get a duplicate row, or if you prevent it via unique/primary keys, an error.</p>
  
  <p>Now normally I'd think transactions help here, but because the row doesn't exist, the transaction don't actually help (or am I missing something?).</p>
  
  <p>LOCK TABLE sounds like an overkill, especially if the table is updated multiple times per second.</p>
  
  <p>The only other solution I can think of is GET_LOCK() for every different id, but isn't there a better way? Are there no scalability issues here as well? And also, doing it for every table sounds a bit unnatural, as it sounds like a very common problem in high-concurrency databases to me. </p>