A subquery is a SELECT inside another statement. It lets you use the result of one question to answer another: who scored above the average? first needs what is the average?
Scalar subqueries - a single value#
The inner query runs first and returns one value (7.83); the outer query uses it. Scalar subqueries can also appear in SELECT:
IN and NOT IN - a list of values#
NOT IN and NULL do not mix. If the subquery returns even one NULL, x NOT IN (...) is never true and you get no rows. students.dept_id contains a NULL (Om Malviya), so SELECT name FROM departments WHERE dept_id NOT IN (SELECT dept_id FROM students) returns nothing. Use NOT EXISTS instead (below), or add WHERE dept_id IS NOT NULL inside the subquery.
EXISTS and correlated subqueries#
A correlated subquery refers to the outer row, so it is evaluated once per outer row. EXISTS is true if the subquery returns any row:
Subquery = query के अंदर query। पहले अंदर वाली query जवाब देती है (जैसे औसत CGPA), फिर बाहर वाली उसका इस्तेमाल करती है। Correlated subquery हर बाहरी row के लिए दोबारा चलती है, क्योंकि वह बाहरी row का column (जैसे s.dept_id) इस्तेमाल करती है - "अपने ही department के औसत से ज़्यादा" ऐसे सवालों के लिए।
Derived tables - a subquery in FROM#
Common Table Expressions (WITH)#
A CTE gives a subquery a name at the top of the query. Several CTEs can be chained, which makes complex reports read top-to-bottom like steps:
Write complex queries as CTEs: each step is small, has a meaningful name, and can be tested on its own by running SELECT * FROM step_name.
Recursive CTEs#
A recursive CTE refers to itself - perfect for hierarchies (org charts, categories) and generating sequences:
Set operations: UNION, INTERSECT, EXCEPT#
They combine the results of two queries with the same number and types of columns:
| Operator | Result |
|---|---|
UNION |
rows in either query, duplicates removed |
UNION ALL |
rows in either query, duplicates kept (faster) |
INTERSECT |
rows in both queries |
EXCEPT (MINUS in Oracle) |
rows in the first but not the second |
Summary#
- Scalar subqueries return one value;
INsubqueries return a list;EXISTSchecks for any row. - Correlated subqueries refer to the outer row; beware
NOT INwith NULLs (preferNOT EXISTS). WITH name AS (...)(CTE) names intermediate results;WITH RECURSIVEwalks hierarchies.UNION,INTERSECT,EXCEPTcombine query results.