title: SQL: ORDER BY based on two columns of interlaced values
body: <p>I have a table that is to be sorted based on two columns of numbers (call them Column X and Column Y). In each row, the two columns can either both have numeric values (in which case X&lt;=Y), or one of the columns can be NULL.</p>
  
  <p>Example data:</p>
  
  <pre><code>      X     Y
      ----- -----
  ... NULL   26
  ...  31   NULL
  ...   1     7
  ...  39    46
  ... NULL   36
  ...  15    16
  ... NULL   14
  ...  23    29
  </code></pre>
  
  <p>I would like to sort this data so that the columns interleave "correctly". Specifically:</p>
  
  <p>1) If the X value is present in both rows, order based on X.</p>
  
  <p>2) Else, if the Y value is present in both rows, order based on Y.</p>
  
  <p>3) Else, compare the available X value and the available Y value.</p>
  
  <p>The "correct" sorting of the example data would be:</p>
  
  <pre><code>      X     Y
      ----- -----
  ...   1     7
  ... NULL   14
  ...  15    16
  ... NULL   26
  ...  23    29
  ...  31   NULL
  ... NULL   36
  ...  39    46
  </code></pre>
  
  <p>Is there any simple way to perform this sorting, in an ORDER BY clause?</p>