UNION
clause in SQL is used to combine the result sets of two or more SELECT
statements into a single result set. It removes duplicate rows between the SELECT
statements, ensuring that each row in the final result set is unique. This is particularly useful when you want to combine data from multiple tables or queries while eliminating duplicates.
UNION
is used to combine rows from two or more tables or queries.UNION
removes duplicate rows from the combined result set.SELECT
statements being combined.SELECT
statements must be in the same order.column1, column2, ...
: The columns you want to retrieve.table1, table2
: The tables from which you want to retrieve data.Employees
and Managers
, and you want to retrieve a list of all unique names from both tables.
Table: Employees
Name |
---|
Anand |
Bala |
Kavitha |
Raj |
Kumar |
Name |
---|
Ram |
Karthik |
David |
Anand |
Kannan |
Name |
---|
Anand |
Bala |
Kavitha |
Raj |
Kumar |
Ram |
Karthik |
David |
Kannan |
UNION
removes duplicates.
Employees
and Managers
tables:
Name |
---|
Anand |
Bala |
Kavitha |
Raj |
Kumar |
Ram |
Karthik |
David |
Anand |
Kannan |
UNION ALL
does not remove duplicates.
UNION
when you want to combine results from multiple queries and ensure that the final result set contains only unique rows.UNION ALL
when you want to combine results and are okay with including duplicate rows.UNION
can be slower than UNION ALL
because it requires additional processing to remove duplicates.SELECT
statement.ORDER BY
clause at the end of the last SELECT
statement.Name |
---|
Anand |
Bala |
David |
Kannan |
Karthik |
Kavitha |
Kumar |
Raj |
Ram |
Name
column.
Students2022
and Students2023
, and you want to create a list of all unique students who enrolled in either year.
Table: Students2022
Name |
---|
Siva |
Ramesh |
Suresh |
Sathish |
Name |
---|
Sujatha |
Siva |
Ramesh |
Kannan |
Name |
---|
Siva |
Ramesh |
Suresh |
Sathish |
Sujatha |
Kannan |
UNION
clause combines results from multiple SELECT
statements into a single result set.UNION ALL
to include duplicates.SELECT
statements.ORDER BY
to sort the final result set.UNION
is useful for combining data from multiple sources while ensuring uniqueness.