Search⌘ K
AI Features

Answer: Subquery in the SELECT Clause

Explore the technique of embedding subqueries in the SELECT clause to retrieve related data from multiple tables. Understand how to use aliases, filtering conditions, and joins as alternate solutions. Gain confidence in applying subqueries to solve common SQL interview problems involving employees and projects.

Solution

The solution is given below:

MySQL
/* The use of subquery to find the employees working on a project */
SELECT (SELECT e.EmpName FROM Employees AS e WHERE e.EmpID = p.EmpID) AS EmpName,
ProjectName
FROM Projects AS p
WHERE p.EmpID IS NOT NULL;

Explanation

The explanation of the solution code is given below:

  • Lines 2–3: The SELECT query selects EmpName (coming from the subquery) and ProjectName from Projects, respectively. The e.EmpName refers to the EmpName column from the Employees table (aliased as e) and  p.EmpID refers to the EmpID column from the Projects table (aliased ...