Bird
0
0

You want to list all departments and their employees, including departments with no employees. Which query achieves this?

hard📝 Application Q15 of 15
PostgreSQL - Joins in PostgreSQL
You want to list all departments and their employees, including departments with no employees. Which query achieves this?
ASELECT departments.dept_name, employees.name FROM employees RIGHT JOIN departments WHERE employees.id = departments.id;
BSELECT departments.dept_name, employees.name FROM employees LEFT JOIN departments ON employees.id = departments.id;
CSELECT departments.dept_name, employees.name FROM departments RIGHT JOIN employees ON departments.id = employees.id;
DSELECT departments.dept_name, employees.name FROM departments LEFT JOIN employees ON departments.id = employees.id;
Step-by-Step Solution
Solution:
  1. Step 1: Identify which table to keep all rows from

    We want all departments, even those without employees, so departments is the left table in LEFT JOIN.
  2. Step 2: Use LEFT JOIN from departments to employees

    LEFT JOIN keeps all departments and adds matching employees or NULL if none.
  3. Final Answer:

    SELECT departments.dept_name, employees.name FROM departments LEFT JOIN employees ON departments.id = employees.id; -> Option D
  4. Quick Check:

    LEFT JOIN from departments keeps all departments [OK]
Quick Trick: LEFT JOIN from main table keeps all its rows, unmatched get NULLs [OK]
Common Mistakes:
  • Using employees as left table instead of departments
  • Using RIGHT JOIN incorrectly
  • Confusing which table to keep all rows from

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes