How do you use 'Subqueries' in SQL, and what are their limitations?
Instruction: Explain the concept of subqueries and discuss their potential drawbacks.
Updated
Official answer
A subquery is a query nested inside another statement. It can provide a scalar, a derived table or an existence/membership condition. Its allowed number of rows and columns depends on that context.
For PostgreSQL employees(employee_id integer, salary numeric):
SELECT employee_id, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees)
ORDER BY employee_id;
For salaries 10, 20, 30 the average is 20, so only the employee earning 30 qualifies. AVG ignores NULL salaries. If no non-NULL salary exists, the average is NULL and the comparison is not true.
A scalar subquery returning multiple rows raises an error; returning no rows yields NULL. A correlated subquery refers to outer values, but the optimizer may transform it rather than literally execute it once per row. EXISTS can avoid multiplying outer rows when only existence matters.
Check NULL and duplicate semantics before rewriting as a join. Inspect the plan and measure representative workloads; subqueries are not inherently slow, and a CTE or temporary table is not inherently faster. Use clear names to keep nested logic maintainable.