2. Tracy McKibben
DBA Supervisor, Senior SQL Server DBA
Pearson VUE
Blog:
realsqlguy.com
Twitter: @RealSQLGuy
I’m not saying I’m Batman, I’m just saying that nobody has
ever seen me and Batman in the same room together...
4. What is a subquery?
A query wrapped within another query. Also
known as an INNER query.
The lowly sidekicks of the
SQL world.
5. Anatomy of a subquery
Which of these is a valid place to put a
subquery?
SELECT ?
FROM ?
INNER JOIN ?
ON ?
WHERE ?
GROUP BY ?
HAVING ?
6. Anatomy of a subquery
SELECT <a subquery can go here>
FROM <or here>
INNER JOIN <or here>
ON <or here>
WHERE <or here>
GROUP BY <or here>
HAVING <or here>
It’s, like, the ultimate superpower!
17. Sometimes loopy
A subquery is either correlated or non-correlated.
What is the difference?
A correlated subquery depends on the
outer query, looping through the outer
resultset, executing once for each row
in the outer query.
A non-correlated subquery stands
alone, only running once, independent
of the values in the outer query.
29. COUNT vs EXISTS
Are there any Green
Lantern symbols in this
collection?
Did you count them, or did
you simply see green and
say “yes”?
How do you know?
Did you do this:
WHERE COUNT() > 0?
or, did you do this:
WHERE EXISTS()?
30. NOT IN vs NULL
Be careful of NULL values returned by inner query
or value list in a NOT IN clause. NULL has no
value and can produce surprising results.
Always returns an empty resultset.
31. MAX vs RANK
MAX/MIN are often used in a
subquery to determine the
oldest/greatest/most recent row in
the outer query.
RANK/OVER and other windowing
functions are more efficient.
defeats
33. Subqueries In Disguise
Some T-SQL constructs behave much like
subqueries.
● non-indexed views
● common table
expressions (CTE)
● user-defined functions
Be wary of performance
problems.
35. The conclusion
● correlated vs non-correlated - know the
difference and potential impacts
● multiple ways to get the same data, but not all
perform well
● know new language features like RANK
● don’t count unless you need a number
● be wary of NULL values and hidden subqueries