Bird
0
0

Given the tables:

medium📝 query result Q4 of 15
PostgreSQL - Subqueries in PostgreSQL
Given the tables:
employees(id, name, department_id)
departments(id, name)
What will this query return?
SELECT name, (SELECT name FROM departments WHERE id = department_id) AS dept_name FROM employees;
AEmployee names with NULL for all departments
BEmployee names with their department names
COnly employees from the first department
DSyntax error due to subquery
Step-by-Step Solution
Solution:
  1. Step 1: Understand the scalar subquery usage

    The subquery fetches the department name matching each employee's department_id.
  2. Step 2: Analyze the output

    Each employee's name is paired with their department name from the departments table.
  3. Final Answer:

    Employee names with their department names -> Option B
  4. Quick Check:

    Scalar subquery returns matching department name [OK]
Quick Trick: Scalar subqueries can fetch related single values per row [OK]
Common Mistakes:
  • Assuming subquery returns multiple rows causing error
  • Confusing department_id with department name
  • Expecting NULLs when matching rows exist

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes