ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.

In SQL Server, you may face an error and get the below error message:
Msg 104, Level 16, State 1, Line 4
ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.

Below is the solution of your query, make sure you have followed the pattern as below

Select * from
(               
            SELECT   field1, field2 FROM Table1 WHERE  field1 = 'abc'
            UNION
            SELECT   field1, field2 FROM Table2 WHERE  field2 = 'xyz'
) VarTable
                    order by case when field1 is not null then field1 else field2 end desc


Let us know your feedback.

Thank you Hiral Shah for this post!

By

4 comments:

  1. THANKS A LOT IT HAS SOLVED MY LOTS OF PROBLEM

    ReplyDelete
  2. Thanks alot for this, was struggling for a few hours.

    ReplyDelete
  3. A million thanks to you...that solved my big problem. I hope that GOD will give you more knowledge in programming so that you will can always share your given grace. More power to you....

    ReplyDelete
  4. Thank you very much.

    visit regularly for more solutions :)

    ReplyDelete