title: Insert if not exists, else return id in postgresql
body: <p>I have a simple table in PostgreSQL that has three columns:</p>
  
  <ul>
  <li>id serial primary key</li>
  <li>key varchar</li>
  <li>value varchar</li>
  </ul>
  
  <p>I have already seen this question here on SO: <a href="https://stackoverflow.com/questions/1109061/insert-on-duplicate-update-postgresql">Insert, on duplicate update in PostgreSQL?</a> but I'm wondering just how to get the id if it exists, instead of updating. If the standard practice is to always either "insert" or "update if exists", why is that? Is the cost of doing a SELECT (LIMIT 1) greater than doing an UPDATE?</p>
  
  <p>I have the following code</p>
  
  <pre><code>INSERT INTO tag
      ("key", "value")
      SELECT 'key1', 'value1'
  WHERE
      NOT EXISTS (
          SELECT id,"key","value" FROM tag WHERE key = 'key1' AND value = 'value1'
      );
  </code></pre>
  
  <p>which works in the sense that it doesn't insert if exists, but I'd like to get the id. Is there a "RETURNING id" clause or something similar that I could tap in there?</p>