title: How to create foreign key only if it doesn't exists already?
body: <p>I'm using PostgreSQL 9.1.</p>
  
  <p>I have a table <code>common.client_contact</code> where I created foreign key using this code: </p>
  
  <pre><code>ALTER TABLE common.client_contact 
  ADD FOREIGN KEY (contact_id) REFERENCES common.contact_item(id);
  </code></pre>
  
  <p>If I execute this code, I will get several foreign keys with different names (like <code>client_contact_contact_id_fkey1</code>, <code>client_contact_contact_id_fkey2</code>, <code>client_contact_contact_id_fkey3</code> and so on).</p>
  
  <p>So, before creating new constraint, I need to check if it's exists.</p>
  
  <p>I check if this constraint exists in <code>pg_constraint</code> table:</p>
  
  <pre><code>SELECT * FROM pg_constraint WHERE conname = 'client_contact_contact_id_fkey'
  </code></pre>
  
  <p>And now I need to combine them together. Something like</p>
  
  <pre><code>IF NOT EXISTS
      (SELECT * FROM pg_constraint WHERE conname = 'client_contact_contact_id_fkey')
  ALTER TABLE common.client_contact
      ADD CONSTRAINT client_contact_contact_id_fkey
      FOREIGN KEY (contact_id) REFERENCES common.contact_item(id)
  </code></pre>
  
  <p>or just</p>
  
  <pre><code>ALTER TABLE common.client_contact 
  ADD FOREIGN KEY IF NOT EXISTS (contact_id) REFERENCES common.contact_item(id)
  </code></pre>
  
  <p>But these two queries are produce syntax error. So, how can I do it in PostgreSQL?</p>