title: MySQL CASE working backwards
body: <p>I'm using CASE to clean up some state abbreviations, in a table, but it's working contrary to the logic. I selected the length alone to show that the length is being calculated correctly, so I think it's the CASE logic that's off</p>
  
  <p>When I query...</p>
  
  <pre><code>SELECT billing_state,
         length(billing_state),
         CASE billing_state
           WHEN length(billing_state) &gt; 2 THEN (select state_abbr from lkup_states where upper(state_name) = billing_state)
           WHEN length(billing_state) = 2 THEN upper(billing_state)
           ELSE 'UNKNOWN'
         END as billing_state_fixed           
    FROM accounts
  +---------------+-----------------------+---------------------+
  | billing_state | length(billing_state) | billing_state_fixed |
  +---------------+-----------------------+---------------------+
  | GA            |                     2 | NULL                |
  | Alabama       |                     7 | ALABAMA             |
  | MS            |                     2 | NULL                |
  | FL            |                     2 | NULL                |
  | NULL          |                  NULL | UNKNOWN             |
  +---------------+-----------------------+---------------------+
  </code></pre>
  
  <p>However, when I enter this bizarro logic, it works.  </p>
  
  <pre><code>SELECT billing_state,
         length(billing_state),
         CASE billing_state
           WHEN length(billing_state) = 2 THEN (select state_abbr from lkup_states where upper(state_name) = billing_state)
           WHEN length(billing_state) &lt;&gt; 2 THEN upper(billing_state)
           ELSE 'UNKNOWN'
         END as billing_state_fixed           
    FROM accounts
  
  +---------------+-----------------------+---------------------+
  | billing_state | length(billing_state) | billing_state_fixed |
  +---------------+-----------------------+---------------------+
  | GA            |                     2 | GA                  |
  | Alabama       |                     7 | AL                  |
  | MS            |                     2 | MS                  |
  | FL            |                     2 | FL                  |
  | NULL          |                  NULL | UNKNOWN             |
  +---------------+-----------------------+---------------------+
  </code></pre>
  
  <p>Can anyone take a swing at this one?</p>