1. Home
SQL

SQL Tutorial: Learn Structured Query Language Basics

Learn all SQL tutorial concepts in detail and master your career today.

  • 59
  • 9 Hours
right-top-arrow

Tutorial Playlist

81 Lessons
49

Inner Join in SQL

Updated on 19/07/2024456 Views

Introduction

In the world of databases, SQL (Structured Query Language) is a powerful tool for managing and manipulating data. Joining data from multiple tables is one of SQL's most important features. Among the different types of joins, the SQL inner join is widely used for retrieving data that exists in both tables. This article will explore SQL's inner join concept, syntax, real-world examples, common errors, and performance considerations before wrapping up with some frequently asked questions. 

Overview

When two tables are joined, records with matching values are retrieved using an SQL inner join. Based on a shared column between two or more tables, it merges rows from those tables. If there is no match found between the tables, the rows are not included in the result set.

Understanding SQL Inner Join

Database management and manipulation are carried out using SQL (Structured Query Language). Combining data from various tables into a single, cohesive dataset is one of its most potent features. This is where the idea of "joins" is useful.

"Inner Join" is one of the most common types of joins in SQL. SQL inner join returns rows from both tables where there is a match based on a specific condition, often the equality between two or more columns.

An inner join in a SQL query is achieved by using the INNER JOIN or JOIN clause in the SELECT statement. 

Key Components:

  • Joining Condition: This is the condition based on which the tables are joined. It is usually equality between certain columns in the involved tables.
  • Joined Table: This is the result of the inner join operation. It contains all the columns from both tables for rows where the joining condition is true.

Syntax of SQL Inner Join

The basic syntax for performing an inner join in SQL is as follows:

SELECT column_name(s)

FROM table1

INNER JOIN table2 ON table1.column_name = table2.column_name;

In this syntax:

  • SELECT column_name(s) specifies the columns to be retrieved from the tables.
  • The names of the tables that are being joined are table1 and table2.
  • ON table1.column_name = table2.column_name specifies the condition for the join based on the related column.

Practical Examples

Practical examples are explained below with examples:

Example 1: Simple Inner Join

Let us look at an example where we have two tables: Departments and Employees. The Employees table contains employee data, including an EmployeeID for each employee and a DepartmentID indicating the department they belong to. The Department table contains department data, including a DepartmentID for each department and a DepartmentName.

Here is an example of what these tables might look like:

Employees Table:

EmployeeID

FirstName

LastName

DepartmentID

1

John

Doe

1

2

Jane

Smith

2

3

Tom

Johnson

1

4

Mary

Lee

3

Departments Table:

DepartmentID

DepartmentName

1

Sales

2

Marketing

3

HR

Let's say you want to create a report that includes the employee's first name, last name, and the name of the department they belong to. This is a perfect situation for an inner join.

The SQL might look something like this:

SELECT Employees.FirstName, Employees.LastName, Departments.DepartmentName

FROM Employees

INNER JOIN Departments

ON Employees.DepartmentID = Departments.DepartmentID;

Output:

This will return a table that includes the First Name, Last Name, and Department Name for every employee where there is a matching DepartmentID in both the Employees and Departments tables. The output would look like this:

FirstName

LastName

DepartmentName

John

Doe

Sales

Jane

Smith

Marketing

Tom

Johnson

Sales

Mary

Lee

HR

Example 2: Joining Multiple Tables

Let's consider a scenario where we have three tables: Students, Courses, and Enrollments.

  • The Students table contains student data, including a StudentID for each student. 
  • The Courses table contains course data, including a CourseID for each course. 
  • The Enrollments table stores the relationship between Students and Courses, i.e., which student is enrolled in which course.

Here is an example of what these tables might look like:

Students Table:

StudentID

FirstName

LastName

1

John

Doe

2

Jane

Smith

3

Tom

Johnson

Courses Table:

CourseID

CourseName

1

Math

2

Science

3

English

Enrollments Table:

StudentID

CourseID

1

1

1

2

2

3

3

1

3

3

Let's say you want to create a report that shows which courses each student is enrolled in. This scenario requires joining multiple tables.

The query for an inner join in SQL with a WHERE clause might look something like this:

SELECT Students.FirstName, Students.LastName, Courses.CourseName

FROM ((Enrollments

INNER JOIN Students ON Enrollments.StudentID = Students.StudentID)

INNER JOIN Courses ON Enrollments.CourseID = Courses.CourseID);

Output:

This will return a table that includes the First Name, Last Name, and Course Name for every enrollment where there is a matching StudentID in the Enrollments and Students tables and a matching CourseID in the Enrollments and Courses tables. The output would look like this:

FirstName

LastName

CourseName

John

Doe

Math

John

Doe

Science

Jane

Smith

English

Tom

Johnson

Math

Tom

Johnson

English

Example 3: Using Table Alias with Inner Join

Table aliases can be particularly useful when dealing with complex queries involving multiple tables, as they provide shorthand notation for referencing table names.

By using aliases, developers can write more concise and readable SQL code, improving the overall maintainability of the queries. 

When working with multiple tables in a single SQL query, particularly with JOIN operations, it is essential to qualify column names with table aliases. This is important for a couple of reasons:

  • Avoiding Ambiguity: If the same column name is present in more than one table involved in the query, qualifying the column name with a table alias avoids confusion about which table's column the query should reference.
  • Enhancing Readability: Even if there's no ambiguity, fully qualifying column names with table aliases makes the query easier to understand, as it is clear which columns are coming from which tables.

Let’s use the above Employees table and Departments table, alias them, and use them in query.

The query for an inner join in SQL with aliases might look something like this:

SELECT E.FirstName, E.LastName, D.DepartmentName

FROM Employees AS E

INNER JOIN Departments AS D

ON E.DepartmentID = D.DepartmentID;

Output:

This will return a table that includes the First Name, Last Name, and Department Name for every employee where there is a matching DepartmentID in both the Employees and Departments tables. The output would look like this:

FirstName

LastName

DepartmentName

John

Doe

Sales

Jane

Smith

Marketing

Tom

Johnson

Sales

Mary

Lee

HR

Common Mistakes

Common mistakes are explained below:

  • Misaligned Join Conditions: The most common mistake is not correctly matching the columns in the join condition. This can cause incorrect results or, in some cases, an error in the SQL statement.
  • Ignoring Data Types: Another common error occurs when trying to join columns of different data types. SQL will often throw an error or produce unexpected results if you try to join a numeric column with a text column.
  • Overlooking NULL Values: If the columns being joined contain NULL values, these rows will be excluded from an inner join. This can result in missing data if not taken into account.
  • Confusing Inner Join with Other Types of Joins: Inner Join only returns the rows where there is a match in both tables. If you want all the rows from one table and the matching rows from another table (or all rows from both tables), you should use left join, right join, or full join respectively. Using inner join in these scenarios may lead to data loss.

Performance Considerations

While inner joins are a powerful tool, they can potentially be resource-intensive and slow down query performance, especially when dealing with large amounts of data. 

  • Data Volume: The more data you have, the longer it will take to execute the join. Try to filter your data as early as possible in your SQL statement. Use a WHERE clause to reduce the number of rows that need to be joined.
  • Joining Multiple Tables: Try to keep the number of tables being joined to a minimum. The more tables you join, the more complex the query, which can impact performance.
  • Column Types: Joining on a column of type integer is faster than joining on a column of type string. If possible, use integer columns for your join conditions.
  • Use of Subqueries: While subqueries can be useful, they can also significantly slow down a query if not used properly. Whenever possible, try to use a join instead of a subquery.
  • Normalization: A well-normalized database can reduce the redundancy and improve the overall performance of the join operation.

Final Thoughts

To sum up, an essential idea in SQL for merging data from several tables based on matching values is the SQL inner join. Database administrators and developers can use inner joins to efficiently retrieve desired data from relational databases by knowing their syntax, practical applications, common errors, and performance considerations. 

FAQs

How many types of inner joins are there in SQL?

Technically, there is only one type of inner join in SQL, but it can be applied in many different ways, such as joining two tables, multiple tables, or using aliases.

What is an inner join with syntax?

The syntax for an inner join in a SQL example is SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;

Why is it called an inner join?

It is called an "inner" join because it only returns the set of records that match in both Table A and Table B, effectively the "intersection" of the two tables.

What is the difference between a join and an inner join?The term "join" in SQL often refers to an "inner join" by default, but can also be used more broadly to refer to any type of join, including outer joins (left, right, or full) and cross joins. When the type of join is not specified, it is typically an inner join.

Abhimita Debnath

Abhimita Debnath

Abhimita Debnath is one of the students in UpGrad Big Data Engineering program with BITS Pilani. She's a Senior Software Engineer in Infosys. She…Read More

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...