Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute UNION without sorting? (SQL)

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).

like image 840
hightow Avatar asked Sep 26 '11 07:09

hightow


People also ask

Does UNION all sort the data?

You can use UNION ALL to avoid sorting, but UNION ALL will return duplicates. So you only use UNION ALL to avoid sorting if you know that there are no duplicate rows in the tables).

What can I use instead of UNION all in SQL?

When a UNION is required to put together data from multiple queries, you might be able to use a CASE statement instead. This is very useful, particularly when the data for each of the queries in the UNION come from the same table.

Can UNION work with different columns?

We can apply UNION on multiple columns and can also order the results using the ORDER BY operator in the end.


2 Answers

I notice this question gets quite a lot of views so I'll first address a question you didn't ask!

Regarding the title. To achieve a "Sql Union All with “distinct”" then simply replace UNION ALL with UNION. This has the effect of removing duplicates.

For your specific question, given the clarification "The first query should have "priority", so duplicates should be removed from bottom" you can use

SELECT col1,        col2,        MIN(grp) AS source_group FROM   (SELECT 1 AS grp,                col1,                col2         FROM   t1         UNION ALL         SELECT 2 AS grp,                col1,                col2         FROM   t2) AS t GROUP  BY col1,           col2 ORDER  BY MIN(grp),           col1   
like image 142
Martin Smith Avatar answered Oct 02 '22 23:10

Martin Smith


"UNION also sort the final output" - only as an implementation artifact. It is by no means guaranteed to perform the sort, and if you need a particular sort order, you should specify it with an ORDER BY clause. Otherwise, the output order is whatever is most convenient for the server to provide.

As such, your request for a function that performs a UNION ALL but that removes duplicates is easy - it's called UNION.


From your clarification, you also appear to believe that a UNION ALL will return all of the results from the first query before the results of the subsequent queries. This is also not guaranteed. Again, the only way to achieve a particular order is to specify it using an ORDER BY clause.

like image 25
Damien_The_Unbeliever Avatar answered Oct 02 '22 21:10

Damien_The_Unbeliever