Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove duplicates from sql union

Tags:

sql

tsql

I'm doing some basic sql on a few tables I have, using a union(rightly or wrongly)

but I need remove the duplicates. Any ideas?

select * from calls
left join users a on calls.assigned_to= a.user_id
where a.dept = 4 
union
select * from calls
left join users r on calls.requestor_id= r.user_id
where r.dept = 4
like image 570
thegunner Avatar asked Nov 08 '10 20:11

thegunner


People also ask

Does UNION remove duplicates in SQL Server?

SQL Union All Operator Overview The SQL Union All operator combines the result of two or more Select statement similar to a SQL Union operator with a difference. The only difference is that it does not remove any duplicate rows from the output of the Select statement.

Does UNION remove duplicates in same table?

Union will remove duplicates. Union All does not.

Can UNION have duplicates?

UNION: only keeps unique records. UNION ALL: keeps all records, including duplicates.

Does UNION keep duplicates SQL?

Anyway, the answer to this question is simple, though both UNION and UNION ALL are used to combine the result of two separate SQL queries on the same or different table, UNION does not keep a duplicate record (a row is considered duplicate if the value of all columns is same), while UNION ALL does.


3 Answers

Union will remove duplicates. Union All does not.

like image 76
Randy Minder Avatar answered Sep 20 '22 13:09

Randy Minder


Using UNION automatically removes duplicate rows unless you specify UNION ALL: http://msdn.microsoft.com/en-us/library/ms180026(SQL.90).aspx

like image 32
Jeremy Elbourn Avatar answered Sep 23 '22 13:09

Jeremy Elbourn


Others have already answered your direct question, but perhaps you could simplify the query to eliminate the question (or have I missed something, and a query like the following will really produce substantially different results?):

select * 
    from calls c join users u
        on c.assigned_to = u.user_id 
        or c.requestor_id = u.user_id
    where u.dept = 4
like image 44
Jerry Coffin Avatar answered Sep 19 '22 13:09

Jerry Coffin