Back to all questions

How does INNER JOIN work?

Devs Hive

Devs Hive

Seen on interview: 0 users

INNER JOIN is a type of JOIN that returns only the rows that have a match in both tables. In other words, if a value in one table has no corresponding value in the other table, that row will not appear in the result.

Let's walk through an example

We have two tables: users and subscriptions. Our goal is to get only the users who have a subscription. To do this, we will use INNER JOIN.

-- users
id | name
------------
1 | Alice
2 | Bob
3 | John

-- subscriptions
id | user_id | plan_name
-------------------------
1 | 1 | Basic
2 | 2 | Premium

The query looks like this. Let's break it down in more detail:

-- Вибираємо стовпці, які хочемо бачити в результаті:
-- name - з таблиці users
-- plan_name - з таблиці subscriptions
SELECT
users.name,
subscriptions.plan_name
FROM
users

-- Робимо INNER JOIN таблиці subscriptions
-- по полю users.id та subscriptions.user_id
INNER JOIN
subscriptions
ON
users.id = subscriptions.user_id;

After running the query, we get the following result:

name | plan_name
-------------------------
Alice | Basic
Bob | Premium

Important to remember

INNER JOIN returns only the records that have збіг в обох таблицях. If there is no match, the row is excluded from the result.

Seen on interview?

Related Questions

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!