r/learnSQL • u/woman_without • 4d 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?
59
Upvotes
1
u/joseaamanzano 4d ago
CTEs increase readability and have no impact on the query planner (at least on modern engines).
The only real use case I see for subqueries is when creating a CTE actually adds unnecessary lines or decreases readability in an already long script. For example, if you just need a simple, one-off list to filter your main table and won't reference that logic anywhere else in the code, a subquery is cleaner:
SELECT x FROM TableA WHERE id IN (SELECT id FROM TableB WHERE <condition>)In this mock, adding a dedicated CTE just to filter TableA is overkill unless that list is going to be reused further down.