title: Negating an arbitrary where clause condition (including the null tests)
body: <p>I want to efficiently check if a table contains any rows that match &lt;condition A&gt; and do not match &lt;condition B&gt;, where the conditions are arbitrary.</p>
  
  <p>In Oracle, this <em>almost</em> works:</p>
  
  <pre><code>select count(*) from dual
  where exists (
    select * from people
    where (&lt;condition A&gt;)
    and not (&lt;condition B&gt;)
  );
  -- returns zero if all rows that match &lt;condition A&gt; also match &lt;condition B&gt;
  -- (well, almost)
  </code></pre>
  
  <p>The problem is the dreaded null values. Lets say &lt;condition A&gt; is <strong>name = 'Aaron'</strong> and &lt;condition B&gt; is <strong>age = 21</strong>. The query will correctly identify any Aarons whose age is not equal to 21, but it fails to identify any Aarons whose age is null.</p>
  
  <p>Here is a correct solution, but on a table with millions of records it can take a while:</p>
  
  <pre><code>select (
    select count(*) from people
    where (&lt;condition A&gt;)
  ) - (
    select count(*) from people
    where (&lt;condition A&gt;)
    and (&lt;condition B&gt;)
  ) from dual;
  -- returns zero if all rows that match &lt;condition A&gt; also match &lt;condition B&gt;
  -- (correct, but it is s l o w...)
  </code></pre>
  
  <p>Unfortunately the two conditions will be arbitrary, complex, changing, and generally out of my control. They are generated from the application's persistence framework from user searches, and while we try to keep our indexes up with our users, a lot of the time they will cause big table scans (which is why that first query with the "exists" clause is so much faster than the second - it can stop as soon as it finds one matching record, and it doesn't have to do two separate scans).</p>
  
  <p>How can I do this efficiently without futzing up on the nulls?</p>