title: Ordering a MySQL Table Based on a Positive or Negative Integer in a Column
body: <p>I have a <strong>MySQL</strong> table called <code>example</code> with columns <code>my_order</code> and <code>alt_order</code>.</p>
  
  <p><strong>Here's what I'm trying to accomplish:</strong></p>
  
  <ul>
  <li>If <code>alt_order</code> is null, order by <code>my_order</code>.</li>
  <li>If <code>alt_order</code> is not null, order by <code>my_order</code>, but position the row above or below where it should be based on the integer in <code>alt_order</code>.</li>
  </ul>
  
  <p><strong>Pseudocode:</strong></p>
  
  <pre><code>SELECT
    *
  FROM
    example
  ORDER BY
    IF(alt_order IS NULL, my_order, [MOVE UP OR DOWN BASED ON alt_order])
  </code></pre>
  
  <p><strong>Ideal Output:</strong></p>
  
  <pre><code>+--------+----------+-----------+-------------------------------------+
  | desc   | my_order | alt_order | notes                               |
  +--------+----------+-----------+-------------------------------------+
  | Item 1 | 1        | NULL      | Ordered by my_order                 |
  | Item 3 | 122      | -1        | Ordered by my_order + alt_order     | &lt;-- Move up one row
  | Item 2 | 50       | NULL      | Ordered by my_order                 |
  | Item 4 | 127      | NULL      | Ordered by my_order                 |
  | Item 5 | 205      | NULL      | Ordered by my_order                 |
  +--------+----------+-----------+-------------------------------------+
  </code></pre>
  
  <p><strong>Attempt:</strong></p>
  
  <pre><code>SELECT
    *
  FROM
    example
  ORDER BY
    IF(alt_order IS NULL, my_order, my_order + alt_order)
  
  # The problem with using this method is that the value of my_order
  # has to be the same as the value of above it to work.
  </code></pre>
  
  <hr>
  
  <blockquote>
    <p><strong>Edit:</strong></p>
    
    <p>If the <code>alt_order</code> is positive <strong><em>n</em></strong>, then it should move down <strong><em>n</em></strong> rows. On the other hand, if the <code>alt_order</code> is negative <strong><em>n</em></strong>, then it should move up <strong><em>n</em></strong> rows.</p>
  </blockquote>