CombineUNION ALL results using a subquery and applyORDER BYoutside it:
SELECT*FROM (
SELECT columnA FROM tableX --roaming through tableXUNIONALLSELECT columnA FROM tableY --not forgetting to visit tableY) AS combined -- Alpha 'X' and Yankee 'Y' joined forces and...formed 'combined'ORDERBY columnA; -- Who runs the world? columnA!
Offers a sorted single result set for UNION ALL by sorting column columnA.
Fitting more complexity into ORDER BY
Adding a sortby column for managing sort order across different tables:
SELECT columnA, 1as sortby FROM tableX --tableX took the first shot, or shall we say...sort!UNIONALLSELECT columnB, 2as sortby FROM tableY --tableY keeping up, at sortby 2!ORDERBY sortby, columnA; --Let the sorting games begin!
Teams up different tables with custom sorting directives using sortby.
Indulging alias for more efficient ORDER BY
Maintain alias consistency for concise ORDER BY:
SELECT columnA as SortColumn FROM tableX --tableX ships out SortColumnUNIONALLSELECT columnB as SortColumn FROM tableY --tableY answers with its own SortColumnORDERBY SortColumn; --and the SortColumn takes it home!
Column alias SortColumn employed for ordering the joined tables.
Autonomy in UNION set sorting
To sort each union set before merging:
SELECT*FROM (
SELECT TOP 100PERCENT columnA, otherColumn FROM tableX ORDERBY otherColumn --tableX nails the sorting UNIONALLSELECT TOP 100PERCENT columnA, otherColumn FROM tableY ORDERBY otherColumn --tableY, every bit as sorted) AS combined --two sorted souls combinedORDERBY columnA; --And then columnA said... let there be order!
Individual union sets sorted using a TOP keyword before combining.
Sidestepping pitfalls
Abstain from erroneous usage of ORDER BY with UNION ALL to evade errors. Be especially cautious with parentheses usage, and keep aliases well-defined.
SQL dialects and choosing the efficient ORDER BY
Oracle SQLoptimizesORDER BY using column numbers:
SELECT columnA, columnB FROM tableX --tableX declares A and BUNIONALLSELECT columnA, columnB FROM tableY --tableY counts two, how about you?ORDERBY1, 2; --Numbers, the universal language!
Subqueries for your sorting pleasure
Try subqueries for complex sorts:
SELECT*FROM (
SELECT columnA, 'X'as source FROM tableX --X marks the source!UNIONALLSELECT columnA, 'Y'as source FROM tableY --Y not?) AS combined --X or Y, we're still good ol' combinedORDERBYCASEWHEN source ='X'THEN1ELSE2END, columnA; --Choose your loyalty, X or Y?
Custom sort logic outside of UNION ALL for more refined results.
Going custom with ORDER BY
Paint by numbers: row numbers to the rescue!
AddROW_NUMBER() for sequential sorting:
SELECT*FROM (
SELECTROW_NUMBER() OVER(ORDERBY columnA) as RN, *FROM tableX --tableX now with more numbering!UNIONALLSELECTROW_NUMBER() OVER(ORDERBY columnA) as RN, *FROM tableY --tableY follows suit with row numbers!) AS combined
ORDERBY RN; --RN them all!
Row numbers originating from each SELECT, sorting joined data more naturally.
Keeping data type consistency
Ensure columns for sorting share same data type:
SELECT columnA, CAST(otherColumn ASINT) as sortableColumn FROM tableX --sortableColumn now in integer style!UNIONALLSELECT columnB, CAST(anotherColumn ASINT) as sortableColumn FROM tableY --sortableColumn too neat to miss!ORDERBY sortableColumn; --sortableColumn keeps sorting casual
Casting removes inconsistencies when matching up columns from different tables.
Workarounds for DBMS restrictions
Sorting post UNION ALL can bring troubles depending on your SQL implementation. Wrappings can help:
SELECT*FROM (
SELECT*FROM (
SELECT columnA FROM tableX --tableX in style, A game strong!UNIONALLSELECT columnA FROM tableY --tableY unwrapped, gifts sorted! ) AS combined_inside --a combined surprise inside) AS combined_outside --all goodness, combined and sorted!ORDERBY columnA;
Wrapping allows sorting after UNION ALL across SQL dialects.