Understanding SQL Joins: INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN
When working with relational databases, JOIN
operations allow you to retrieve data from multiple tables based on a common column.
SQL Server supports different types of joins, each serving a specific purpose. Let’s break them down with examples.
1. INNER JOIN
The INNER JOIN
returns only the rows where there is a match in both tables.
SELECT A.id, A.name, B.order_id
FROM Customers A
INNER JOIN Orders B ON A.id = B.customer_id;
- If a customer has no matching order, they won’t appear in the result.
2. LEFT JOIN (or LEFT OUTER JOIN)
The LEFT JOIN
returns all rows from the left table (Customers
), and only matching rows from the right table (Orders
). If there’s no match, NULL values are returned for the right table columns.
SELECT A.id, A.name, B.order_id
FROM Customers A
LEFT JOIN Orders B ON A.id = B.customer_id;
- Customers without orders will still appear, but
order_id
will be NULL.
3. RIGHT JOIN (or RIGHT OUTER JOIN)
The RIGHT JOIN
works the opposite of LEFT JOIN
, returning all rows from the right table (Orders
) and only matching rows from the left table (Customers
).
SELECT A.id, A.name, B.order_id
FROM Customers A
RIGHT JOIN Orders B ON A.id = B.customer_id;
- Orders without a matching customer will still appear, but
name
will be NULL.
4. FULL JOIN (or FULL OUTER JOIN)
The FULL JOIN
returns all records from both tables. If there’s no match, NULL values will be shown in the missing columns.
SELECT A.id, A.name, B.order_id
FROM Customers A
FULL JOIN Orders B ON A.id = B.customer_id;
- This ensures that all customers and all orders appear in the results, even if there’s no match.
Quick Summary:
Join Type |
Includes Matching Rows |
Includes Non-Matching Rows (Left Table) |
Includes Non-Matching Rows (Right Table) |
INNER JOIN |
✅ |
❌ |
❌ |
LEFT JOIN |
✅ |
✅ |
❌ |
RIGHT JOIN |
✅ |
❌ |
✅ |
FULL JOIN |
✅ |
✅ |
✅ |
Understanding these joins can help you extract data efficiently and ensure that your queries return the expected results. Happy querying!