mysql-inner-join 

“`html

In MySQL, the INNER JOIN stands as one of the most commonly employed joins to extract data from various tables based on a defined joining criterion. This kind of JOIN holds significance for relational databases because it enables data to be accessed effectively when integrating pertinent information from different tables. It aids in preserving data consistency by confirming that only corresponding records from both tables are retrieved. Additionally, INNER JOINs play a crucial role in enhancing query efficiency in normalized database architectures, where data is distributed across multiple interconnected tables. In this article, we will delve into the INNER JOIN in MySQL comprehensively, accompanied by examples.

Table of Contents:

Before we proceed with the INNER JOIN, let’s set up some tables for enhanced understanding.

Next, let’s create a Student table.

CREATE TABLE Students (

    student_id INT PRIMARY KEY,

    student_name VARCHAR(100),

    email VARCHAR(100)

);

INSERT INTO Students (student_id, student_name, email) VALUES

(1, 'John', '[email protected]'),

(2, 'Smith', '[email protected]'),

(3, 'Johnson', '[email protected]'),

(4, 'Wilson', '[email protected]');

SELECT * FROM Students;

This is what the Students table looks like after inserting records.

Now, let’s create a Course table and insert some records into it

CREATE TABLE Courses (

    course_id INT PRIMARY KEY,

    course_name VARCHAR(100),

    instructor VARCHAR(100)

);

INSERT INTO Courses (course_id, course_name, instructor) VALUES

(101, 'SQL for Beginners', 'Michael Brown'),

(102, 'Advanced MySQL', 'Sarah Johnson'),

(103, 'Data Science with Python', 'Emily Davis'),

(104, 'Big Data Analytics', 'James Miller');

SELECT * from Courses;
create-table

This is how the Courses table appears once created and populated with data.

Finally, let’s establish an enrollment table

CREATE TABLE Enrollments (

enrollment_id INT PRIMARY KEY,

    student_id INT,

    course_id INT,

    enrollment_date DATE,

    FOREIGN KEY (student_id) REFERENCES Students(student_id),

    FOREIGN KEY (course_id) REFERENCES Courses(course_id)

);

INSERT INTO Enrollments (enrollment_id, student_id, course_id, enrollment_date) VALUES

(1, 1, 101, '2024-01-15'),

(2, 1, 102, '2024-02-10'),

(3, 2, 103, '2024-02-20'),

(4, 3, 101, '2024-03-05'),

(5, 3, 104, '2024-03-10'),

(6, 4, 102, '2024-03-15');

SELECT * from Enrollments;
create-table

This is the appearance of the Enrollments table after creation and data insertion.

What is an INNER JOIN in MySQL?

INNER JOIN is a category of SQL join that extracts records from two or more tables that possess a corresponding value in the defined columns. It fetches exclusively those records where the combined records satisfy the defined join condition.

Syntax:

SELECT column_name(s)

FROM table1

INNER JOIN table2

ON table1.common_column = table2.common_column;



Parameters:
  • Table 1 and Table 2: The two tables that require joining.
  • Common_column: Utilized to match the two tables

Example 1:

— Using an INNER JOIN between the Student and Enrollment Tables

SELECT s.student_id, s.student_name, e.course_id

FROM Students s

INNER JOIN Enrollments e ON s.student_id = e.student_id;

Output:

inner-join

Explanation: In this case, the INNER JOIN connects student_id from the Students table with student_id from the Enrollments table. Students not registered in any course will not be included in the result set.

Example 2:

SELECT c.course_id, c.course_name, c.instructor, e.enrollment_id, e.student_id, e.enrollment_date

FROM Courses c

INNER JOIN Enrollments e ON c.course_id = e.course_id;

Output:

inner-join-course-id

Explanation: This INNER JOIN links the Courses and Enrollments tables based on course_id, retrieving details about courses that have enrollments.

Why Do We Need an INNER JOIN in MySQL?

Retrieve Related Data:

  • Data is organized in separate tables in relational databases to enhance storage efficiency and organization.
  • “““html

  • Illustration: We can utilize INNER JOIN to combine associated records – students and their enrollment details, as well as clients and their order information.

Prevent Redundant Data:

  • We can structure the data into multiple tables rather than maintaining it within a single table.
  • INNER JOIN fetches the necessary data dynamically, conserving storage and avoiding any data duplication.

Data Filtering:

  • INNER JOIN ensures that only records from both tables that correspond will be returned.
  • In contrast to LEFT JOIN or RIGHT JOIN, an INNER JOIN will eliminate any rows from both tables that lack a match.

Enhances Query Efficiency:

  • This ultimately reduces data processing since less data is utilized due to the exclusion of non-matching records.
  • INNER JOIN queries can be refined using an index, which contributes to better performance.

How to Execute an INNER JOIN with Multiple Tables in MySQL?

INNER JOIN is adept at consolidating data from several tables by linking shared columns. The data obtained through INNER JOIN includes only those rows with corresponding values across all the linked tables.

Syntax:

SELECT column_name(s)

FROM table1

INNER JOIN table2 ON table1.common_column = table2.common_column

INNER JOIN table3 ON table2.common_column = table3.common_column;

Illustration:

-- Query to obtain the student name from the Students table, the course name from the Course table, and the date from the enrollment table

SELECT s.student_name, c.course_name, e.enrollment_date

FROM Students s

INNER JOIN Enrollments e ON s.student_id = e.student_id

INNER JOIN Courses c ON e.course_id = c.course_id;

Outcome:

inner-join-with-multiple-tables

Clarification: Here, the Students table connects with the Enrollments table using student_id, and the Enrollments table further connects with the Courses table based on course_id. Only corresponding records for student names, enrolled courses, and enrollment dates are returned as a result of the join.

How to Execute an INNER JOIN with a WHERE Clause in MySQL?

By employing an INNER JOIN alongside the WHERE clause, only pertinent information is retrieved by filtering the joined records based on specific criteria.

Syntax:

SELECT column_name(s)

FROM table1

INNER JOIN table2 ON table1.common_column = table2.common_column

WHERE condition;

Illustration:

-- To obtain the students who have enrolled after ‘2024-03-01’

SELECT s.student_name, c.course_name, e.enrollment_date

FROM Students s

INNER JOIN Enrollments e ON s.student_id = e.student_id

INNER JOIN Courses c ON e.course_id = c.course_id

WHERE e.enrollment_date > '2024-03-01';

Outcome:

inner-join-with-where-clause

Clarification: In this scenario, the INNER JOIN extracts all matching records from three tables. The WHERE Clause filters the students enrolled after 2024-03-01.

How to Execute an INNER JOIN with an ORDER BY Clause in MySQL?

With the use of the ORDER BY clause and an INNER JOIN, the retrieved records are arranged according to the specified column, either in ascending (ASC) or descending (DESC) order.

Syntax:

SELECT column_name(s)

FROM table1

INNER JOIN table2 ON table1.common_column = table2.common_column

ORDER BY column_name [ASC|DESC];

Illustration:

-- To get course enrollment details sorted by enrollment date.

SELECT s.student_name, c.course_name, e.enrollment_date

FROM Students s

INNER JOIN Enrollments e ON s.student_id = e.student_id

INNER JOIN Courses c ON e.course_id = c.course_id

ORDER BY e.enrollment_date DESC;

Outcome:

inner-join-with-order-by-clause

Clarification: Here, the ORDER BY organizes the records by enrollment_date in descending (DESC) order to showcase the latest enrollments first. The INNER JOIN fetches matching records from all three tables.

Distinction Between INNER JOIN with WHERE and INNER JOIN with ORDER BY

INNER JOIN with WHERE INNER JOIN with ORDER BY
It filters records based on specific conditions. It organizes the result set in either ascending or descending order.
Only filters rows if the condition is fulfilled. Displays all matching rows, but in a designated order.
The WHERE Clause is applied prior to the final results. The ORDER BY Clause is applied following the result retrieval.
By minimizing the number of processed rows, we can enhance performance. May reduce performance on large datasets.

Difference Between INNER JOIN and Other JOINS

“““html

Feature INNER JOIN LEFT JOIN RIGHT JOIN FULL JOIN
Definition Returns records from both tables that correspond. LEFT JOIN returns every record from the left table along with any that match from the right table. RIGHT JOIN retrieves every record from the right table, alongside the corresponding records from the left table. FULL JOIN obtains every record from both tables while substituting NULL for unmatched values.
Matching Criteria Only includes rows existing in both tables. Includes all rows present in the left table, even NULL values.
Where no rows are present in the right table. Includes all rows found in the right table, comprising NULL where there are no rows available in the left table. Encompasses all rows from both tables; NULL where a match is absent.
Unmatched Data Only records that match are included Records from the left table that do not match are included. Records from the right table that do not match are included. Records from both tables that do not match are included.
Use Case Shows only the students who have signed up for a course Shows all the students who have not signed up for a course Displays all the courses, including those with no enrolled students Displays all the students alongside all the courses

Frequent Errors in INNER JOIN and How to Avoid Them?

1. Omitting the ON Condition

Error: Omitting the ON condition

SELECT s.student_name, c.course_name 

FROM Students s

INNER JOIN Enrollments e

INNER JOIN Courses c;

Correction: Always incorporate the ON condition in JOINS to avert the Cartesian product

SELECT s.student_name, c.course_name 

FROM Students s

INNER JOIN Enrollments e ON s.student_id = e.student_id

INNER JOIN Courses c ON e.course_id = c.course_id;



2. Employing WHERE Instead of ON Condition

Error: Using WHERE instead of ON to link tables

SELECT s.student_name, c.course_name 

FROM Students s, Enrollments e, Courses c

WHERE s.student_id = e.student_id

AND e.course_id = c.course_id;

SELECT s.student_name, c.course_name

FROM Students s

INNER JOIN Enrollments e ON s.student_id = e.student_id

INNER JOIN Courses c ON e.course_id = c.course_id;

Correction: Always utilize the ON condition for table joins and the WHERE Clause for record filtering

SELECT s.student_name, c.course_name  
FROM Students s  
INNER JOIN Enrollments e ON s.student_id = e.student_id  
INNER JOIN Courses c ON e.course_id = c.course_id;

3. Neglecting to use aliases with multiple tables

Error: Omitting the alias when handling multiple tables leads to ambiguity

SELECT student_name, course_name 

FROM Students

INNER JOIN Enrollments ON Students.student_id = Enrollments.student_id

INNER JOIN Courses ON Enrollments.course_id = Courses.course_id;

Correction: Utilize alias names

SELECT s.student_name, c.course_name 

FROM Students s

INNER JOIN Enrollments e ON s.student_id = e.student_id

INNER JOIN Courses c ON e.course_id = c.course_id;

4. Improperly managing duplicate records

Error: Retrieving student names may result in duplicates if a student is registered in multiple courses.

SELECT s.student_name 

FROM Students s

INNER JOIN Enrollments e ON s.student_id = e.student_id;

Correction: Utilize the DISTINCT keyword to eliminate duplicates

SELECT DISTINCT s.student_name 

FROM Students s

INNER JOIN Enrollments e ON s.student_id = e.student_id;

Practical Examples

1. HR System: Imagine an HR department wanting to display all employees along with their department names.

Example:

CREATE TABLE Employees (

    employee_id INT PRIMARY KEY,

    employee_name VARCHAR(50),

    department_id INT

);

CREATE TABLE Departments (

    department_id INT PRIMARY KEY,

    department_name VARCHAR(50)

);

INSERT INTO Employees VALUES (1, 'Rohit', 101), (2, 'Vinoth', 102), (3, 'Babu', 101);

INSERT INTO Departments VALUES (101, 'HR'), (102, 'IT'), (103, 'Finance');

SELECT e.employee_name, d.department_name

FROM Employees e

INNER JOIN Departments d ON e.department_id = d.department_id;

Output:

HR-system

Explanation: In this case, the INNER JOIN retrieves only employees associated with departments. The Finance department is excluded as there are no employees linked to it.

Recommended Practices

  • Employ WHERE to Filter, Not HAVING, Unless Handling Aggregates: Use the WHERE clause for filtering unanalyzed data, and reserve HAVING for post-aggregate filtering.
  • Emphasize Explicit INNER JOIN Syntax: It’s beneficial to employ the INNER JOIN command as opposed to the WHERE clause to enhance readability and maintainability.
  • Verify Adequate Indexing: For optimal query performance, index the columns in the ON clause (particularly for foreign keys) to enhance execution speed.
  • Utilize Table Aliases: Use concise and suitable aliases for tables to simplify queries and boost readability.
  • Avoid Creating a Cartesian Product: Ensure that conditions are present in the ON or WHERE clause to prevent unintentional creation of a Cartesian Product, which can inflate the result set size.

Final Thoughts

The INNER JOIN in SQL is essential for retrieving pertinent data spread across multiple tables. INNER JOINs are commonly utilized in practical scenarios like employee record management, customer order tracking, or student enrollment management. Mastering INNER JOIN serves as a foundation for grasping more complex joins and operations within relational databases, enhancing your SQL proficiency. This blog has equipped you with insights on executing an INNER JOIN in MySQL.

Advance your skills by registering for our SQL Training Course today and gaining practical experience. Also, prepare for job interviews with our SQL interview questions, crafted by industry professionals.

MySQL INNER JOIN – FAQs

Q1. What does INNER JOIN signify in MySQL?

An INNER JOIN combines rows from multiple tables based on a matching condition. It returns solely those rows that have corresponding matches in both tables.

Q2. What is the syntax for INNER JOIN?

“““html

SELECT columns  
FROM table1  
INNER JOIN table2 ON table1.common_column = table2.common_column;
Q3. What distinguishes INNER JOIN from LEFT JOIN?

INNER JOIN retrieves solely the records that match, whereas LEFT JOIN brings forth all records from the left table along with any corresponding records (or NULL) from the right table.

Q4. Is it possible to INNER JOIN with three or more tables?

INNER JOIN can connect several tables, provided each join condition is specified.

Q5. What occurs if there are no corresponding records in the second table?

The record would be omitted from the result set because INNER JOIN exclusively returns records that have a match.

The post MySQL INNER JOIN appeared first on Intellipaat Blog.

“`


Leave a Reply

Your email address will not be published. Required fields are marked *

Share This