Bird
0
0

You have tables:

hard📝 Application Q8 of 15
SQL - Advanced Joins
You have tables:
Employees(id, name, dept_id),
Departments(id, name),
Projects(id, dept_id, project_name)
Write a query to list employee names, their department names, and project names for projects in their department. Which query is correct?
ASELECT Employees.name, Departments.name, Projects.project_name FROM Employees JOIN Projects ON Employees.id = Projects.dept_id JOIN Departments ON Projects.dept_id = Departments.id;
BSELECT Employees.name, Departments.name, Projects.project_name FROM Employees JOIN Departments ON Employees.id = Departments.id JOIN Projects ON Departments.id = Projects.id;
CSELECT Employees.name, Departments.name, Projects.project_name FROM Employees LEFT JOIN Departments ON Employees.dept_id = Departments.id LEFT JOIN Projects ON Employees.dept_id = Projects.dept_id;
DSELECT Employees.name, Departments.name, Projects.project_name FROM Employees JOIN Departments ON Employees.dept_id = Departments.id JOIN Projects ON Departments.id = Projects.dept_id;
Step-by-Step Solution
Solution:
  1. Step 1: Understand relationships

    Employees link to Departments by dept_id; Projects link to Departments by dept_id.
  2. Step 2: Check join conditions

    SELECT Employees.name, Departments.name, Projects.project_name FROM Employees JOIN Departments ON Employees.dept_id = Departments.id JOIN Projects ON Departments.id = Projects.dept_id; correctly joins Employees to Departments on dept_id, then Departments to Projects on dept_id.
  3. Final Answer:

    SELECT Employees.name, Departments.name, Projects.project_name FROM Employees JOIN Departments ON Employees.dept_id = Departments.id JOIN Projects ON Departments.id = Projects.dept_id; -> Option D
  4. Quick Check:

    Correct chaining of joins by department id = SELECT Employees.name, Departments.name, Projects.project_name FROM Employees JOIN Departments ON Employees.dept_id = Departments.id JOIN Projects ON Departments.id = Projects.dept_id; [OK]
Quick Trick: Join tables by shared keys in logical order [OK]
Common Mistakes:
MISTAKES
  • Joining on wrong columns
  • Using employee id instead of department id

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes