How to order by with union in SQL?
Sort results after a UNION by placing the combined queries inside a subquery and using the ORDER BY clause outside:
This strategy will provide a neatly sorted result set from your UNION query, with col
being the column of your choice for sorting.
Standard sort with UNION
A standard way to perform a sort while using UNION is to include the ORDER BY clause after the UNION statement:
This will give a result set combining records from both table1
and table2
and sort based on col
.
Maintaining original sort with UNION ALL
There can be situations where you would like to keep the sort order from the individual queries before the union. In such cases, use UNION ALL along with an extra sort column:
This ensures the second set of results is appended after the first, retaining the original sort order within each set. It's like serving two dishes on the same platter, while not mixing them up.
Matching column aliases across SELECTs
Make sure the aliases for columns used in the ORDER BY and SELECT clauses match to avoid unwanted surprises:
In this query, alias_name
is used in ORDER BY as a representative for col
from both tables.
Handling specific databases
Oracle: Combine subselect, UNION ALL and ORDER BY
In certain Oracle database systems, you will have to use a slightly different approach when combining subselect, UNION ALL, and ORDER BY:
Note that in Oracle, unlike your ex, ORDER BY stays outside the UNION ALL.
Handling different tables
You can UNION results from different tables and still ORDER BY. Just make sure you reference the correct column name:
It's like ordering from different restaurant menus – as long as you know what you want, you're good to go!
Ordering by column aliases
For query readability, it's a good idea to use aliases for columns and maintain a consistent syntax in all SELECT statements:
Remember, not everything in SQL is as shady as dark-web transactions. So, great naming conventions are key to clear coding!
Was this article helpful?