Certainly! Here's another example of using INNER JOIN with two tables: employees and departments.
Tables
-
employees
employee_idfirst_namelast_namedepartment_id
-
departments
department_iddepartment_name
SQL Query
The following query retrieves the first and last names of employees along with their corresponding department names:
SELECT employees.first_name, employees.last_name, departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.department_id;
Explanation
- SELECT Clause: Specifies the columns to retrieve:
first_name,last_name, anddepartment_name. - FROM Clause: Indicates the primary table (
employees) to query from. - INNER JOIN Clause: Joins the
departmentstable on the condition thatdepartment_idin theemployeestable matchesdepartment_idin thedepartmentstable.
Result
The result set will include only those employees who belong to a department, and it might look like this:
| first_name | last_name | department_name |
|---|---|---|
| John | Doe | Sales |
| Jane | Smith | Marketing |
| David | Johnson | IT |
In this example, only employees with a matching department_id in the departments table are included in the output.
