Bird
0
0

Consider these tables:

medium📝 query result Q5 of 15
PostgreSQL - Joins in PostgreSQL
Consider these tables:

departments
id | name
1 | HR
2 | IT
3 | Sales

employees
id | dept_id | name
1 | 2 | Alice
2 | 2 | Bob
3 | 4 | Carol

What will this query return?

SELECT departments.name, employees.name FROM departments RIGHT JOIN employees ON departments.id = employees.dept_id ORDER BY employees.id;
A[{"name": "IT", "name": "Alice"}, {"name": "IT", "name": "Bob"}]
B[{"name": "HR", "name": "Alice"}, {"name": "IT", "name": "Bob"}, {"name": "Sales", "name": "Carol"}]
C[{"name": "HR", "name": "Alice"}, {"name": "IT", "name": "Bob"}]
D[{"name": "IT", "name": "Alice"}, {"name": "IT", "name": "Bob"}, {"name": null, "name": "Carol"}]
Step-by-Step Solution
Solution:
  1. Step 1: Understand RIGHT JOIN with departments and employees

    RIGHT JOIN keeps all employees (right table). For each employee, it tries to find matching department by dept_id.
  2. Step 2: Match employees to departments

    Alice and Bob have dept_id=2 (IT). Carol has dept_id=4 which does not exist in departments, so department name is NULL.
  3. Final Answer:

    All employees appear with their department name or NULL if no match. -> Option D
  4. Quick Check:

    RIGHT JOIN keeps all right rows; unmatched left columns are NULL [OK]
Quick Trick: RIGHT JOIN keeps all right table rows; unmatched left columns NULL [OK]
Common Mistakes:
  • Assuming unmatched right rows are dropped
  • Mixing up which table is left or right
  • Expecting INNER JOIN behavior

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes