mySQL: INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN

As mentioned earlier, I’ve been brushing up on my JOIN terminology using data in my mySQL databases. The results here probably apply to other SQL DBMSs as well.

Differences

These three joins result in almost the same rows with minor—crucial—differences. The INNER JOIN returns all of the rows in the first table that have a match in the second table. The order in which the tables is specified doesn’t matter. If there is a row in either table that doesn’t have a match (specified by the join condition) it doesn’t appear in the join.

The LEFT OUTER JOIN returns all of the rows in the first table regardless of whether there is a matching the second table. If there is no match in the second table, the values for those fields are NULL. The RIGHT OUTER JOIN returns all of the rows in the second table regardless of whether there is a matching the first table. If there is no match in the first table, the values for those fields are NULL. As you can see by the specification, the order in which the tables are specified for the outer joins matters.

Examples

In my database the `apps` table has 30 rows. The `category` table has 10 rows. Two of the apps do not have a category assigned to them. Two of the categories have no apps associated with them.

In my database, this code returns 28 rows—the two apps with no assigned category do not appear.


SELECT apps.name, app_category.name 
FROM apps
INNER JOIN app_category 
ON category_id = app_category.id

This code returns 30 rows—the two apps with no assigned category appear in the result and the result and the app_category.name is NULL.


SELECT apps.name, app_category.name 
FROM apps
LEFT OUTER JOIN app_category 
ON category_id = app_category.id

This is a bit more complicated. This code returns 30 rows—the two apps with no assigned category do not appear in the result. The two categories that have no matching apps have an app.name of NULL.


SELECT apps.name, app_category.name 
FROM apps
RIGHT OUTER JOIN app_category 
ON category_id = app_category.id

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.