본문 바로가기
Study Note/SQL

Union & Union All

by jhleeatl 2024. 5. 1.

UNION: The `UNION` operator in SQL is used to combine the results of two or more SELECT statements into a single result set. It removes duplicate rows from the result set, so each row appears only once.

UNION ALL: On the other hand, the `UNION ALL` operator also combines the results of two or more SELECT statements into a single result set, but it includes all rows from all SELECT statements, including duplicates.

 

 

 

 

 


To illustrate:

Let's consider two tables, A and B.

Table A:

id | name
---------
1  | Alice
2  | Bob
3  | Charlie


Table B:

id | name
---------
2  | Bob
3  | Charlie
4  | David



When we combine these tables using `UNION` and `UNION ALL`:

- With `UNION`, the result would be:

SELECT * FROM A
UNION
SELECT * FROM B;
id | name
---------
1  | Alice
2  | Bob
3  | Charlie
4  | David


Bob and Charlie appear only once in the result because duplicates are removed.

 


- With `UNION ALL`, the result would be:

SELECT * FROM A
UNION ALL
SELECT * FROM B;
id | name
---------
1  | Alice
2  | Bob
3  | Charlie
2  | Bob
3  | Charlie
4  | David



Bob and Charlie appear twice in the result because duplicates are retained.

 

 

'Study Note > SQL' 카테고리의 다른 글

With CTE  (0) 2024.05.20
Difference between COALESCE and IFNULL  (0) 2024.04.23
How to add localhost at DBeaver (MY SQL)  (0) 2024.04.16
Having  (0) 2024.04.11
7. Pivot, Window function (Rank & sum), Date  (0) 2024.03.22