Sobes.tech
Junior — Middle

What are the differences between INNER JOIN and RIGHT JOIN operations when joining tables in SQL?

sobes.tech AI

Answer from AI

INNER JOIN and RIGHT JOIN are table join operations in SQL, which differ in the way they select rows:

  • INNER JOIN returns only those rows that have matches in both tables based on the join condition.

  • RIGHT JOIN returns all rows from the right table and the matching rows from the left table. If there are no matches, the fields from the left table will be filled with NULL.

Example:

-- Table A
id | name
---|------
1  | Alice
2  | Bob

-- Table B
id | city
---|-------
2  | NY
3  | LA

-- INNER JOIN
SELECT A.name, B.city FROM A INNER JOIN B ON A.id = B.id;
-- Result:
-- Bob | NY

-- RIGHT JOIN
SELECT A.name, B.city FROM A RIGHT JOIN B ON A.id = B.id;
-- Result:
-- Bob | NY
-- NULL | LA

Thus, INNER JOIN filters only matching records, while RIGHT JOIN retains all records from the right table, supplementing them with data from the left if available.