Published on

January 8, 2020

Understanding INNER JOIN and LEFT JOIN in SQL Server

When working with SQL Server, you may come across situations where you need to combine data from multiple tables. Two common ways to achieve this are through INNER JOIN and LEFT JOIN. In this article, we will explore these join types and understand their differences.

INNER JOIN

Let’s start by discussing INNER JOIN. This join type allows us to retrieve only the records that have a matching pair in both tables. Here’s an example:

SELECT *
FROM country
INNER JOIN city ON city.country_id = country.id;

The result of this query will include all pairs of countries and cities that are related via a foreign key. If there are no matching pairs, those records will not be included in the result.

It’s worth noting that you can achieve the same result by listing the tables in the FROM part of the query and specifying the join condition in the WHERE part. However, using INNER JOIN provides better readability and makes it easier to identify if the join condition is omitted.

LEFT JOIN

Now let’s move on to LEFT JOIN. This join type allows us to retrieve all records from the “left” table, regardless of whether they have a matching pair in the “right” table. Here’s an example:

SELECT *
FROM country
LEFT JOIN city ON city.country_id = country.id;

The result of this query will include all records from the “left” table (country), even if there is no matching pair in the “right” table (city). In such cases, the attributes from the “right” table will have NULL values.

It’s important to note that RIGHT JOIN is rarely used because it returns the same result as LEFT JOIN. However, queries using LEFT JOIN are generally easier to read and understand.

Conclusion

In summary, the choice between INNER JOIN and LEFT JOIN depends on your specific requirements. Use INNER JOIN when you only want to retrieve records with matching pairs, and use LEFT JOIN when you need all records from the “left” table, regardless of whether they have a pair in the “right” table.

Understanding these join types is essential for writing effective SQL queries and retrieving the desired results from your database.

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.