title: Update and Insert cases in postgresql function
body: <p>I have a table <code>tab</code> with columns:</p>
  
  <pre><code>userid, usercode, value
  </code></pre>
  
  <p>I'm writing a <code>plpgsql</code> function that update/insert the table.
  In case userid &amp; usercode exists I need to update value
  In case they don't I need to insert the new value</p>
  
  <p>for example if table data is:</p>
  
  <pre><code>userid, usercode, value
    5       10        20 
    3       8         10
  </code></pre>
  
  <p>for function call: </p>
  
  <pre><code>addvalue(5, 10 , 40)
  addvalue(1, 12 , 40.5)
  </code></pre>
  
  <p>The new data will be:</p>
  
  <pre><code>userid, usercode, value
    5       10        60 
    3       8         10
    1       12        40.5
  </code></pre>
  
  <p>This is My function body:</p>
  
  <pre><code>CREATE OR REPLACE FUNCTION addvalue(xuserid integer, xusercode Integer,xvalue Numeric)
  RETURNS integer AS
  
  $BODY$ 
  begin
  
       insert into tab(userid,usercode,value) values(xuserid ,xusercode,xvalue);
       return 1
  end;                
  $BODY$
  LANGUAGE plpgsql VOLATILE
  </code></pre>
  
  <p>What is the best way to find out if I need to do <code>INSERT</code> or <code>UPDATE</code> statments?</p>
  
  <p>Should I do <code>UPDATE</code> and check if it returns 0  ( 0 rows updated) and in that case do <code>INSERT</code>? Or should I query <code>tab</code> table to see if <code>userid = xuserid and usercode = xusercode</code>?</p>