The SQL UNION operator is used to combine the result sets of two or more SELECT statements into a single result set. The SELECT statements must have the same number of columns and compatible data types in corresponding positions.
Here's the basic syntax of the UNION operator:
SELECT column1, column2, ...
FROM table1
UNION
SELECT column1, column2, ...
FROM table2;
Note that the column names in the result set are determined by the column names in the first SELECT statement. Also, the UNION operator removes duplicate rows from the final result set. If you want to include duplicate rows, you can use the UNION ALL operator instead.
Here's an example to illustrate the usage of UNION:
Let's say we have two tables, "Customers" and "Suppliers," and we want to retrieve a list of all distinct company names from both tables:
SELECT CompanyName
FROM Customers
UNION
SELECT CompanyName
FROM Suppliers;
This query will combine the company names from the "Customers" and "Suppliers" tables, remove any duplicate entries, and return a result set with a single column named "CompanyName" containing the distinct values.
It's important to note that the UNION operator requires the SELECT statements to have the same number of columns and compatible data types in corresponding positions. If the number of columns or data types do not match, you'll encounter an error.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc