Introduction to SQL JOINs
Seven different ways you can return data from two relational tables; excluding cross joins and self referencing joins:
- INNER JOIN
- LEFT JOIN
- RIGHT JOIN
- OUTER JOIN
- LEFT JOIN excluding INNER JOIN
- RIGHT JOIN excluding INNER JOIN
- OUTER JOIN excluding INNER JOIN
For the sake of this article, 5, 6, and 7 are LEFT EXCLUDING JOIN , RIGHT Excluding JOIN , and OUTER Excluding JOIN , respectively. Some may argue that 5, 6, and 7 are not really joining the two tables, but for simplicity, let’s refer to these as joins because you use a SQL join in each of these queries (but exclude some records with a WHERE clause).
INNER JOIN ¶

This is the simplest, most understood join and is the most common. This query will return all of the records in the left table ( Table_A ) that have a matching record in the right table ( Table_B ). This join is written as follows:
LEFT JOIN ¶

This query will return all of the records in the left table ( Table_A ) regardless if any of those records have a match in the right table ( Table_B ). It will also return any matching records from the right table. This join is written as follows:
RIGHT JOIN ¶

This query will return all of the records in the right table ( Table_B ) regardless if any of those records have a match in the left table ( Table_A ). It will also return any matching records from the left table. This join is written as follows:
OUTER JOIN ¶

This Join can also be referred to as a FULL OUTER JOIN or a FULL JOIN . This query will return all of the records from both tables, joining records from the left table ( Table_A ) that match records from the right table ( Table_B ). This join is written as follows:
LEFT Excluding JOIN ¶

This query will return all of the records in the left table ( Table_A ) that do not match any records in the right table ( Table_B ). This join is written as follows:
RIGHT Excluding JOIN ¶

This query will return all of the records in the right table ( Table_B ) that do not match any records in the left table ( Table_A ). This join is written as follows:
OUTER Excluding JOIN ¶

This query will return all of the records in the left table ( Table_A ) and all of the records in the right table ( Table_B ) that do not match. I have yet to have a need for using this type of join, but all of the others, I use quite frequently. This join is written as follows:
Examples¶
Suppose we have two tables, TABLE_A and TABLE_B . The data in these tables are shown below:
The results of the seven joins are shown below:
INNER JOIN
LEFT JOIN
RIGHT JOIN
OUTER JOIN
LEFT Excluding JOIN
RIGHT Excluding JOIN
OUTER Excluding JOIN
Conclusion¶
Note on the OUTER JOIN that the inner joined records are returned first, followed by the right joined records, and then finally the left joined records (at least, that’s how my Microsoft SQL Server did it; this, of course, is without using any ORDER BY statement).
SQL Joins — LEFT Join, RIGHT Join, and INNER Join Explained
SQL is a programming language we use to interact with relational databases. SQL databases contain tables, which contain rows of data. These tables usually contain similar or related data.
In an office management web application database, you would have tables for employees , their departments , their managers , the projects they work on, and so on depending on the structure of your application.
In the employees table, you would find data like the employee ID, name, salary, department ID (used to link the employee to the department), and other fields that match your needs. The other tables would also contain data for their specific entities.
What Are Joins?
If you ever need to bring multiple tables in your database together to access the data, you use a JOIN.
Joins let you fetch data that is scattered across tables. For example, using the database tables that we’ll create in a moment, we’ll be able to get all the details of an employee, along with their manager name, and department they’re working in by using a join.
A join lets you use a single query to achieve this. You use a join because you can only get this data by bringing data from the employees table, departments table, and projects table together. In simple terms, you would be JOIN-ing these tables together.
To perform a join, you use the JOIN keyword. And we’ll see how it works in this tutorial.
Prerequisites:
To continue with this tutorial, you should know the basics of insertion and retrieval operations with SQL.
Also, you can setup a demo database that we’ll use for this article. The database should have tables like this:
How to Use an Inner Join in SQL
There are many types of joins in SQL, and each one has a different purpose.
The inner join is the most basic type of join. It is so basic that sometimes, you can omit the JOIN keyword and still perform an inner join.
For example, say you want to fetch the name of all employees in the organanization, along with the name of their departments. In a situation like this, you need data from both the employees table and the departments table. A simple join like this would do:
So how does this actually work? To start with, take a look at the FROM part of the query:
Here, data is being fetched from more than one table, and each table is aliased. The alias is very useful for scenarios where both tables have similarly named fields, like the id field both tables have in this case. You would be able to access the different fields easily using the short alias created.
Next, in the SELECT part of the query, we also specify the columns we want (and we use the alias to tell which table each value comes from):
And finally, to ensure only correct values are matched to each other, the WHERE part of the query specifies the conditions that have to be met for the data to be joined.
So for the first employee, the dept_id is 1 , so we fetch the department with id = 1 , and it's name is returned. This happens for as many rows as there are in the employees table.
The result of the query looks like this:
Here, notice that the number of employees returned is smaller than the number of employees that actually exist. This is because when you use an INNER JOIN, you only get records that exist in both tables.
That is, the employee with id = 6 that was not returned has a dept_it = 8 . Now, this department isn't in the departments table, so it wasn't returned.
Another way to achieve this same result would be to actually spell out the JOIN like this:
Or use the INNER JOIN like this:
These queries return exactly the same result as the first one. But they are more readable as they’re explicit.
In these queries, you’re selecting from the employees table, then joining the departments table to the result. The ON in the query is used to specify the conditions on which to JOIN. It's the same as the WHERE condition in the first query.
INNER JOIN Use Case
In real applications, you use an INNER JOIN when only records that exist in both tables matter.
For example, in an inventory management application, you could have a table for sales , and another for products . Now, the sales table will contain product_id (a reference to the sold product), along with other details like sold_at (when the product was sold) and maybe customer details.
Now say it’s end of the week and you need to do a sales report. You would need to fetch all sales records, along with the product name and price to display on a dashboard or export as a CSV of some sort.
To do this, you would use an INNER JOIN of the products table on the sales table, because you do not care about products that were not sold — you only want to see every sale that was made, and the name and price of the product that was sold. Every other product will be exempted from this report.
How to Use a Left Join in SQL
In another scenario, you might want to fetch all the employee names and their department names, but this time without leaving any employee or department name out. Here, you’d you use a LEFT JOIN.
In a LEFT JOIN, every record from the table on the left, the base table, will be returned. Then values from the right table, the table being joined, will be added where they exist.
The LEFT JOIN is also known as LEFT OUTER JOIN and you can use them interchangeably.
So to fetch all employee and department names, you can modify the previous query to use LEFT JOIN, like this:
The result of this query looks like this now:
Now, employee with id = 6 and dept_id = 8 is returned, with the department name being set as NULL because there is no department with id = 8 .
LEFT JOIN Use Case
In real applications, you use a LEFT JOIN when there’s a primary, always existing entity that can be related to another entity that doesn’t always exist.
An easy use case would be in a multi-vendor ecommerce application where after a user signs up, they can set up a store and add products to the store.
A user, on signing up, doesn’t automatically have a store until they create it. So if you try to view all users, with their store details, you would use a LEFT JOIN of the stores table on the users table. This is because every record in the users table is important, store or no store.
When the user has a store set up, the store details are returned, and if otherwise, NULL is returned. But, you wouldn’t be losing any existing data.
How to Use a Right Join in SQL
The RIGHT JOIN works like the opposite of the LEFT JOIN. In a RIGHT JOIN, every record from the table on the right, the table being joined, will be returned. Then values from the left table, the base table, will be added where they exist.
The RIGHT JOIN is also known as the RIGHT OUTER JOIN and you can use them interchangeably.
An example would be to modify the previous query to use a RIGHT JOIN instead of a LEFT JOIN, like this:
Now, your result looks like this:
Now, every department in the departments table was returned. And employees in those departments were returned too. For the last row, there is no employee with dept_id = 4 , which is why the NULL value gets returned.
RIGHT JOIN Use Case
The RIGHT JOIN works exactly as the LEFT JOIN works in real applications. The difference between them comes from the level of importance of the tables to be joined.
The LEFT JOIN is more commonly used because you very likely will write your query from left to right, listing tables in that order of importance too. Otherwise, the RIGHT JOIN works exactly as the LEFT JOIN.
How to Combine JOINS in SQL
So far, we’ve only joined one table to another. But, you can actually join as many tables as you like by using any or all of these joins together as you like.
For example, say you want to fetch the names of all employees, with their department names, manager names, and projects names. You would have to join the employees table to the departments table, the managers table, and the projects table. You can achieve this using this query:
In this query, start from the employees table as a base table. Then you LEFT JOIN the departments table. You also LEFT JOIN the managers table, and finally, the projects table.
The result of this query will look like this:
The reason for using a LEFT JOIN here is because you have to fetch ALL employees. You could use an INNER JOIN in place of the LEFT JOIN in the managers table because all employees have a manager_id that actually exists in the managers table. But to be safe, you can just use the LEFT JOIN.
How to Use a Cross Join in SQL
This is also known as a CARTESIAN JOIN. It returns every record from both tables in a multiplication-like manner. It returns every possible combination of rows from both tables. It doesn’t need a JOIN condition like the other JOINs.
For example, if you do a CROSS JOIN between tables employees and departments , your result will look like this:
Here you have 24 rows, which is a product of the number of rows in the employees table, 6, and the number of rows in the departments table, 4. The records were returned so that for every record in the employees table, it is mapped to a record in the departments table.
CROSS JOIN Use Case
A common use case of CROSS JOIN would be in an ecommerce application where it is possible to have size or color variations of all products. If you ever need to fetch a list of all products in different sizes, like this:
This result was gotten from CROSS JOINing a sizes table that contains an id for each size, a string size that can be either 'Small', 'Medium', or 'Large' and another field called ratio to affect how this size affects the product price. So, for every product, it is mapped to a size, and the price is calculated.
How to Use a Self Join in SQL
As the name implies, is when you try to join a table to itself. There is no self JOIN keyword.
Take this new categories table, for example. This table contains both main categories and sub-categories. If you ever have to fetch the categories and their sub-categories, you can use a SELF JOIN.
Here, see how the table was referenced twice. Be careful with the alias as it’s important in differentiating both instances. The result of this query looks like this:
SELF JOIN Use Case
In many applications, you find hierarchical data stored in a single table. Like the category and sub-category as shown in the previous example. Or as in employee and manager, because they’re both employees of the company.
In case of the latter, the table will have fields such as id , name , manager_id (this is basically the id of another employee). Let's say you want to write a query where you have to fetch a list of managers and the number of their employees. Given that these managers are also employees, you only have one table to fetch from, the employees table. To do this fetch, do a SELF JOIN of the employees table on the employees table like this:
This would correctly return the managers and the number of employees working under them.
Summary
I hope you now understand SQL JOINs, the different types, and when to use them so you can write better queries.
All the JOINs here work with MySQL. There are other JOINs like FULL OUTER JOIN and NATURAL JOIN that we didn’t discuss, but you can look into them yourself if you like.
If you have any questions or relevant advice, please get in touch with me to share them.
This article was originally published at https://www.freecodecamp.org on January 10, 2023.
To read more of my articles or follow my work, you can connect with me on LinkedIn, Twitter, and Github. It’s quick, it’s easy, and it’s free!
В чем разница между INNER, LEFT и RIGHT JOIN?

В данной статье я раскрою разницу между SQL-запросами INNER, LEFT и RIGHT JOIN. Здесь описываются базовые случаи, для каждой конкретной платформы (MySQL, MSSQL, Oracle и прочих) могут быть свои нюансы.
INNER JOIN
Возвращаются все записи из таблиц table_01 и table_02, связанные посредством primary/foreign ключей, и соответствующие условию WHERE для таблицы table_01. Если в какой-либо из таблиц отсутствует запись, соответствующая соседней, то в выдачу такая пара включена не будет. Иными словами, выдадутся только те записи, которые есть и в первой, и во второй таблице. То есть выборка идет фактически по связи (ключу), выдадутся только те записи, которые связаны между собой. «Одинокие» записи, для которых нет пары в связи, выданы не будут.
LEFT JOIN
Возвращаются все данные из «левой» таблицы, даже если не найдено соответствий в «правой» таблице («левая» таблица в SQL-запросе стоит левее знака равно, «правая» — правее, то есть обычная логика правой и левой руки). Иными словами, если мы присоединяем к «левой» таблице «правую», то выберутся все записи в соответствии с условиями WHERE для левой таблицы. Если в «правой» таблице не было соответствий по ключам, они будут возвращены как NULL. Таким образом, здесь главной выступает «левая» таблица, и относительно нее идет выдача. В условии ON «левая» таблица прописывается первой по порядку (table_01), а «правая» – второй (table_02):
RIGHT JOIN
Возвращаются все данные из «правой» таблицы, даже если не найдено соответствий в «левой» таблице. То есть примерно также, как и в LEFT JOIN, только NULL вернется для полей «левой» таблицы. Грубо говоря, эта выборка ставит во главу угла правую «таблицу», относительно нее идет выдача. Обратите внимание на WHERE в следующем примере, условие выборки затрагивает «правую» таблицу:
Таким образом, мы разложили по полочкам, в чем отличие INNER, LEFT и RIGHT JOIN. Разумеется, представленная выше информация не нова, но она может быть полезна начинающим программистам, которые часто путаются в типах запросов.
Понимание джойнов сломано. Это точно не пересечение кругов, честно
Так получилось, что я провожу довольно много собеседований на должность веб-программиста. Один из обязательных вопросов, который я задаю — это чем отличается INNER JOIN от LEFT JOIN.
Чаще всего ответ примерно такой: «inner join — это как бы пересечение множеств, т.е. остается только то, что есть в обеих таблицах, а left join — это когда левая таблица остается без изменений, а от правой добавляется пересечение множеств. Для всех остальных строк добавляется null». Еще, бывает, рисуют пересекающиеся круги.
Я так устал от этих ответов с пересечениями множеств и кругов, что даже перестал поправлять людей.
Дело в том, что этот ответ в общем случае неверен. Ну или, как минимум, не точен.
Давайте рассмотрим почему, и заодно затронем еще парочку тонкостей join-ов.
Во-первых, таблица — это вообще не множество. По математическому определению, во множестве все элементы уникальны, не повторяются, а в таблицах в общем случае это вообще-то не так. Вторая беда, что термин «пересечение» только путает.
(Update. В комментах идут жаркие споры о теории множеств и уникальности. Очень интересно, много нового узнал, спасибо)
INNER JOIN
Давайте сразу пример.
Итак, создадим две одинаковых таблицы с одной колонкой id, в каждой из этих таблиц пусть будет по две строки со значением 1 и еще что-нибудь.
Давайте, их, что ли, поджойним
Если бы это было «пересечение множеств», или хотя бы «пересечение таблиц», то мы бы увидели две строки с единицами.

На практике ответ будет такой:

Для начала рассмотрим, что такое CROSS JOIN. Вдруг кто-то не в курсе.
CROSS JOIN — это просто все возможные комбинации соединения строк двух таблиц. Например, есть две таблицы, в одной из них 3 строки, в другой — 2:
Тогда CROSS JOIN будет порождать 6 строк.
Так вот, вернемся к нашим баранам.
Конструкция
— это, можно сказать, всего лишь синтаксический сахар к
Т.е. по сути INNER JOIN — это все комбинации соединений строк с неким фильтром condition . В общем-то, можно это представлять по разному, кому как удобнее, но точно не как пересечение каких-то там кругов.
Небольшой disclaimer: хотя inner join логически эквивалентен cross join с фильтром, это не значит, что база будет делать именно так, в тупую: генерить все комбинации и фильтровать. На самом деле там более интересные алгоритмы.
LEFT JOIN
Если вы считаете, что левая таблица всегда остается неизменной, а к ней присоединяется или значение из правой таблицы или null, то это в общем случае не так, а именно в случае когда есть повторы данных.
Опять же, создадим две таблицы:
Теперь сделаем LEFT JOIN:
Результат будет содержать 5 строк, а не по количеству строк в левой таблице, как думают очень многие.
Так что, LEFT JOIN — это тоже самое что и INNER JOIN (т.е. все комбинации соединений строк, отфильтрованных по какому-то условию), и плюс еще записи из левой таблицы, для которых в правой по этому фильтру ничего не совпало.
LEFT JOIN можно переформулировать так:
Сложноватое объяснение, но что поделать, зато оно правдивее, чем круги с пересечениями и т.д.
Условие ON
Удивительно, но по моим ощущениям 99% разработчиков считают, что в условии ON должен быть id из одной таблицы и id из второй. На самом деле там любое булево выражение.
Например, есть таблица со статистикой юзеров users_stats, и таблица с ip адресами городов.
Тогда к статистике можно прибавить город
где && — оператор пересечения (см. расширение посгреса ip4r)
Если в условии ON поставить true, то это будет полный аналог CROSS JOIN
Производительность
Есть люди, которые боятся join-ов как огня. Потому что «они тормозят». Знаю таких, где есть полный запрет join-ов по проекту. Т.е. люди скачивают две-три таблицы себе в код и джойнят вручную в каком-нибудь php.
Это, прямо скажем, странно.
Если джойнов немного, и правильно сделаны индексы, то всё будет работать быстро. Проблемы будут возникать скорее всего лишь тогда, когда у вас таблиц будет с десяток в одном запросе. Дело в том, что планировщику нужно определить, в какой последовательности осуществлять джойны, как выгоднее это сделать.
Сложность этой задачи O(n!), где n — количество объединяемых таблиц. Поэтому для большого количества таблиц, потратив некоторое время на поиски оптимальной последовательности, планировщик прекращает эти поиски и делает такой план, какой успел придумать. В этом случае иногда бывает выгодно вынести часть запроса в подзапрос CTE; например, если вы точно знаете, что, поджойнив две таблицы, мы получим очень мало записей, и остальные джойны будут стоить копейки.
Кстати, Еще маленький совет по производительности. Если нужно просто найти элементы в таблице, которых нет в другой таблице, то лучше использовать не ‘LEFT JOIN… WHERE… IS NULL’, а конструкцию EXISTS. Это и читабельнее, и быстрее.
Выводы
Как мне кажется, не стоит использовать диаграммы Венна для объяснения джойнов. Также, похоже, нужно избегать термина «пересечение».
Как объяснить на картинке джойны корректно, я, честно говоря, не представляю. Если вы знаете — расскажите, плиз, и киньте в коменты.
Update В этом видео я наглядно объясняю, как правильно визуализировать джойны (English):