Home Forums SQL Server 2008 T-SQL (SS2K8) How to use"Union ALL" to join sql queries each containing order by clause RE: How to use"Union ALL" to join sql queries each containing order by clause

  • That's not correct. When using UNION or UNION ALL SQL server will use the alias of the first statement for all. Also, it will use the data type with the highest precedence for all queries.

    ========================================================================

    A few examples:

    -- will fail

    SELECT 1 AS a

    UNION

    SELECT 2 AS b

    ORDER BY B

    --if both aliases were the same this wouldnt fail also what advantage is there to having two different aliases because the "b" alias gets lost in the mix. It becomes "a".

    -- will run

    SELECT 1 AS a

    UNION

    SELECT 2 AS b

    --no order is being applied here. if a=2 and b=1 it would return 2,1

    --to your point i suppose there is no reason at all to even alias any but the first select. interesting.