Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicate using union all

Just reading this site https://www.toptal.com/sql/interview-questions

they show this trick to remove duplicate using union all

SELECT * 
FROM mytable 
WHERE a = X 

UNION ALL 

SELECT * 
FROM mytable 
WHERE b = Y AND a != X 

The above script is not clear to me. Suppose I want to fetch data from two employee table but like to remove duplicate using union all with where clause.

Suppose my employee table has structure like ID, Name and salary.

Now post a sample SQL using union all which will show distinct rows from 2 tables.

like image 497
Mou Avatar asked Apr 29 '26 07:04

Mou


2 Answers

IF and ONLY IF you have to use a UNION ALL otherwise I would go with Handoko Chen's solution

Select Distinct *
 From (
        Select * From Employee1
        Union All
        Select * From Employee2
      ) A
like image 123
John Cappelletti Avatar answered Apr 30 '26 22:04

John Cappelletti


Actually, it's UNION that removes duplicates. Let's say I have 3 rows of data in a table. Then use 2 unioned queries. See the differences between union and union all.

DECLARE @Employee TABLE
(
    ID INT,
    Name VARCHAR(100),
    Salary  INT
)

INSERT @Employee VALUES
(1, 'Alice', 50000),
(2, 'Bob', 40000),
(3, 'Charlie', 60000)

SELECT ID, Name, Salary FROM @Employee WHERE Salary >= 50000
UNION
SELECT ID, Name, Salary FROM @Employee WHERE Salary >= 60000

SELECT ID, Name, Salary FROM @Employee WHERE Salary >= 50000
UNION ALL
SELECT ID, Name, Salary FROM @Employee WHERE Salary >= 60000

Result:

+----+---------+--------+
| ID | Name    | Salary |
+----+---------+--------+
| 1  | Alice   | 50000  |
| 3  | Charlie | 60000  |
+----+---------+--------+

+----+---------+--------+
| ID | Name    | Salary |
+----+---------+--------+
| 1  | Alice   | 50000  |
| 3  | Charlie | 60000  |
| 3  | Charlie | 60000  |
+----+---------+--------+
like image 41
Han Avatar answered Apr 30 '26 21:04

Han



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!