Junior — Middle
Can you explain what a nested query in a database is and how it is used?
sobes.tech AI
Answer from AI
A subquery is a query nested inside another SQL query. It is used to retrieve data that is then used in the main query.
For example, if you need to select all employees working in the department with the highest budget:
SELECT * FROM employees WHERE department_id = (
SELECT id FROM departments ORDER BY budget DESC LIMIT 1
);
Here, the inner query selects the id of the department with the maximum budget, and the outer query selects employees from that department. In Python, nested queries are often used with database libraries, such as SQLAlchemy or directly through cursors.