Home › Interview Questions › How can you reference the department name from the…

How can you reference the department name from the outer query inside an inner query?

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

💡 Model Answer

In SQL you can reference a column from the outer query inside an inner query by using a correlated subquery. The inner query can refer to columns of the outer query by simply naming them; the database engine will bind the outer values for each row processed. For example: SELECT d.dept_name, (SELECT COUNT() FROM employees e WHERE e.dept_id = d.dept_id AND e.status = 'active') AS active_count FROM departments d; Here the inner SELECT uses d.dept_id from the outer SELECT. The engine evaluates the inner query once per row of the outer result set, substituting the current dept_id value. This is useful when you need a per‑row aggregate or a conditional filter that depends on the outer row. If you need to filter the outer rows based on a condition that involves the inner query, you can use the EXISTS or IN predicate: SELECT d. FROM departments d WHERE EXISTS (SELECT 1 FROM employees e WHERE e.dept_id = d.dept_id AND e.status = 'active'); The key point is that the inner query can reference outer columns directly; you do not need to join explicitly. However, correlated subqueries can be slower than joins because they may execute repeatedly, so consider rewriting as a JOIN if performance is critical. In summary, you reference the outer column by name inside the inner query, and the database engine handles the binding automatically.

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