title: Why can't i refer to a column alias in the ORDER BY using CASE?
body: <p>Sorry if this a duplicate, but i haven't found one. Why can't i use my column alias defined in the <code>SELECT</code> from  the <code>ORDER BY</code> when i use  <code>CASE</code>?</p>
  
  <p>Consider this simple query:</p>
  
  <pre><code>SELECT NewValue=CASE WHEN Value IS NULL THEN '&lt;Null-Value&gt;' ELSE Value END
  FROM dbo.TableA
  ORDER BY CASE WHEN NewValue='&lt;Null-Value&gt;' THEN 1 ELSE 0 END
  </code></pre>
  
  <p>The result is an error: </p>
  
  <blockquote>
    <p>Invalid column name 'NewValue'</p>
  </blockquote>
  
  <p><a href="http://sqlfiddle.com/#!3/0018ac/4/0" rel="noreferrer">Here's a sql-fiddle.</a> (Replace the <code>ORDER BY NewValue</code> with the <code>CASE WHEN...</code> that´'s commented out)</p>
  
  <p>I know i can use <code>ORDER BY CASE WHEN Value IS NULL THEN 1 ELSE 0 END</code> like <a href="http://sqlfiddle.com/#!3/0018ac/5/0" rel="noreferrer"><strong>here</strong></a> in this case but actually the query is more complex and i want to keep it as readable as possible. Do i have to use a sub-query or CTE instead, if so why is that so?</p>
  
  <p><strong>Update</strong> as  Mikael Eriksson has commented <em>any</em> expression in combination with an alias is not allowed. So even this (pointless query) fails for the same reason:</p>
  
  <pre><code>SELECT '' As Empty
  FROM dbo.TableA
  ORDER BY Empty + ''
  </code></pre>
  
  <p>Result:</p>
  
  <blockquote>
    <p>Invalid column name 'Empty'.</p>
  </blockquote>
  
  <p>So an alias is allowed in an <code>ORDER BY</code> and also an expression but <strong>not both</strong>. Why, is it too difficult to implement? Since i'm mainly a programmer i think of aliases as variables which could simple be used in an expression.</p>