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

  • BaldingLoopMan (3/4/2010)


    also u have to ensure that the aliases of everything your selecting must match between the top select and bottom select. these aliases is what you will put in your order by

    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 '1a'AS a

    UNION

    SELECT 2 AS b

    -- will fail

    SELECT 1 AS a

    UNION

    SELECT 2 AS b

    ORDER BY B

    -- will run

    SELECT 1 AS a

    UNION

    SELECT 2 AS b



    Lutz
    A pessimist is an optimist with experience.

    How to get fast answers to your question[/url]
    How to post performance related questions[/url]
    Links for Tally Table [/url] , Cross Tabs [/url] and Dynamic Cross Tabs [/url], Delimited Split Function[/url]