UNION joins two results and remove duplicates, while UNION ALL does not remove duplicates. UNION also sort the final output.
What I want is the UNION ALL without duplicates and without the sort. Is that possible?
The reason for this is that I want the result of the first query to be on top of the final result, and the second query at the bottom. (And each sorted as if they where run individually)
Consider these tables (Standard SQL code, runs on SQL Server 2008):
The desired effect is this to sort table
A
bycol
ascending, sort tableB
bycol
descending then unioning the two, removing duplicates, retaining order before the union and leaving tableA
results on the "top" with tableB
on the "bottom" e.g. (pesudo code)Of course, this won't work in SQL because there can only be one
ORDER BY
clause and it can only be applied to the top level table expression (or whatever the output of aSELECT
query is known as; I call it the "resultset").The first thing to address is the intersection between the two tables, in this case the values
4
,5
and6
. How the intersection should be sorted needs to be specified in SQL code, therefore it is desirable that the designer specifies this too! (i.e. the person asking the question, in this case).The implication in this case would seem to be that the intersection ("duplicates") should be sorted within the results for table A. Therefore, the sorted resultset should look like this:
Note in SQL "top" and "bottom" has no inferent meaning and a table (other than a resultset) has no inherent ordering. Also (to cut a long story short) consider that
UNION
removes duplicate rows by implication and must be applied beforeORDER BY
. The conclusion has to be that each table's sort order must be explicitly defined by exposing a sort order column(s) before being unioned. For this we can use theROW_NUMBER()
windowed function e.g.1,1:
select 1 from dual union all select 1 from dual
1:select 1 from dual union select 1 from dual