title: Correct bad data in database latest-flag
body: <pre><code>Background
  </code></pre>
  
  <p>My database is keeping track of users and their changing user names. Each real person can have had many user names over time, but only one is the "Latest" (the current one). This is achieved by having a from-date and to-date, where if it it the latest one, toDate is null and have latest-column set to 1. Unfortunately, the data has been corrupted and now some users don't have a latest-flag. 
  And another bug is that some have toDate that is null even though it shouldn't be. </p>
  
  <pre><code>Question
  </code></pre>
  
  <p>How can I find the rows that needs to set/update the latest-flag to 1 ? (No need to worry about second bug for now, but it might make it trickier to find the right row to update latest flag).</p>
  
  <p>The correct SELECT should return row 5 and 8 (but not row 6), in the example below.</p>
  
  <pre><code>Example
  </code></pre>
  
  <p>PersonId=1 is a correct person.
  PersonId=2 is missing the latest=1 in row 5.
  PersonId=3 has the second bug (toDate=null) in row 6 and is missing latest=1 in row 8.</p>
  
  <p>To avoid the second bug (row 5), we know that the fromDate is always bigger(newer) for the row that needs to be corrected.</p>
  
  <p>I've tried to make a join but I couldn't get it right...</p>
  
  <p>Here is the table "users":</p>
  
  <pre><code>+----+--------+----------+------------+------------+--------+
  | id | name   | personId | fromDate   | toDate     | latest |
  +----+--------+----------+------------+------------+--------+
  |  1 | Perold |        1 | 2016-12-01 | 2016-12-31 |      0 |
  |  2 | Pernew |        1 | 2016-12-31 | NULL       |      1 |
  |  3 | Body   |        2 | 2016-01-01 | 2016-12-01 |      0 |
  |  4 | Bo     |        2 | 2016-12-01 | 2016-12-31 |      0 |
  |  5 | Bonew  |        2 | 2016-12-31 | NULL       |      0 | &lt;-- Wrong latest
  |  6 | Joe    |        3 | 2016-01-01 | NULL       |      0 | &lt;-- Wrong toDate, correct latest
  |  7 | Joey   |        3 | 2016-12-01 | 2016-12-31 |      0 |
  |  8 | Jo     |        3 | 2016-12-31 | NULL       |      0 | &lt;-- Wrong latest
  +----+--------+----------+------------+------------+--------+
  </code></pre>