title: SQLAlchemy fast bulk upsert from another table
body: <p>I would like to insert records into <code>table_a</code> from <code>table_b</code> that don't already exist in table <code>table_a</code>. I already have Postgres SQL code to do this, but now my team has requested that I use an ORM (SQLAlchemy) instead.</p>
  
  <pre><code>INSERT INTO table_a
  SELECT
    composite_pk1,
    composite_pk2,
    col_c,
    col_d
  FROM table_b
  ON CONFLICT (
    composite_pk1,
    composite_pk2
  ) DO NOTHING
  </code></pre>
  
  <p>I have nearly a million rows and about 15 columns (not shown in the example). I need this query to be fast, which is why I don't think the solution posted <a href="https://stackoverflow.com/a/26018934/554481">here</a> will work for my use case. </p>
  
  <p>For performance reasons I also want to avoid treating my Python function as a data conduit. I don't want to transfer many rows of <code>table_b</code> over the network to my function just to push them back over the network again to <code>table_a</code>. That is, I would prefer the insert to happen entirely on Postgres, which I already accomplish with my original SQL query. </p>