title: Locking table in postgresql
body: <p>I have a table named as <code>'games'</code>, which contains a column named as <code>'title'</code>, this column is unique, database used in <code>PostgreSQL</code></p>
  
  <p>I have a user input form that allows him to insert a new <code>'game'</code> in <code>'games'</code> table. The function that insert a new game checks if a previously entered <code>'game'</code> with the same <code>'title'</code> already exists, for this, I get the <code>count of rows</code>, with the same game <code>'title'</code>.</p>
  
  <p>I use transactions for this, the insert function at the start uses <code>BEGIN</code>, gets the row count, if row count is 0, inserts the new row and after process is completed, it <code>COMMITS</code> the changes.</p>
  
  <p>The problem is that, there are chances that 2 games with the same <code>title</code> if submitted by the user at the same time, would be inserted twice, since I just get the count of rows to chk for duplicate records, and each of the transaction would be <strong>isolated</strong> from each other</p>
  
  <p>I thought of <strong>locking the tables</strong> when getting the row count as:</p>
  
  <pre><code>LOCK TABLE games IN ACCESS EXCLUSIVE MODE;
  SELECT count(id) FROM games WHERE games.title = 'new_game_title' 
  </code></pre>
  
  <p>Which would lock the table for reading too (which means the other transaction would have to wait, until the current one is completed successfully). This would solve the problem, which is what I suspect. Is there a better way around this (avoiding duplicate <code>games</code> with the same <code>title</code>)</p>