Home » What is the difference between “INNER JOIN” and “OUTER JOIN”?

# What is the difference between “INNER JOIN” and “OUTER JOIN”?

## Solutons:

Assuming you’re joining on columns with no duplicates, which is a very common case:

• An inner join of A and B gives the result of A intersect B, i.e. the inner part of a Venn diagram intersection.

• An outer join of A and B gives the results of A union B, i.e. the outer parts of a Venn diagram union.

Examples

Suppose you have two tables, with a single column each, and data as follows:

``````A    B
-    -
1    3
2    4
3    5
4    6
``````

Note that (1,2) are unique to A, (3,4) are common, and (5,6) are unique to B.

Inner join

An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common.

``````select * from a INNER JOIN b on a.a = b.b;
select a.*, b.*  from a,b where a.a = b.b;

a | b
--+--
3 | 3
4 | 4
``````

Left outer join

A left outer join will give all rows in A, plus any common rows in B.

``````select * from a LEFT OUTER JOIN b on a.a = b.b;
select a.*, b.*  from a,b where a.a = b.b(+);

a |  b
--+-----
1 | null
2 | null
3 |    3
4 |    4
``````

Right outer join

A right outer join will give all rows in B, plus any common rows in A.

``````select * from a RIGHT OUTER JOIN b on a.a = b.b;
select a.*, b.*  from a,b where a.a(+) = b.b;

a    |  b
-----+----
3    |  3
4    |  4
null |  5
null |  6
``````

Full outer join

A full outer join will give you the union of A and B, i.e. all the rows in A and all the rows in B. If something in A doesn’t have a corresponding datum in B, then the B portion is null, and vice versa.

``````select * from a FULL OUTER JOIN b on a.a = b.b;

a   |  b
-----+-----
1 | null
2 | null
3 |    3
4 |    4
null |    6
null |    5
``````

The Venn diagrams don’t really do it for me.

They don’t show any distinction between a cross join and an inner join, for example, or more generally show any distinction between different types of join predicate or provide a framework for reasoning about how they will operate.

There is no substitute for understanding the logical processing and it is relatively straightforward to grasp anyway.

1. Imagine a cross join.
2. Evaluate the `on` clause against all rows from step 1 keeping those where the predicate evaluates to `true`
3. (For outer joins only) add back in any outer rows that were lost in step 2.

(NB: In practice the query optimiser may find more efficient ways of executing the query than the purely logical description above but the final result must be the same)

I’ll start off with an animated version of a full outer join. Further explanation follows.

# Explanation

Source Tables

First start with a `CROSS JOIN` (AKA Cartesian Product). This does not have an `ON` clause and simply returns every combination of rows from the two tables.

SELECT A.Colour, B.Colour FROM A CROSS JOIN B

Inner and Outer joins have an “ON” clause predicate.

• Inner Join. Evaluate the condition in the “ON” clause for all rows in the cross join result. If true return the joined row. Otherwise discard it.
• Left Outer Join. Same as inner join then for any rows in the left table that did not match anything output these with NULL values for the right table columns.
• Right Outer Join. Same as inner join then for any rows in the right table that did not match anything output these with NULL values for the left table columns.
• Full Outer Join. Same as inner join then preserve left non matched rows as in left outer join and right non matching rows as per right outer join.

# Some examples

SELECT A.Colour, B.Colour FROM A INNER JOIN B ON A.Colour = B.Colour

The above is the classic equi join.

## Animated Version

### SELECT A.Colour, B.Colour FROM A INNER JOIN B ON A.Colour NOT IN (‘Green’,’Blue’)

The inner join condition need not necessarily be an equality condition and it need not reference columns from both (or even either) of the tables. Evaluating `A.Colour NOT IN ('Green','Blue')` on each row of the cross join returns.

SELECT A.Colour, B.Colour FROM A INNER JOIN B ON 1 =1

The join condition evaluates to true for all rows in the cross join result so this is just the same as a cross join. I won’t repeat the picture of the 16 rows again.

### SELECT A.Colour, B.Colour FROM A LEFT OUTER JOIN B ON A.Colour = B.Colour

Outer Joins are logically evaluated in the same way as inner joins except that if a row from the left table (for a left join) does not join with any rows from the right hand table at all it is preserved in the result with `NULL` values for the right hand columns.

### SELECT A.Colour, B.Colour FROM A LEFT OUTER JOIN B ON A.Colour = B.Colour WHERE B.Colour IS NULL

This simply restricts the previous result to only return the rows where `B.Colour IS NULL`. In this particular case these will be the rows that were preserved as they had no match in the right hand table and the query returns the single red row not matched in table `B`. This is known as an anti semi join.

It is important to select a column for the `IS NULL` test that is either not nullable or for which the join condition ensures that any `NULL` values will be excluded in order for this pattern to work correctly and avoid just bringing back rows which happen to have a `NULL` value for that column in addition to the un matched rows.

### SELECT A.Colour, B.Colour FROM A RIGHT OUTER JOIN B ON A.Colour = B.Colour

Right outer joins act similarly to left outer joins except they preserve non matching rows from the right table and null extend the left hand columns.

### SELECT A.Colour, B.Colour FROM A FULL OUTER JOIN B ON A.Colour = B.Colour

Full outer joins combine the behaviour of left and right joins and preserve the non matching rows from both the left and the right tables.

### SELECT A.Colour, B.Colour FROM A FULL OUTER JOIN B ON 1 = 0

No rows in the cross join match the `1=0` predicate. All rows from both sides are preserved using normal outer join rules with NULL in the columns from the table on the other side.

### SELECT COALESCE(A.Colour, B.Colour) AS Colour FROM A FULL OUTER JOIN B ON 1 = 0

With a minor amend to the preceding query one could simulate a `UNION ALL` of the two tables.

### SELECT A.Colour, B.Colour FROM A LEFT OUTER JOIN B ON A.Colour = B.Colour WHERE B.Colour=”Green”

Note that the `WHERE` clause (if present) logically runs after the join. One common error is to perform a left outer join and then include a WHERE clause with a condition on the right table that ends up excluding the non matching rows. The above ends up performing the outer join…

… And then the “Where” clause runs. `NULL= 'Green'` does not evaluate to true so the row preserved by the outer join ends up discarded (along with the blue one) effectively converting the join back to an inner one.

If the intention was to include only rows from B where Colour is Green and all rows from A regardless the correct syntax would be

## SQL Fiddle

See these examples run live at SQLFiddle.com.

Joins are used to combine the data from two tables, with the result being a new, temporary table. Joins are performed based on something called a predicate, which specifies the condition to use in order to perform a join. The difference between an inner join and an outer join is that an inner join will return only the rows that actually match based on the join predicate.
For eg- Lets consider Employee and Location table:

Inner Join:-
Inner join creates a new result table by combining column values of two tables (Employee and Location) based upon the join-predicate. The query compares each row of Employee with each row of Location to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied by matching non-NULL values, column values for each matched pair of rows of Employee and Location are combined into a result row.
Here’s what the SQL for an inner join will look like:

``````select  * from employee inner join location on employee.empID = location.empID
OR
select  * from employee, location where employee.empID = location.empID
``````

Now, here is what the result of running that SQL would look like:

Outer Join:-
An outer join does not require each record in the two joined tables to have a matching record. The joined table retains each record—even if no other matching record exists. Outer joins subdivide further into left outer joins and right outer joins, depending on which table’s rows are retained (left or right).

Left Outer Join:-
The result of a left outer join (or simply left join) for tables Employee and Location always contains all records of the “left” table (Employee), even if the join-condition does not find any matching record in the “right” table (Location).
Here is what the SQL for a left outer join would look like, using the tables above:

``````select  * from employee left outer join location on employee.empID = location.empID;
//Use of outer keyword is optional
``````

Now, here is what the result of running this SQL would look like:

Right Outer Join:-
A right outer join (or right join) closely resembles a left outer join, except with the treatment of the tables reversed. Every row from the “right” table (Location) will appear in the joined table at least once. If no matching row from the “left” table (Employee) exists, NULL will appear in columns from Employee for those records that have no match in Location.
This is what the SQL looks like:

``````select * from employee right outer join location  on employee.empID = location.empID;
//Use of outer keyword is optional
``````

Using the tables above, we can show what the result set of a right outer join would look like:

Full Outer Joins:-
Full Outer Join or Full Join is to retain the nonmatching information by including nonmatching rows in the results of a join, use a full outer join. It includes all rows from both tables, regardless of whether or not the other table has a matching value.

Image Source

MySQL 8.0 Reference Manual – Join Syntax

Oracle Join operations

## Extract file from docker image?

You can extract files from an image with the following commands: docker create \$image # returns container ID docker cp \$container_id:\$source_path \$destination_path docker rm \$container_id According to the docker create documentation, this doesn't run the...

## Transfer files using scp: permission denied

Your commands are trying to put the new Document to the root (/) of your machine. What you want to do is to transfer them to your home directory (since you have no permissions to write to /). If path to your home is something like /home/erez try the following:...

## What’s the purpose of DH Parameters?

What exactly is the purpose of these DH Parameters? These parameters define how OpenSSL performs the Diffie-Hellman (DH) key-exchange. As you stated correctly they include a field prime p and a generator g. The purpose of the availability to customize these...

## How to rsync multiple source folders

You can pass multiple source arguments. rsync -a /etc/fstab /home/user/download bkp This creates bkp/fstab and bkp/download, like the separate commands you gave. It may be desirable to preserve the source structure instead. To do this, use / as the source and...

## Benefits of Structured Logging vs basic logging

There are two fundamental advances with the structured approach that can't be emulated using text logs without (sometimes extreme levels of) additional effort. Event Types When you write two events with log4net like: log.Debug("Disk quota {0} exceeded by user...

## Interfaces vs Types in TypeScript

2019 Update The current answers and the official documentation are outdated. And for those new to TypeScript, the terminology used isn't clear without examples. Below is a list of up-to-date differences. 1. Objects / Functions Both can be used to describe the...

## Get total as you type with added column (append) using jQuery

One issue if that the newly-added column id's are missing the id number. If you look at the id, it only shows "price-", when it should probably be "price-2-1", since the original ones are "price-1", and the original ones should probably be something like...

## Determining if a file is a hard link or symbolic link?

Jim's answer explains how to test for a symlink: by using test's -L test. But testing for a "hard link" is, well, strictly speaking not what you want. Hard links work because of how Unix handles files: each file is represented by a single inode. Then a single...

## How to restrict a Google search to results of a specific language?

You can do that using the advanced search options: http://www.googleguide.com/sharpening_queries.html I also found this, which might work for you: http://www.searchenginejournal.com/how-to-see-google-search-results-for-other-locations/25203/ Just wanted to add...

## Random map generation

Among the many other related questions on the site, there's an often linked article for map generation: Polygonal Map Generation for Games you can glean some good strategies from that article, but it can't really be used as is. While not a tutorial, there's an...

## Difference in sites-available vs sites-enabled vs conf.d directories (Nginx)?

The sites-* folders are managed by nginx_ensite and nginx_dissite. For Apache httpd users who find this with a search, the equivalents is a2ensite/a2dissite. The sites-available folder is for storing all of your vhost configurations, whether or not they're...

## How to prettyprint a JSON file?

The json module already implements some basic pretty printing in the dump and dumps functions, with the indent parameter that specifies how many spaces to indent by: >>> import json >>> >>> your_json = '["foo", {"bar":["baz", null,...

## How can I avoid the battery charging when connected via USB?

I have an Android 4.0.3 phone without root access so can't test any of this but let me point you to /sys/class/power_supply/battery/ which gives some info/control over charging issues. In particular there is charging_enabled which gives the current state (0 not...

## How to transform given dataset in python? [closed]

From your expected result, it appears that each "group" is based on contiguous id values. For this, you can use the compare-cumsum-groupby pattern, and then use agg to get the min and max values. # Sample data. df = pd.DataFrame( {'id': [1, 2, 2, 2, 2, 2, 1, 1,...

## Output of the following C++ Program [closed]

It works exactly like this non-recursive translation: int func_0() { return 2; } int func_1() { return 3; } int func_2() { return func_1() + func_0(); } // Returns 3 + 2 = 5 int func_3() { return func_2() + func_1(); } // Returns 5 + 3 = 8 int func_4() { return...

## Making a circle out of . (periods) [closed]

Here's the maths and even an example program in C: http://pixwiki.bafsoft.com/mags/5/articles/circle/sincos.htm (link no longer exists). And position: absolute, left and top will let you draw: http://www.w3.org/TR/CSS2/visuren.html#choose-position Any further...

## Should I use a code converter (Python to C++)?

Generally it's an awful way to write code, and does not guarantee that it will be any faster. Things which are simple and fast in one language can be complex and slow in another. You're better off either learning how to write fast Python code or learning C++...

## tkinter: cannot concatenate ‘str’ and ‘float’ objects

This one line is more than enough to cause the problem: text="რეგულარი >> "+2.23+ 'GEL' 2.23 is a floating-point value; 'GEL' is a string. What does it mean to add an arithmetic value and a string of letters? If you want the string label 'რეგულარი...

## Java regex for removing all single letters except “a” and “i” from string [closed]

Code See regex in use here (?:^| )[b-hj-z](?= |\$) Usage See code in use here import java.util.regex.Matcher; import java.util.regex.Pattern; class Ideone { public static void main (String[] args) throws java.lang.Exception { final String regex = "(?:^|...

## How to make a file (e.g. a .sh script) executable, so it can be run from a terminal

You can mark the file as executable: chmod +x filename.sh You can then execute it like this: ./filename.sh If you want to use a different command to start it, you can add an alias: gedit ~/.bashrc Add this at the end of the file: alias <new...