Prompt
Answer
Joining Three Different Tables Using SQL
Objective
To demonstrate how to write an SQL query that links three different tables using JOIN
and WHERE
clauses.
Assumptions
- Table1 (Employees): Contains employee details.
- Table2 (Departments): Contains department details.
- Table3 (Salaries): Contains salary details of employees.
Schema
Table1 (Employees):
employee_id
first_name
last_name
department_id
Table2 (Departments):
department_id
department_name
Table3 (Salaries):
employee_id
salary
SQL Query
-- Linking three tables using JOIN and WHERE clause
SELECT
e.employee_id,
e.first_name,
e.last_name,
d.department_name,
s.salary
FROM
Employees e
JOIN
Departments d ON e.department_id = d.department_id
JOIN
Salaries s ON e.employee_id = s.employee_id
WHERE
s.salary > 50000; -- Filter to only include employees with a salary greater than 50,000
Explanation
SELECT Statement:
- Retrieves specific columns from the combined tables:
employee_id
,first_name
,last_name
,department_name
, andsalary
.
- Retrieves specific columns from the combined tables:
FROM Clause:
- Specifies the primary table to query from, which is
Employees
(aliased ase
).
- Specifies the primary table to query from, which is
JOIN Clauses:
JOIN Departments d ON e.department_id = d.department_id
: Links theEmployees
table to theDepartments
table based on thedepartment_id
column.JOIN Salaries s ON e.employee_id = s.employee_id
: Links theEmployees
table to theSalaries
table based on theemployee_id
column.
WHERE Clause:
- Adds a condition to filter the results where the
salary
is greater than 50,000.
- Adds a condition to filter the results where the
Practical Example
Imagine you want to view a list of employees, their corresponding department names, and salaries for all employees earning more than $50,000. You can run the above SQL query in your database management system (DBMS) to get the desired results.
Conclusion
This query efficiently joins three tables and filters results based on the specified condition. Following best practices, the code is modular and can be easily extended or modified for additional requirements.
For more advanced learning and in-depth knowledge on SQL and data analytics, consider exploring courses on platforms like Enterprise DNA.
Description
This guide demonstrates how to join three tables (Employees, Departments, Salaries) using SQL with JOIN and WHERE clauses, filtering for employees with salaries over $50,000.