Difference between JOIN and UNION
Joins and Unions can be used to combine data from one or more tables. The difference lies in how the data is combined.
JOIN:
JOIN in SQL is used to combine data from many tables based on a matched condition between them. The data combined using JOIN statement results into new columns.In simple terms, joins combine data into new columns. If two tables are joined together, then the data from the first table is shown in one set of column alongside the second table’s column in the same row.
UNION:
UNION in SQL is used to combine the result-set of two or more SELECT statements. The data combined using UNION statement is into results into new distinct rows.Unions combine data into new rows. If two tables are “unioned” together, then the data from the first table is in one set of rows, and the data from the second table in another set. The rows are in the same result.
Here is a visual depiction of a join. Table A and B’s columns are combined into a single result.
Each row in the result contains columns from BOTH table A and B. Rows are created when columns from one table match columns from another. This match is called the join condition.
This makes joins really great for looking up values and including them in results. This is usually the result of denormalizing (reversing normalization) and involves using the foreign key in one table to look up column values by using the primary key in another.
Now compare the above depiction with that of a union. In a union each row within the result is from one table OR the other. In a union, columns aren’t combined to create results, rows are combined.
Both joins and unions can be used to combine data from one or more tables into a single results. They both go about this is different ways. Whereas a join is used to combine columns from different tables, the union is used to combine rows.
Difference between JOIN and UNION in SQL :
JOIN | UNION |
---|---|
JOIN combines data from many tables based on a matched condition between them. | SQL combines the result-set of two or more SELECT statements. |
It combines data into new columns. | It combines data into new rows |
Number of columns selected from each table may not be same. | Number of columns selected from each table should be same. |
Datatypes of corresponding columns selected from each table can be different. | Datatypes of corresponding columns selected from each table should be same. |
It may not return distinct columns. | It returns distinct rows. |
Post a Comment
0 Comments