title: Prevent concurrent update on Postgresql database row
body: <p>I have a query like below to increase count of transaction after each transaction happening through a specific gateway. The below query is used in a PHP application which does post transaction maintenance jobs. How to make sure two concurrent updates do not create a trouble in the count?</p>
  
  <p>Thinking of using advisory locks of PostgreSQL, but not sure how to use it in below context. Have few references in Java but is relatively new in PHP.</p>
  
  <p>Query 1 (To find the record to be updated):</p>
  
  <pre><code>SELECT id
  FROM Client.gatewaystat_tbl
  WHERE clientid = 1 AND gatewayid = 2 ;
  </code></pre>
  
  <p>If record found:</p>
  
  <pre><code>UPDATE gatewaystat_tbl gt
  SET statvalue = statvalue + 1
  WHERE id = '&lt;from above query&gt;'
  </code></pre>
  
  <p>If record not found:</p>
  
  <pre><code>INSERT INTO client.gatewaystat_tbl
     (gatewayid, clientid, statetypeid, statvalue)
  VALUES (2, 1, 1, 1);
  </code></pre>
  
  <p>The above code may be called multiple time within a second, as transactions will happen at a very high volume during peak hours and after every transaction the counter (<code>statvalue</code>) needs to be increased. How to make sure that multiple threads do not try to update the count at the same time and end up with erroneous data?</p>