Difference Between JOIN and UNION in SQL
JOIN and UNION are the clauses in SQL, used to combine the data of two or more relations. But the way in which they combine data and format of the result obtained, differs. The JOIN clause combines the attributes of two relations to form the resultant tuples whereas, UNION clause combines the result of two queries.
Let us discuss the difference between JOIN and UNION with the help of comparison chart shown below.
Content: JOIN Vs UNION
Comparison Chart
| Basis for Comparison | JOIN | UNION |
|---|---|---|
| Basic | JOIN combines attributes of the tuples present in the two different relations that share some common fields or attributes. | UNION combines tuples of the relations that are present in the query. |
| Condition | JOIN is applicable when the two involved relations have at least one common attribute. | UNION is applicable when the number of columns present in query are same and the corresponding attributes has the same domain. |
| Types | INNER, FULL (OUTER), LEFT JOIN, RIGHT JOIN. | UNION and UNION ALL. |
| Effect | The length of the resultant tuples is more as compared to the length of tuples of the involved relations. | The number of the resultant tuples is more as compared to the number of tuples present in the each relation involved in the query. |
| Diagram | ![]() |
![]() |
Definition of JOIN
JOIN clause in SQL combines the tuples from two relations or tables resulting in a longer tuple size. The resultant tuple contains attributes from both the relation. Attributes are combined based on the common attributes between them. The different types of JOIN in SQL are INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN.
- INNER JOIN combines tuples from both the tables as long as there is a common attribute between both of them.
- LEFT JOIN results in all the tuples of the left table and matching tuple from the right table.
- RIGHT JOIN results in all the tuples from the right table and only matching tuple from the left table.
- FULL OUTER JOIN results in all the tuples from both the table though they have matching attributes or not.
INNER JOIN is same as the JOIN. You can also drop INNER keyword and simply use JOIN to perform INNER JOIN.
Definition of UNION
UNION is a set operation in SQL. UNON combines the result of two queries. The result of UNION includes the tuples from both the relations present in the query. The conditions that must be satisfied take the UNION of two relations are:
- The two relations must have the same number of attributes.
- The domains of the corresponding attribute must be same.
There are two types of UNION that are UNION and UNION ALL. The result obtained using UNION do not include duplicates. On the other hand, the result obtained using UNION ALL retains duplicate.
Key Differences Between JOIN and UNION in SQL
- The primary difference between JOIN and UNION is that JOIN combines the tuples from two relations and the resultant tuples include attributes from both the relations. On the other hand, the UNION combines the result of two SELECT queries.
- The JOIN clause is applicable only when the two relations involved have at least one attribute common in both. On the other hands, the UNION is applicable when the two relations have the same number of attribute and the domains of corresponding attributes are same.
- There are four types of JOIN INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN. But there are two types of UNION, UNION and UNION ALL.
- In JOIN, the resultant tuple has the larger size as it includes attributes from both the relation. On the other hands, in UNION the number of tuples are increased as a result include the tuple from both the relations present in the query.
Conclusion
Both being data combining operations are used in different situations. JOIN is used when we want to combine attributes of two relations having at least one attribute in common. UNION is used when we want to combine the tuples of the two relations that are present in the query.
Combining Data in SQL : Join & Union
SQL, or Structured Query Language, is used to interact with multiple tables of data. Coming from industry where excel was used heavily and daily, I found myself being intrigued by how similar SQL seemed to be to my beloved ❤ pivot tables.
This operator combines two or more tables of data using columns and a condition.
Below is the syntax for JOIN:
Let’s look at below two tables of cats and owners.
Here, join can be used to create a new table by matching Cats table’s owner_id and Owners table’s id. Note how we are using “Inner Join” and how the condition of matching the ID’s are noted after “ON”.
This inner join creates a new table containing only the data existing in both tables. In our example with cats + owners Lil’Bub is dropped because owner_id is null.
There are multiples ways to use join to combine data: using left join, right join, inner join and full join. Left join adds all data from where the left data is called, or the first table used in the syntax, with the data that exists in both tables. Inner join only shows the coinciding data between the two tables. Full join shows all the data in both tables.
UNION
This operator combines tables of data using rows. Union is often used to sort same data from two separate tables into one.
To use union below conditions have to be met:
- Each of the select statements used must have same number of conditions
- Columns required must have similar type of data
- Columns selected must be in the same order
Below is UNION’s syntax:
Let’s take example of a school keeping track of 2 classroom full of students from different cities. Union will allow the school to combine cities from both tables and create a city table.
If we want to combine the cities of both tables we can use UNION to get back a list of all cities, without duplicates. We can also use UNION ALL to get back all results, including duplicates.
EXCEPT returns left table data without coinciding data and INTERSECT is used to create table with only the coinciding data.
В чем принципиальное различие в sql оператора Join от Union? Чем принципиально отличаются? Где используются?
Ха-ха! На самом деле и JOIN и UNION делают одно и то же — объединяют SELECT запросы.
Только JOIN добавляет столбцы в результирующую таблицу,
а UNION пририсовывает к концу имеющейся таблицы ещё одну.
JOIN полезен если есть некая таблица и захотели выбрать связанные записи. Например, взяли таблицу «продажи» и дополнительно выбрали наименование клиента у каждой операции. Склеивание таблиц пойдёт по внешним ключам.
UNION полезен если нужно соединить 2 таблицы. К примеру ситуация. Есть продажи оптовые, хранятся в таблице оптовых продаж. И розничные. В таблице розничных продаж. Делаешь
select . from «оптовые»
union
select . from «розничные»
Только надо помнить что union требует одинаковости колонок во всех SELECT.
И получаешь суммарные продажи по всему предприятию.
Соединение и объединение таблиц в SQL: операторы JOIN,UNION, INTERSECT и EXCEPT
Соединение таблиц в запросе SELECT выполняется с помощью оператора JOIN.
Возможно также выполнить соединение и без оператора JOIN с помощью инструкции WHERE используя столбцы соединения, но этот синтаксис считается неявным и устаревшим.
Выделяют следующие виды соединения, каждому из которых соответствует своя форма оператора JOIN:
- CROSS JOIN — перекрестное или декартово соединение
- [INNER] JOIN — естественное или внутреннее соединение
- LEFT [OUTER] JOIN — левое внешнее соединение
- RIGHT [OUTER] JOIN — правое внешнее соединение
- FULL [OUTER] JOIN — полное внешнее соединение
Существует также тета-соединение, самосоединение и полусоединение.
Естественное соединение
Естественное соединение — внутреннее соединение или соединение по эквивалентности.
Здесь предложение FROM определяет соединяемые таблицы и в нем явно указывается тип соединения — INNER JOIN. Предложение ON является частью предложения FROM и указывает соединяемые столбцы. Выражение employee.dept_no = department.dept_no определяет условие соединения.
Эквивалентный запрос с применением неявного синтаксиса:
Соединяемые столбцы должны иметь идентичную семантику, т.е. оба столбца должны иметь одинаковое логическое значение. Соединяемые столбцы не обязательно должны иметь одинаковое имя (или даже одинаковый тип данных), хотя часто так и бывает.
Соединяются только строки имеющие одинаковое значение в соединяемых столбцах. Строки, не имеющие таких одинаковых значений в результирующий набор вообще не попадут.
В инструкции SELECT объединить можно до 64 таблиц (ограничение MS SQL), при этом один оператор JOIN соединяет только две таблицы:
Декартово произведение (перекрестное соединение)
Декартово произведение (перекрестное соединение) соединяет каждую строку первой таблицы с каждой строкой второй. Результатом декартово произведения первой таблицы с n строками и второй таблицы с m строками будет таблица с n × m строками.
Внешнее соединение
Внешнее соединение позволяет в отличие от внутреннего извлечь не только строки с одинаковыми значениями соединяемых столбцов, но и строки без совпадений из одной или обеих таблиц.
Выделяют три вида внешних соединений:
-
левое внешнее соединение — в результирующий набор попадают все строки из таблицы с левой стороны оператора сравнения (независимо от того имеются ли совпадающие строки с правой стороны), а из таблицы с правой стороны — только строки с совпадающими значениями столбцов. При этом если для строки из левой таблицы нет соответствий в правой таблице, значениям строки в правой таблице будут присвоены NULL
Тета-соединение
Условие сравнения столбцов соединения не обязательно должно быть равенством, но может быть любым другим сравнением. Соединение, в котором используется общее условие сравнения столбцов соединения, называется тета-соединением:
Самосоединение
Самосоединение — это естественное соединение таблицы с самой собой. При этом один столбец таблицы сравнивается сам с собой. Сравнивание столбца с самим собой означает, что в предложении FROM инструкции SELECT имя таблицы употребляется дважды. Поэтому необходимо иметь возможность ссылаться на имя одной и той же таблицы дважды. Это можно осуществить, используя, по крайней мере, один псевдоним. То же самое относится и к именам столбцов в условии соединения в инструкции SELECT. Для того чтобы различить столбцы с одинаковыми именами, необходимо использовать уточненные имена.
Полусоединение
Полусоединение похоже на естественное соединение, но возвращает только набор всех строк из одной таблицы, для которой в другой таблице есть одно или несколько совпадений.
Оператор UNION
Оператор UNION объединяет результаты двух или более запросов в один результирующий набор, в который входят все строки, принадлежащие всем запросам в объединении:

