r/SQLServer • u/Tectec8 • Jul 03 '26
Discussion sub queries
I'm studying SQL and am currently on the lesson about subqueries, but I just can't seem to wrap my head around it.
I'm struggling to get the different types of subqueries—and when to use each one—to stick in my mind.
Does anyone have any study materials on this? Maybe a YouTube video tutorial?
THANKS!
5
Upvotes
3
u/American_Streamer Jul 03 '26 edited Jul 03 '26
A SQL subquery is just a query inside another query. It is used when one SQL statement needs a result from another SQL statement. A Scalar subquery returns just one value. In contrast, an IN subquery returns a list of values. An EXISTS subquery checks whether matching rows exist. And a Subquery in FROM creates a temporary result table.
In short: A subquery helps you answer a question whose answer depends on another SQL result.
And uncorrelated subqueries are independent inner queries, while a correlated inner subquery refers back to the outer row.
7
u/No_Resolution_9252 Jul 03 '26
so there are two basic types, correlated and non-correlated, but doubt that is what you are struggling with.
Do you have any specific questions?
2
u/mqaiser Jul 03 '26
Sub queries and correlated sub queries
1
u/CPDRAGMEISH Jul 05 '26
69.70 69.80
Subquerys.
-
Nu Subqueries:-)DG
-6
u/Hopeful_Candle_9781 Jul 03 '26
Just because you can do something, it doesn't mean you have to do something.
I just use CTEs 🤷♀️
I used to do temp tables in my first SQL job because I didn't know anything else, but now I just use CTEs. If someone else has written some code and I've been asked to edit it I'll change the subquery to a CTE and see if it runs faster.
I just like CTEs. 🤷♀️
CTEs and window functions. Served me well for over 2 years.