title: Get latest record
body: <p>I'd like to select the latest row in my table based on a date field.</p>
  
  <p>The latest date should be pulled out. The catch, however, is that if the date is NULL, that should be prioritised over any max(end_date).</p>
  
  <p>The closest I've got is something like the following:</p>
  
  <pre><code>SELECT id, status_id
  FROM
  contacts AS cc
  INNER JOIN
  statuses AS s ON (s.id = cc.id)
  INNER JOIN (
      SELECT id, max(end_date) as max_end_date FROM statuses
      GROUP BY id 
  ) s2 ON s2.max_end_date = s.end_date AND s2.id = s.id
  </code></pre>
  
  <p>This works if I have two rows like the following:</p>
  
  <pre><code>id     end_date
   1     2014-06-02
   2     2015-06-02
  </code></pre>
  
  <p>It should pull out the row with end_date "2015-06-02" - which it does correctly.</p>
  
  <p>However, it does not work if the rows are like this:</p>
  
  <pre><code>id    end_date
   1    2014-06-02
   2    NULL
  </code></pre>
  
  <p>It should be returning the row where the end date is NULL.</p>
  
  <p>Any help would be appreciated, thanks.</p>