What is the difference between "INNER JOIN" and "OUTER JOIN"?

In SQL, both INNER JOIN and OUTER JOIN are used to combine data from multiple tables based on a related column, but they have different behaviors in terms of the records they include in the result set.

INNER JOIN: An INNER JOIN returns only the rows where there is a match in both tables being joined. It filters out rows from both tables that do not have matching values in the specified column(s).

Here's an example:

Suppose you have two tables, customers and orders, with the following data:

customers table:

customer_id | customer_name
1           | Alice
2           | Bob
3           | Carol

orders table:

order_id | customer_id | order_amount
1        | 1           | 100
2        | 2           | 150
3        | 1           | 200

If you perform an INNER JOIN on the customer_id column:

sql

SELECT customers.customer_name, orders.order_amount
FROM customers
INNER JOIN orders ON customers.customer_id = orders.customer_id;

The result will be:

customer_name | order_amount
Alice         | 100
Alice         | 200
Bob           | 150

Only the rows where there's a match between customers.customer_id and orders.customer_id are included in the result set.

OUTER JOIN: An OUTER JOIN returns all the rows from one table and the matching rows from the other table. If there's no match, the missing values are filled with NULLs.

There are three types of OUTER JOIN:

    LEFT OUTER JOIN returns all rows from the left table and matching rows from the right table.
    RIGHT OUTER JOIN returns all rows from the right table and matching rows from the left table.
    FULL OUTER JOIN returns all rows from both tables.

Here's an example using LEFT OUTER JOIN:

sql

SELECT customers.customer_name, orders.order_amount
FROM customers
LEFT OUTER JOIN orders ON customers.customer_id = orders.customer_id;

The result will be:

arduino

customer_name | order_amount
Alice         | 100
Alice         | 200
Bob           | 150
Carol         | NULL

In this result, all customers are included, and for the customer "Carol" who doesn't have any orders, the order_amount is filled with NULL.

In summary, the main difference between INNER JOIN and OUTER JOIN is that INNER JOIN returns only matching rows, while OUTER JOIN returns all rows from at least one table and includes NULL values for non-matching rows.

Comments