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.
What is the difference between JOIN and UNION?
What is the difference between JOIN and UNION ? Can I have an example?
14 Answers 14
UNION puts lines from queries after each other, while JOIN makes a cartesian product and subsets it — completely different operations. Trivial example of UNION :
similary trivial example of JOIN :
UNION combines the results of two or more queries into a single result set that includes all the rows that belong to all queries in the union.
By using JOINs, you can retrieve data from two or more tables based on logical relationships between the tables. Joins indicate how SQL should use data from one table to select the rows in another table.
The UNION operation is different from using JOINs that combine columns from two tables.
This will output all the rows from both the tables for which the condition a.Id = b.AFKId is true.
You may see the same schematic explanations for both, but these are totally confusing.


![]()
![]()
A join is used for displaying columns with the same or different names from different tables. The output displayed will have all the columns shown individually. That is, the columns will be aligned next to each other.
UNION:
The UNION set operator is used for combining data from two tables which have columns with the same datatype. When a UNION is performed the data from both tables will be collected in a single column having the same datatype.
See the two tables shown below:
Now for performing a JOIN type the query is shown below.
UNION means that you have to tables or resultset with the same amount and type of columns and you add this to tables/resultsets together. Look at this example:
Разница между JOIN и UNION в SQL
JOIN и UNION — это предложения в SQL, используемые для объединения данных двух или более отношений. Но способ, которым они объединяют данные и формат полученного результата, отличается. Предложение JOIN объединяет атрибуты двух отношений для формирования результирующих кортежей, тогда как предложение UNION объединяет результат двух запросов. Давайте обсудим разницу между JOIN и UNION с помощью сравнительной таблицы, показанной ниже.
Сравнительная таблица
| Основа для сравнения | ПРИСОЕДИНИТЬСЯ | UNION |
|---|---|---|
| основной | JOIN объединяет атрибуты кортежей, присутствующих в двух разных отношениях, которые имеют общие поля или атрибуты. | UNION объединяет кортежи отношений, которые присутствуют в запросе. |
| Состояние | JOIN применяется, когда два вовлеченных отношения имеют хотя бы один общий атрибут. | UNION применяется, когда число столбцов, присутствующих в запросе, одинаково и соответствующие атрибуты имеют одинаковый домен. |
| Типы | ВНУТРЕННЯЯ, ПОЛНАЯ (НАРУЖНАЯ), ЛЕВАЯ РЕГИСТРАЦИЯ, ПРАВАЯ СОЕДИНЕНИЕ | СОЮЗ и СОЮЗ ВСЕХ. |
| эффект | Длина результирующих кортежей больше по сравнению с длиной кортежей вовлеченных отношений. | Количество результирующих кортежей больше по сравнению с количеством кортежей, присутствующих в каждом отношении, участвующем в запросе. |
| схема | ![]() |
![]() |
Определение JOIN
Предложение JOIN в SQL объединяет кортежи из двух отношений или таблиц, что приводит к увеличению размера кортежа. Результирующий кортеж содержит атрибуты из обоих отношений. Атрибуты объединяются на основе общих атрибутов между ними. Различные типы JOIN в SQL: INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN.
INNER JOIN объединяет кортежи из обеих таблиц, если между ними существует общий атрибут. LEFT JOIN приводит ко всем кортежам левой таблицы и соответствующим кортежу из правой таблицы. RIGHT JOIN приводит ко всем кортежам из правой таблицы и соответствует только кортежу из левой таблицы. FULL OUTER JOIN приводит ко всем кортежам из обеих таблиц, хотя они имеют совпадающие атрибуты или нет.
ВНУТРЕННЕЕ СОЕДИНЕНИЕ — то же самое, что СОЕДИНЕНИЕ. Вы также можете удалить ключевое слово INNER и просто использовать JOIN для выполнения INNER JOIN.
Определение СОЮЗА
UNION — это операция над множествами в SQL. UNON объединяет результат двух запросов. Результат UNION включает в себя кортежи обоих отношений, присутствующих в запросе. Условия, которые должны быть выполнены для объединения двух отношений:
- Два отношения должны иметь одинаковое количество атрибутов.
- Домены соответствующего атрибута должны быть одинаковыми.
Существует два типа UNION: UNION и UNION ALL . Результат, полученный с помощью UNION, не содержит дубликатов. С другой стороны, результат, полученный с помощью UNION ALL, сохраняет дубликат.
Ключевые различия между JOIN и UNION в SQL
- Основное различие между JOIN и UNION состоит в том, что JOIN объединяет кортежи из двух отношений, а результирующие кортежи включают атрибуты из обоих отношений. С другой стороны, UNION объединяет результат двух запросов SELECT.
- Предложение JOIN применимо только тогда, когда два участвующих отношения имеют хотя бы один общий атрибут в обоих. С другой стороны, UNION применяется, когда два отношения имеют одинаковое количество атрибутов и домены соответствующих атрибутов одинаковы.
- Существует четыре типа РЕАГИРОВАНИЯ ВНУТРЕННЕГО РЕШЕНИЯ, ЛЕВОГО СОЕДИНЕНИЯ, ПРЯМОГО СОЕДИНЕНИЯ, ПОЛНОГО НАРУЖНОГО СОЕДИНЕНИЯ. Но есть два типа UNION, UNION и UNION ALL.
- В JOIN результирующий кортеж имеет больший размер, поскольку включает атрибуты обоих отношений. С другой стороны, в UNION число кортежей увеличивается, в результате чего в них входит кортеж из обоих отношений, присутствующих в запросе.
Заключение:
Обе операции объединения данных используются в разных ситуациях. JOIN используется, когда мы хотим объединить атрибуты двух отношений, имеющих хотя бы один общий атрибут. UNION используется, когда мы хотим объединить кортежи двух отношений, которые присутствуют в запросе.
What Is the Difference Between a Join and a UNION?
Use joins and UNIONS to combine data from two or more tables. Read this article to find out each command’s strengths and when to use them.
To get the most of this and our other lessons are sure to practice using the examples!
All the examples for this lesson are based on Microsoft SQL Server Management Studio and the AdventureWorks2012 database.
What Is the Difference Between a Join and UNION?
There are several options you can use to combine data from multiple data. One of those option is to decide whether to use Joins or Unions. But before you look into choosing one over the other, you need to understand how they combine data.
In simple terms, joins combine data into new columns. The query uses a “join condition” to match column together to form new rows. The new rows consist of column values from both tables.
Unions combine data into new rows. Here the union takes the result as rows and appends them together row by row.
Join – Visual Depiction
Here is a visual depiction of a join. Notice we combine columns from Table A and B to create the result.

Joins Combine Columns
Each row in the result contains columns from BOTH table A and B. Typically one or more columns are compared. Column are then combined when the comparison is true.
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 lookup column values by using the primary key in another.
Union – Visual Depiction
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.

Unions Combine Rows
Use UNION when you need to combine row from two different queries together.
A use case may be that you have two tables: Teachers and Students. You would like to create a master list of names and birthdays sorted by date.
To do this you can use a union to first combine the rows into a single result and then sort them.
Let’s now take a slightly deeper look into both.
Combining Data with a Join
In this section well look at the inner join. It is one of the most common forms of join and is used when you need to match rows from two tables. Rows that match remain in the result, those that don’t are rejected.
Below is an example of a simple select statement with an INNER JOIN clause.
Here is an example of using a join to lookup an employee’s name:
Here are the results

INNER JOIN Results
You can learn more about INNER JOINS here, but for now here are two things I want to point out.
First, notice the join condition , see how we are matching BusinessEntityID from both tables.
Second, check out that the results contain columns from both tables .
Combining Data with a UNION
Let’s take a closer look at the UNION statement. In SQL the UNION statement looks like
Suppose you were asked to provide a list of all AdventureWorks2012 product categories and subcategories. To do this you could write two separate queries and provide two separate results, such as two spreadsheets, or you could use the UNION clause to deliver one result.
In order to unite two tables there are a couple of requirements:
- The number of columns must be the same for both select statements.
- The columns, in order, must be of the same data type.
Combining rows eliminates duplicates. If you want to keep all rows from both select statement’s results use the ALL keyword
Conclusion
To combine data into a single result use both joins and unions. They both go about this is different ways. Difference tables’ columns are combine using a join. The union combines different tables’ rows.
This site uses Akismet to reduce spam. Learn how your comment data is processed.
can we join and compare two different data types of different columns of different tables by using join?
I think this post is very helpful but I’m still a little bit confused about it

