Home › Interview Questions › If a subquery does not return the department name,…

If a subquery does not return the department name, how can the outer query access that department information?

🟡 Medium Conceptual Junior level
1Times asked
Oct 2026Last seen
Oct 2026First seen

💡 Model Answer

When a subquery does not return the column that the outer query expects, the outer query will either raise an error or return NULL for that column, depending on the SQL dialect and how the query is written. In most relational databases, a SELECT list in the outer query must match the columns produced by the subquery if the subquery is used as a derived table or a scalar subquery. For example, if you write: SELECT d.dept_name, sub.max_salary FROM departments d JOIN (SELECT MAX(salary) FROM employees) sub ON d.id = sub.dept_id; the derived table 'sub' does not expose the department id, so the join condition fails and you get no rows. To fix this, you must include the required column in the subquery's SELECT clause: SELECT d.dept_name, sub.max_salary FROM departments d JOIN (SELECT dept_id, MAX(salary) AS max_salary FROM employees GROUP BY dept_id) sub ON d.id = sub.dept_id; Now the outer query can reference sub.dept_id. If the subquery is a scalar subquery used in the SELECT list, you must ensure it returns a single column that matches the outer query's expectation. If the column is truly missing, the database will throw an error like 'column not found' or 'subquery returned no columns'. Therefore, always project the necessary columns in the subquery, or use a JOIN instead of a subquery when you need to combine multiple columns. This practice keeps the query clear and avoids runtime errors.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500