INNER JOIN in SQL is used to combine rows from two or more tables based on a related column between them. It returns only the rows where there is a match in both tables. If there is no match, the rows are excluded from the result set. This is the most commonly used type of join in SQL.
Key Points
- Matching Rows:
INNER JOINreturns only the rows where there is a match in both tables. - Common Column: The tables being joined must have at least one common column, usually a primary key and foreign key.
- Exclusion of Non-Matching Rows: Rows that do not have a match in both tables are excluded from the result set.
- Alias Support: You can use table aliases to simplify queries.
Syntax
column1, column2, ...: The columns you want to retrieve.table1, table2: The tables you want to join.common_column: The column that relates the two tables.
Examples
Suppose you have two tables:Employees and Departments.
Table: Employees
Table: Departments
To retrieve employee names along with their department names:
Using INNER JOIN with WHERE Clause
You can combineINNER JOIN with the WHERE clause to filter the results further. For example, retrieve employees who work in the IT department.
Using INNER JOIN with Multiple Tables
You can useINNER JOIN to join more than two tables. Suppose you have an additional table named Projects.
Table: Projects
To retrieve employee names, their department names, and the projects they are working on:
Practical Use Case
Suppose you have a table namedStudents and another table named Courses.
Table: Students
Table: Courses
To retrieve student names along with the courses they are enrolled in:
Key Takeaways
INNER JOINreturns only the rows where there is a match in both tables.- It is used to combine rows from two or more tables based on a related column.
- Non-matching rows are excluded from the result set.
- You can use
INNER JOINwith theWHEREclause to filter results further. INNER JOINcan be used to join multiple tables in a single query.