6

What is the difference between the SQL keywords union and join?

Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
angel ansari
  • 99
  • 2
  • 5

5 Answers5

16

The UNION operator is used to combine the result-set of two or more SELECT statements.

The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables.

The tutorials on these two topics (linked to above) on w3schools.com go into further detail.

Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
  • Also, A union is from the branch of mathematics called set theory. This is a good image of a union http://en.wikipedia.org/wiki/File:Venn0111.svg – Winter May 17 '10 at 22:03
4

Think of joins as horizontal and unions as vertical

Chris Bednarski
  • 3,364
  • 25
  • 33
  • 1
    Are you sure this is correct? As stated here: http://stackoverflow.com/a/905383/1170330 `union` combines results one after the other (horizontally), whereas `join` combines them side by side (vertically). – Evgenij Reznik Aug 15 '15 at 14:58
  • @user1170330 My answer matches the other answer. I think you have your directions confused. – Chris Bednarski Aug 17 '15 at 03:07
  • UNION puts lines from queries after each other, while JOIN makes a cartesian product and subsets it -- completely different operations. It is just like the SO link @EvgenijReznik mentions about. – Pepe Alvarez Nov 27 '21 at 19:58
1

Union is a combination of elements from multiple sets.

Join is a subset of the cross product of multiple sets

Midhat
  • 17,454
  • 22
  • 87
  • 114
1

If need combinate more then one queries use operator Union, this operator execute first query and the second query, and then return all result in one dataset see more

select field from t1
union 
select field from t2

If need create query to select data from two or more table then use operator join see more

select t1.field, t2.field
from t1.number inner join t2.key on t1.number=t2.key
Andriy Mytroshyn
  • 221
  • 1
  • 5
  • 14
0

Union:

  1. In UNION you need to take care That col length, datatype and no.of columns used in SELECT statement should be same in both tables
  2. The result is displayed with first table column names as a combination of data from two tables by eliminating duplicates
  3. To use UNION you should have at least two SELECT statements

Join:

  1. In JOINs there is no need to have rules mentioned in point 1.
  2. The result is displayed with all columns mentioned in query depending on the type of JOIN used(Outer, Inner,Cartesian..)
  3. One SELECT statement is enough

Hope this helps u..

Stephen Byrne
  • 7,400
  • 1
  • 31
  • 51
Sai
  • 659
  • 4
  • 12
  • 21