20
loading...
This website collects cookies to deliver better user experience
JOIN
s can be very confusing. In this quick post we are going to learn what the difference between JOIN
and INNER JOIN
is!INNER JOIN
AND JOIN
are functionally equivalent. INNER JOIN == JOIN
INNER JOIN
is the default if you don't specify the type when you use the word JOIN.INNER JOIN
can be a bit clearer to read. Especially in cases that you have a query containing other join types.INNER
as the join type.INNER JOIN
is. INNER
join is used to join two tables. However, unlike the CROSS
join, by convention, it is based on a condition. By using an INNER
join, you can match the first table to the second one.id
column and a foreign key for the user_id
; that way, we can 'link' or relate the users table to the posts table. However, this is beyond the scope of this SQL basics eBook, though I might extend it in the future and add more chapters.SELECT *
FROM users
INNER JOIN posts
ON users.id = posts.user_id;
SELECT * FROM users
: This is a standard select we've covered many times in the previous chapters.INNER JOIN posts
: Then, we specify the second table and which table we want to join the result set.ON users.id = posts.user_id
: Finally, we specify how we want the data in these two tables to be merged. The user.id
is the id
column of the user
table, which is also the primary ID, and posts.user_id
is the foreign key in the email address table referring to the ID column in the users table.user_id
column:+----+----------+----+---------+-----------------+
| id | username | id | user_id | title |
+----+----------+----+---------+-----------------+
| 1 | bobby | 1 | 1 | Hello World! |
| 2 | devdojo | 2 | 2 | Getting started |
| 3 | tony | 3 | 3 | SQL is awesome |
| 2 | devdojo | 4 | 2 | MySQL is up! |
| 1 | bobby | 5 | 1 | SQL |
+----+----------+----+---------+-----------------+
SELECT *
FROM users
JOIN posts
ON users.id = posts.user_id;
INNER JOIN
and ON
clauses.NULL
values are discarded. For example, if you have a user who does not have a post associated with it, the user with NULL posts will not be displayed when running the above INNER
join query.