Junior — Middle
Explain what subqueries in SQL are and how they are used.
sobes.tech AI
Answer from AI
Subqueries in SQL are nested queries that are executed within another SQL query. They allow using the result of one query as part of a condition or data for the main query. Subqueries can be in the WHERE, FROM, or SELECT clause.
Example of using a subquery in WHERE:
SELECT name, salary FROM employees
WHERE department_id = (
SELECT id FROM departments WHERE name = 'Sales'
);
Here, the inner query finds the id of the "Sales" department, and the outer query selects employees from that department. Subqueries help write more compact and expressive queries, avoiding complex joins.