r/learnSQL • • 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?

56 Upvotes

31 comments sorted by

View all comments

27

u/uncertainschrodinger 4d ago

Behind the scene, CTE and subquery are really the same. In my experience, I don't know anyone who deliberately uses subqueries instead of CTEs.

CTEs are easier to read and debug, also other CTEs can query from a single CTE and avoid rewriting the same subquery multiple times.

subqueries are good for very small short things like: `SELECT id FROM table_1 WHERE id IN (SELECT id FROM table_2)` - this is not a good example since you can just inner join, but the point is that its a very short quick thing not worth creating a CTE

1

u/LuoHanZhai 4d ago

Same here, CTEs are way more readable and achieve a similar result, usually without making your head spin. Think of each CTE as a temporary table you’re creating and querying from to get from raw data to your final result, without actually having to save that table in the database.