r/SQL • u/Harshita_Netla • Sep 17 '26
MySQL CTEs vs subqueries vs temp tables — as a beginner, how do you know which one to use?
For people who use SQL regularly, how do you decide which approach to use?
98
Upvotes
111
u/Infini-Bus Sep 17 '26
I use CTEs as I dont have privs for temp tables and they're easier to read, optomize, and troubleshoot than subqueries.
49
u/you_are_wrong_tho Sep 17 '26
Temp tables when you need to call that data more than once, otherwise cte is usually fine. I like to use temps for big queries because they’re usually quicker than a cte
16
u/No_Raspberry_3282 Sep 17 '26
Temp tables. I'm an old fart.
29
u/Last0dyssey Sep 17 '26
I prefer temp tables, easier to read, easier to validate during each step, and you only need to rerun sections of code rather than the entire thing like a CTE. Makes working with larger datasets more manageable. However each of these have their own place and I wouldn't worry about splitting hairs on each of them. Just focus on writing clean SQL with clear to follow logic and though process. I should be able to go through each chunk of your code and see why you did and what you did and where you are going next.
30
u/Odd_Estimate_2179 Sep 17 '26
I use dbt which encourages CTEs
Subqueries are used sparingly
8
u/Better-Credit6701 Sep 17 '26
Lots of data, use temp tables, not so much data CTEs. Lots of data vs not so much is more depending on the resources of your server along with number of rows. A server with 2 TB of ram can do some amazing things
11
u/SnooSprouts4952 Sep 17 '26
Self taught - I started out sub queries, then dabbled in temp tables at one project, then recently learned about CTEs.
They all have their place. I find sub queries easiest to read still. Temp tables are great to pull large sections of data from even larger sections of data so you can analyze it faster (think 10+ years of tax records for every person in a county times however many assessments were done that year, and you only want analysis on certain audit window). Last year I had severe performance issues on a new software I was working with and was directed to try a CTE. The query went from ~2-3 minutes down to <15 seconds to run. I'm still wrapping my head around how they work, so I can't give any advice past that.
So, to answer your question. I haven't used a temp table in ~15 years. I may not even have access to do so any more. I'll do subqueries until I find a performance hit where I need to convert to a CTE.
5
u/jusdonc Sep 17 '26
since i deal with huge amounts of data, TEMP tables for the win
5
u/gumnos Sep 17 '26
With most modern DBs, CTEs and subqueries are largely the same under the hood. In certain older versions, the CTE could be an optimization barrier and result in either MORE-performant queries because it materialized the CTE or LESS-performant queries for exactly the same reason.
If you have to do recursion, CTEs are the only (reasonable, ignoring cursors and other abominations) way to go.
AFAIK, you can only do a
LATERALjoin as a subquery, not a CTE, so I do that as needed.So these days, I tend to choose whichever makes my query more readable. For me, I tend to use subqueries if the underlying data is used once in the main query and it doesn't involve recursive queries; and I use CTEs if the virtual-table data is used in more than one place in the main query. I acknowledge the controversial nature of this since some folks loathe sub-queries and only use CTEs.
Temp tables are notably different than the other two. Cases in which I'd turn to temp-tables:
5
u/sinceJune4 Sep 17 '26
I prefer CTEs, to me they are cleaner than subqueries. Temp tables are very platform-specific; i used them a lot on SQL Server. But other platforms may not have them; or I also worked in some read-only environments where I didn’t have access to create temps. In HIVE, I could use them, but often had issues with them expiring before I was done with them.
You need to know all three, imo, but CTE is my goto first.
5
u/mlhigg1973 Sep 17 '26
I always used temp tables. It helped me keep things more organized.
4
u/Wuthering_depths Sep 17 '26
These all have their limitations...temp tables can't be used in a view for example, you'd need a proc (sql server at least)...but we often do use procs so that's fine. The really great thing about them is that it can create very easy to read code that can be stepped through while troubleshooting.
Subqueries can of course be in various places (select, as derived tables in the from, filters in the where) and sometimes they are the way to go. Once you start nesting layers of these it becomes much harder to troubleshoot as you can't easily run parts of such a query, that's again one nice thing about breaking it up with temp (or real) tables in steps. Correlated subqueries are a handy way to do de-duping of records in an update or delete but they tend to be inefficient, but typically we use these as fixes and not something you'd have called by an application or report.
Temp/real tables also can have an index applied to them, which has a cost of course but can help with big datasets. We are generally working on ETL queries and not real-time application queries I should mention, so we can afford a bit of extra time/inefficiency if it provides easier maintenance and quicker ability to update the logic.
In sql server at least there are also table variables, which I'd use instead of temp or real tables if the data is not huge. They are less easy to step through bit by bit as (same with CTEs) as you have to execute everything back to where the table var is being created. What I will sometimes do is use temp tables while developing, then convert those to table vars once everything is tested. The big advantage for this for our team is that it works better when called by SQL in ssis package as iirc it can know the schema of what is being returned. Then again, if you put it all in a proc and then call the proc, not an issue! :)
4
u/AntLost4161 Sep 17 '26
Tbh, there's not really a lot of times I'd use a subquery. It does everything a CTE can, but it sometimes risks being a bit less readable (especially true if you have a big query). Temp tables are great for when the CTEs would need to be used for tons of queries or if the CTEs go on for a bit too long.
This stuff is pretty much just decided by readability and how much you're gonna use them. Use temp tables if you're gonna use it a lot, then CTEs if you need readability, then subqueries if it's just a tiny thing
3
u/GTS_84 Sep 17 '26
Subqueries when I’m being quick and lazy. Maybe I’m trying to get a sense of the data in a database. They aren’t going to stick around in anything permanent
CTEs when I really need recursion.
Temp tables otherwise.
3
u/Odd-Substance-4455 Sep 17 '26
Temp tables are good pre queries, can help reduce a result set to a smaller one before using in another query. CTEs are generally not more performant than sub queries - under the hood sql uses stats and indexes and translates into merge/loop/hash joins. CTEs do not provide more insight into a better plan.
3
u/restlessleg Sep 17 '26
wana know something funny?
i just learned about temp tables 2 years ago and have become the BI outside of BI.
i never used cte but incorporate my #temp in subselects with exists/in.
i love temptables ♥️
3
u/mikeblas Sep 17 '26
As a beginner, you focus on getting the query logic right. Get the right results. Do it however you'd like.
Then, once you've achieved correctness, consider other attributes like performance.
3
u/Prownilo Sep 18 '26
Table Declarations for small data sets you are going to use multiple times or want to make minor modifcations to before joining onto the query
Temp Tables for Large data sets you are going to use lots of times, or want to make large modifications to before joining
CTE's for everything else, Once offs, smaller and medium data set sizes. Sometimes I will still use temp tables if the data set size is particularly large or needs to be re-indexed for the query to function
Basically, I start off with a CTE, if the performance is not up to scratch I start trying with Temp tables.
I haven't used subqueries much since I learned CTE's, I may use them as a once off here and there but tend to avoid them unless it's like an EXISTS or something.
5
u/Enigma1984 Sep 17 '26
CTE's rather than subqueries, every time.
Temp tables when it makes sense. For example if I need to write a query and then call it several more times later in the script then a temp table will write once whereas a CTE would have to rerun that logic every time it gets called.
4
u/BanAvoidanceIsACrime Sep 17 '26
Small Data -> CTE (10 rows base table which need to each access the CTE for example) there is no base table, you just filter the result from another query? -> CTE (something like window functions over a whole table, most of the work is done in the CTE which is just one big query, and then the result gets somehow filtered by the CTE caller, this is mostly fine)
Bigger Data, need to index/search the data? -> temp
Every time you're thinking, "I actually want a subquery here." -> temp table
temp tables are very good at what they do, CTEs are ore of specific tool than a general tool, temp tables get it done most of the time without any issues and they are really easy to debug
2
u/read_at_own_risk Sep 17 '26
Temp tables are difficult to debug and don't work well with proxy servers, for me they're a last resort only. CTEs are generally a bit nicer than subqueries, so CTEs > subqueries > temp tables.
2
u/KBradl Sep 17 '26
I prefer temp tables when comparing against un-indexed fields. Lets say you are comparing all columns of one table against all columns of another, I would filter into a temp table then do the comparison.
But if you are comparing against indexed fields then CTEs are easier to read and manage.
2
u/vertigo235 Sep 17 '26
CTE first , temp tables sometimes for optimization , never sub queries
2
u/Pale_Squash_4263 Sep 17 '26
Performance wise, CTEs and sub queries are nearly identical in performance to my knowledge. Mostly a readability thing so I prefer CTEs for the most part.
Temp tables can depend. I’ve had cases where setting up a temp table to structure the aggregations and then doing the data pull lead to better performance or just quality of life changes
2
u/blueberrywalrus Sep 17 '26
Subqueries are for being lazy.
Otherwise, it can depend on what database you're using and how it executes CTEs. Some databases, like big query, basically never materialize CTEs and there can be big cost differences when choosing between temp tables and CTEs. Many databases will materialize CTEs when you reference them multiple times, and the choice is less important.
Generally, I find it easier and more performant to use temp tables for large datasets or for complex transformations.
CTEs tend to be more readable, but harder to debug and sometimes much less performant.
2
u/FSHRPTR Sep 17 '26
Sub queries can have performance hits. Temp tables are preferable when that happens, they are also easier to follow and test. I've not used CTEs a lot, so can't comment on their performance.
2
u/ShadowDancer_88 Sep 17 '26 edited Sep 17 '26
I got used to subqueries before SQL server had CTEs, so I gravitate towards them if I don't need to reuse the data set.
CTE's when I need recursion.
As far as performance goes, they should be the same, but in any specific situation, who knows what the optimizer will do. Try each, and look at the query plan.
When a data set will be used multiple times, table variables or temp tables.
Indexing temp tables can make huge differences in the right circumstances, but with all things, testing will show if it's worth it or not in any specific circumstance.
2
u/Spillz-2011 Sep 17 '26
My approximate workflow.
Use cte. If reasonably fast move on with my life
If slow why ask llm if I accidentally joined on true. If yes don’t do that.
If slow still get query plan.
If query plan says it’s slow because of something I did late filters many to many joins then temp table won’t fix it so fix query.
If its optimizers fault do to bad statistics or just optimizer being stupid use temp tables.
2
u/decrementsf Sep 17 '26
CTEs are generally easier to read than subqueries. In most cases where subqueries may be needed can usually write a CTE to accomplish the same thing, and make it easier for others to follow along with. Even going back and looking at my old subqueries it seems slower to figure out what I was doing than if I'd built it up with a CTE.
Temp tables no opinion on. Have mostly interacted with them with exercises around optimizing workflows. My actual experience didn't use temp tables much. It's possible that's a gap in my projects, dunno.
2
u/Imaginary-poster Sep 17 '26
Sbuqueries felt more natural to me when I started. But CTE are just better subqueries (purely for readability and reusability).
Temp tables Ive only started to dabble with but use them to manage unidexed tables or data transformed that loses its indexing.
Applies are my new favorite thing. Replaced alot of ctes with those.
2
u/lalaluna05 Sep 18 '26
Vibes.
Jk kinda. You start getting a feel for what you need as you work with your data more. I use temp tables pretty extensively for staging since I’m pulling data from other servers; I try to materialize what I need there then bring it over into a temp table and hold it.
I use CTEs for more simple data transformation.
I don’t love subqueries but I use them a lot with min and max to find the first and last of various fields.
2
u/SecureStrike333 Sep 18 '26
I dont like subqueries because they are hard for me to read and seem overly complicated.
I used to prefer temp tables until I grasped the concept of CTEs. CTEs have less syntax to worry about and look cleaner. But sometimes as others have mentioned temp tables still have their place.
2
u/cafealpha82 Sep 18 '26
Temp table for re usablity and readability. I hate nested sub queries as well as nested cte. When it works, its fine. But most time someone need to make enhancement or fix the bug. Temp table saves time a lot in long term.
2
u/This-Emergency8839 Sep 18 '26 edited Sep 18 '26
Temp for big tables where a cte would slow down the query.
I've seen huge performance gains converting a cte to temp.
I especially use them in stored procs to build tables from large sources. Adding indexing on the fly I've found can really help the query planner.
CTE won't give the planner many clues as to what data size you're dealing with. An indexed temp table helps the query planner be maximally efficient.
2
u/LukaGOGO Sep 18 '26
Beginner rule that survives contact with MySQL/MariaDB:
On MySQL/MariaDB a CTE is often just syntax. The optimizer may still spool or reread it. If EXPLAIN looks ugly and the same subquery runs twice, write a TEMPORARY TABLE, index it, then join.Don’t start with temp tables for a 20-row lookup. Don’t use a CTE because a blog said it is “modern. ” https://mariadb.com/docs/server
Are you on MySQL 8 / MariaDB (CTEs exist) or 5.7 (then you only have subqueries and temps)?
6
u/dyogenys Sep 17 '26
CTE, mainly because TT are ugly and therefore unenjoyable to me, not some cerebral reason.
2
u/feignapathy Sep 17 '26
Temp tables if you can. Especially if you're just beginning.
They tend to be easier to create and easier to read in my experience.
But they're kind of like training wheels, and eventually you probably want to use CTEs.
I avoid subqueries when possible. I find them the hardest to read.
2
u/maudeinshades Sep 17 '26
The job I’ve had for the last 2+ years I only use CTEs. I’d never used them before but now that’s all I use. I recoil when I see a subquery.
1
u/Aware-Hovercraft1106 Sep 17 '26
I like using temp tables and sometimes sub queries when it's a very small attribute selection that fits well in something like left join (select account,sum(purchases) from table group by 1). Where temp table would be overkill
1
u/TreeOaf Sep 17 '26
It really depends on the job, you cannot always use one or the other.
For example, a CTE works in a VIEW whereas temporary tables don’t.
1
u/DeltaEdge03 Sep 17 '26
Depends on the query
If the OG query takes only a few seconds to run then I’d use a CTE. If there’s an assload of data in tables that weren’t indexed properly (or at all), then a temp table for inserting data to query against.
1
u/phunkmunkie Sep 17 '26
Temp tables are my way to go. They have indexes and statistics, so perform well.
I go back and forth between CTEs and sub queries in views. Depends on the data set, really.
But the overarching key is that you use these objects to knock the working data set down to only work on what is required, improving processing efficiency
1
u/Stock-Recognition44 Sep 17 '26
Subqueries are only when necessary (some tools like Tableau won’t work with CTEs for some database engines, so subqueries are all you’ve got
CTEs are probably most general purpose and get the most use.
Temp tables if you need custom optimization.
1
u/Max_Americana Sep 17 '26
CTE’s are my go to starting point as well. It helps organize larger complex queries into categories.
As a beginner I’d use temp tables first to design your workflow, then combine them into a CTE and test it. If slow try sub queries or put indexes on the necessary tables and columns to speed it up.
1
u/captain_20000 Sep 17 '26
I mostly use CTEs and only use subqueries for very very small queries.
1
u/Small-Ad-7694 Sep 17 '26
Generally speaking I try to keep things "simple" over "sophisticated" or "complex".
So I tend to use CTEs (with or without subqueries in them but, again, never go too complex and nested). And then temp tables where it makes sense. Comment the whole thing.
1
u/Tackit286 Sep 18 '26
Having just learned about CTEs yesterday, my answer is CTEs. What a revelation.
1
u/Sudden-Step9593 Sep 18 '26
It's all about preferences. For me I'd rather read or write a cte. Subqueries are more difficult for me. Your mileage may very.
1
u/ogfuzzball Sep 18 '26
CTE generally puts pressure on your CPU while temp tables are I/O. It depends on the workload itself which one makes the most sense.
1
u/Porgemansaysmeep Sep 18 '26
Generally temp tables unless I'm not allowed to. Main reason is being able to run and view each component of the query steps I'm doing individually to make sure I have what I want, am not getting funky data pulled in, and ease of troubleshooting/changing more complex queries.
CTE when temp tables aren't allowed, and Subquery for a straightforward aggregation, but even then as often as not I just make another temp table for each logic step for the consistency in process.
1
u/Porgemansaysmeep Sep 18 '26
Huge fan of temp tables because in your first table or 2 you can filter the results down to just your area of interest, and then all the subsequent temp tables build off that and run much faster because they are joining based on your much smaller temp table vs. Searching Everything.
1
u/Informal_Pace9237 Sep 18 '26
CTE and sub queries are generally interchangeable. They can be used in lieu of each other. Keep in mind CTE always comes with memory implications. My preference is Subqueries except if the dataset in question is very small.
TEMP table usage is heavily dependent of Base RDBMS and generally used when the dataset in question is large or needs bulk transactions.
1
u/TechnicalGirlyPop Sep 18 '26
It’s interesting because in my masters program, my SQL class was super focused on subqueries, but on my first day as a data engineer, one of the first things my manager said was to never use a sub query.
I find CTEs and temp tables equally readable but use temp tables when I know I might need to pause at that step later on and look at the data for debugging or if the logic is used in more than one query. I also tend to add a comment above each CTE when I have a few to make sure I understand why it’s needed vs combining the logic somewhere else.
1
u/melodicmonster Sep 19 '26
As with all things SQL, it depends and I often combine them. My recommendation would be to write multiple versions of your queries, using each option and comparing/profiling until you get a feel for when to use what.
I default to CTE's for readability unless there is a reason not to. Subqueries can be faster than CTE's in some cases, but I generally only use them if they are very short (3-4 lines), easily understood, and/or coorelated. I move on to temp tables or table variables if there is a significant performance concern.
1
u/MaximumQuestion1827 Sep 25 '26
I'd say it depends on the purpose.
If you need a "cache" you can use across several queries and want the power of indexes, choose temp tables. CTE is for a single query only. A subquery is a totally different animal, though.
Remember, we still don't have a 'relational variable' entity - others call it a session variable, which seems not fully identical. So, temp tables are a way to implement it.
1
u/BarfingOnMyFace Sep 28 '26
Heh, alot of answers in here align with who works with postgres vs who works with sqlserver
1
u/cwjinc Sep 28 '26
CTEs mainly. subqueries if I need to outer join to it.
I never use temp tables unless you count materialized CTEs.
PS I like chained CTEs because you can test each step in the chain easier than test a single big statement.
1
u/bulldog_blues Sep 17 '26
They're all useful in different ways.
But as a preference, CTEs are more readable than sub-queries albeit require some setting up.
Temp tables are useful for sample testing and want to look at exactly what's happening at each step.
0
u/[deleted] Sep 17 '26
[deleted] — view deleted comment