title: Count distinct values in MySQL without folding NULL values
body: <p>I have table <code>a</code> with two fields: <code>id</code> (PK) and <code>f</code>.</p>
  
  <p>Consider following records:</p>
  
  <pre><code>id | f
  1  | NULL
  2  | 'foo'
  3  | 'bar'
  4  | NULL
  5  | 'foo'
  6  | 'baz'
  </code></pre>
  
  <p>I want to retrieve and count all the records having distinct <code>f</code> values including every record <code>WHERE f IS NULL</code>. Given this criteria, the query should return every record except #5, because the same value is already included in the set, and the total count would be 5.</p>
  
  <p>The query I'm using to retrieve all records looks like this:</p>
  
  <p><code>SELECT CASE WHEN EXISTS (SELECT id FROM a a2 WHERE a2.f = a.f AND a.id &lt; a2.id) THEN 1 END AS not_distinct FROM a HAVING not_distinct IS NULL</code></p>
  
  <p>If this query could be improved, I'd welcome any feedback. Anyway, the main problem is counting. Obviously adding a <code>COUNT(*)</code> will not help here and I'm totally lost how to count the records after the filtering. </p>