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

  • You can only use ORDER BY at the end of the query as it must put all the sub queries into a singular data set before it can apply the sort.

    UNION removes duplicates from multiple subqueries where UNION ALL does not remove them.

    Not sure if this is what you're looking for but,

    I put a literal column to apply to the final Order By to ensure the sort order of each sub query:

    Select a, b, 2 AS Ordinal

    From table1

    UNION

    Select c,d, 1 AS Ordinal

    From table2

    Order By Ordinal