title: SQL query with NOT EXISTS very slow
body: <p>I am migrating person from a view to my database with the following query, which is too slow:</p>
  
  <pre><code>SELECT DISTINCT PI.VALUE ID
  FROM PERSON_VIEW PERV
      inner join PERSON_IDENT PI on PI.VALUE = PERV.IDENTITY
      inner join PERSON PER on PER.ID = PI.EXTERNAL_ID
  WHERE NOT EXISTS (SELECT RECORD_ID FROM PERSON_MIGR_DATA PMD
                    WHERE RECORD_ID = PERV.RECORD_ID)
    AND NOT EXISTS (SELECT RECORD_ID FROM PERSON_MIGR_ERRORS
                    WHERE RECORD_ID = PERV.RECORD_ID)
  </code></pre>
  
  <p>There are indexes on joined fields, but I must change this query, as it lasts 15minutes.. Tables are quite big.</p>
  
  <p>So. I have <code>PERSON_VIEW</code> - from which I read person to migrate, <code>PERSON_MIGR_DATA</code> - id of migrated persons, and <code>PERSON_MIGR_ERRORS</code> - id of records with person thath didn't pass validation during migration.</p>
  
  <p>I think, that the NOT EXIST is the bottleneck. But how could make this query so that it would be faster ?</p>