What is the difference between a join and a union operation in SQL? Provide an example of when you would use each operation.
In SQL, a JOIN operation and a UNION operation are two different operations used to combine data from two or more tables. The main differences between these two operations are:
- JOIN operation: Joins combine rows from two or more tables based on a related column between them. The result of a join operation is a new table that contains columns from both tables.
Example: Suppose you have two tables, "Employees" and "Departments," with a common column "DepartmentID." You can join these two tables using the "INNER JOIN" clause as follows:
sqlSELECT Employees.Name, Departments.DepartmentName
FROM Employees
INNER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
This query will combine the "Name" column from the "Employees" table with the "DepartmentName" column from the "Departments" table based on the common "DepartmentID" column.
- UNION operation: Unions combine rows from two or more tables with the same structure (same columns and data types). The result of a union operation is a new table that contains all the rows from each table, without any duplicates.
Example: Suppose you have two tables, "Students2021" and "Students2022," with the same structure (same columns and data types). You can union these two tables using the "UNION" clause as follows:
sqlSELECT * FROM Students2021
UNION
SELECT * FROM Students2022;
This query will combine all the rows from both tables into a new table, removing any duplicates.
In summary, the main difference between a join and a union operation in SQL is that joins combine rows based on related columns between tables, while unions combine rows from tables with the same structure. You would use a join when you need to combine data from different tables based on a related column, while you would use a union when you need to combine data from tables with the same structure.
Comments
Post a Comment