title: Dynamic conditional insert in postgresql
body: <p>I am attempting to define a conditional insert in postgresql, on an index over 3 columns (which gives uniqueness). I'm trying to follow the following example from the postgresql documentation:</p>
  
  <pre><code> INSERT INTO example_table
       (id, name)
   SELECT 1, 'John'
   WHERE
       NOT EXISTS (
           SELECT id FROM example_table WHERE id = 1
       );
  </code></pre>
  
  <p>For the basic SELECT WHERE NOT EXISTS structure. But if the index varies, i.e. you want to prevent insert if there exists a selection in the table with id=index value of current pre-insert row, how do you implement this? Here is my current (wrong) code:</p>
  
  <pre><code>insert = (
  "INSERT INTO table (index,a,b,c,d,e)"
  "SELECT * FROM table WHERE NOT EXISTS (SELECT * FROM table WHERE index=index)");
  cur.execute(insert,data)
  </code></pre>
  
  <p>For clarity, the index is defined on data columns <code>(a,b,c)</code>, data is a row of <code>(index,a,b,c,d,e)</code>, and I'm wrapping this in psycopg2. I have searched for an answer for a while, but haven't been able to successfully adapt anything to this problem yet.</p>