What is a union in SQL?
In SQL, UNION is a set operation that combines the results of two or more SELECT queries into a single result set, without duplicating any records. This operation returns all unique rows from the combined datasets while maintaining the original column structure. To use UNION, the SELECT statements being combined must have the same number of columns with compatible data types.
What is the difference between UNION and JOIN in SQL?
The main difference between UNION and join in SQL is their purpose. UNION combines the result sets of two or more SELECT queries into a single result set, eliminating duplicate records, while join combines columns from two or more tables based on a related column between them. Essentially, UNION merges data vertically from multiple tables, and join merges data horizontally across tables.
What does a UNION do in SQL?
A UNION in SQL combines the results of two or more SELECT queries into a single result set. It returns all unique records from the combined queries, eliminating duplicate rows. Both queries must have the same number of columns and compatible data types for the UNION to work correctly. Use UNION ALL if you want to keep the duplicate rows.
How can one use UNION in SQL with an example?
To use UNION in SQL, write two or more SELECT statements separated by the UNION keyword. Make sure each SELECT statement has the same number of columns with matching data types. For example:
SELECT column1, column2 FROM table1
UNION
SELECT column1, column2 FROM table2;
How can I combine three tables in SQL using UNION?
To combine 3 tables in SQL using UNION, you need to write individual SELECT statements for each table with the same number of columns and corresponding data types, then combine them with the UNION operator. For example:
```
SELECT column1, column2, column3 FROM table1
UNION
SELECT column1, column2, column3 FROM table2
UNION
SELECT column1, column2, column3 FROM table3;
```
This query will combine the results from table1, table2, and table3 into a single output.