SQL Server: Inner Join Example

In this tutorial you will see what is an inner join in SQL Server and how to use it with some examples.

Contents for SQL Server: Inner Join Example

Use

The inner join is surely one of the most common join that you will encounter in your programming journey.

With its power, you can retrieve records that have matching values from two or more tables

Suppose you have two tables: A and B.

You will get all the records in relation with both tables.

Structure

The structure of an inner join is quite simple

FROM A INNER JOIN B [ON (join_condition)]

You will join A and B based on the join_condition you specify.

Example

Let’s use once again the following database structure:

 

What’s the relationship between the two tables?

Right, RobotFactoryId.

That is your join condition (remember to use aliases):

SELECT *
FROM RobotDog d
JOIN RobotFactory f ON d.RobotFactoryId = f.RobotFactoryId

 

This query only returns values from the RobotDog table, so you will see only the factory id, not its name.

But now, using the join strength, it will not be a problem:

SELECT d.Name AS DogName, d.Armed, d.Guns, f.Name AS FactoryName
FROM RobotDog d
JOIN RobotFactory f ON d.RobotFactoryId = f.RobotFactoryId

The use of d. and f. is mandatory, as the Name column is the same in both tables.

Conclusion

As you have seen, using an inner join is pretty straightforward.

But it will be incredibly useful in your work.

Doubts? Feel free to leave a comment!