title: SQL ORDER BY with CASE with UNION ALL
body: <p>Running PostgreSQL (7.4 and 8.x) and I thought this was working but now I'm getting errors.</p>
  
  <p>I can run the queries separately and it works just fine, but if I UNION or UNION ALL it throws an error.</p>
  
  <p>This errors out: (Warning: pg_query(): Query failed: ERROR:  column "Field1" does not exist ... ORDER BY CASE "Field1" W...) </p>
  
  <pre><code>SELECT "Field1" AS field_1, "Field2" AS field_2,
  "Field3" AS field_3, "Field4" AS field_4
  FROM "TableName" 
  WHERE condition
  AND other_condition
  UNION ALL
  SELECT "Field1" AS field_1, "Field2" AS field_2,
  "Field3" AS field_3, "Field4" AS field_4
  FROM "TableName" 
  WHERE yet_another_condition
  AND yet_another_other_condition
  ORDER BY CASE "Field1"
      WHEN 'A' THEN 1
      WHEN 'B' THEN 2
      WHEN 'C' THEN 3
      ELSE 4
  END
  </code></pre>
  
  <p>This works:</p>
  
  <pre><code>SELECT "Field1" AS field_1, "Field2" AS field_2,
  "Field3" AS field_3, "Field4" AS field_4
  FROM "TableName" 
  WHERE yet_another_condition
  AND yet_another_other_condition
  ORDER BY CASE "Field1"
      WHEN 'A' THEN 1
      WHEN 'B' THEN 2
      WHEN 'C' THEN 3
      ELSE 4
  END
  </code></pre>
  
  <p>And this works as well:</p>
  
  <pre><code>SELECT "Field1" AS field_1, "Field2" AS field_2,
  "Field3" AS field_3, "Field4" AS field_4
  FROM "TableName" 
  WHERE condition
  AND other_condition
  ORDER BY CASE "Field1"
      WHEN 'A' THEN 1
      WHEN 'B' THEN 2
      WHEN 'C' THEN 3
      ELSE 4
  END
  </code></pre>
  
  <p>and if I leave off the ORDER BY and just use the UNION or UNION ALL it works as well.</p>
  
  <p>Any Ideas?</p>