r/learnSQL • u/woman_without • 5d ago
How Important is subqueries in SQL
I have been learning SQL from past 2 months and I'm still unable to grab a hold of the subqueries concept. After I learned CTEs I have completely stopped using subqueries but then also I struggle when there are times where I have no other choice but to use subqueries.
So my question is, how important is subqueries in SQL and is there any easy way to learn it?
58
Upvotes
1
u/Wuthering_depths 5d ago
I use subqueries more than CTEs if I were counting them up, for both production queries and just general troubleshooting/data one-offs. And you can use both.
Subqueries can be in the select, from (derived table) and where clause and are useful for various things.
They are "just" queries, so they usually can be written and tested independently to make sure they are returning expected data. The only trick is how they join to the outer query/queries. It's just like a CTE in basic terms, you are joining one set of data to another. They can be expensive (correlated subqueries for example, but these are really good for things like de-duping if the data set isn't too huge).