UNION with Order: Mastering the Art of Combining and Sorting SQL Results
Problem: Ordering Data in a UNION Query
This explanation details the challenges of using ORDER BY
with UNION
and provides solutions for achieving the desired order.
Challenges:
- Single
ORDER BY
Clause: - Unpredictable Order:
Solutions:
Single ORDER BY at the End:
- Place all your
SELECT
statements inside parentheses, followed by a singleUNION
orUNION ALL
clause. - Add the desired
ORDER BY
clause after the finalUNION
statement. This clause will apply to the entire combined result set.
Example:
SELECT name, age
FROM customers
WHERE city = 'New York'
ORDER BY age
UNION
SELECT name, age
FROM customers
WHERE city = 'Los Angeles'
ORDER BY age;
Explanation:
- The two
SELECT
statements each selectname
andage
from thecustomers
table, filtering by city and ordering by age within each statement (these individual orderings are ignored). - The
UNION
clause combines the results. - The final
ORDER BY age
applies to the entire combined set, sorting all rows by age.
Subqueries with ORDER BY:
- Use subqueries with internal
ORDER BY
clauses for each desired order. - Combine the subqueries using
UNION
orUNION ALL
.
(SELECT name, age
FROM customers
WHERE city = 'New York'
ORDER BY age)
UNION ALL
(SELECT name, age
FROM customers
WHERE city = 'Los Angeles'
ORDER BY age DESC);
- Each subquery selects
name
andage
from thecustomers
table, filtered by city and ordered by age (ascending in the first, descending in the second). - The
UNION ALL
clause combines both subquery results without removing duplicates.
Related Issues:
- Duplicates with
UNION ALL
: UsingUNION ALL
in the previous example will include duplicate rows if both cities have customers with the same name and age. Consider usingUNION
if duplicates are not desired, but note that it removes duplicates even across different cities.
sql ms-access sorting