What is the difference between UNION and UNION ALL?
The main difference between UNION
and UNION ALL
in SQL is how they handle duplicate rows:
-
UNION
:- Combines the results of two or more SELECT queries and removes duplicate rows.
- Only unique records from all the SELECT statements are returned.
-
UNION ALL
:- Combines the results of two or more SELECT queries but includes all rows, even duplicates.
- Returns all records, including duplicates, from the SELECT statements.
Example:
-- Using UNION
SELECT name FROM employees
UNION
SELECT name FROM contractors;
-- Using UNION ALL
SELECT name FROM employees
UNION ALL
SELECT name FROM contractors;
UNION
: Will return a list of unique names from both employees and contractors.UNION ALL
: Will return all names, including any duplicates that appear in both the employees and contractors tables.
Performance:
UNION ALL
is faster thanUNION
because it doesn't require the database to check for duplicates.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.