r/SQL • • 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

109 comments sorted by

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.

64

u/TheAmorphous Sep 17 '26 • Bravo

I find them to be much more difficult to debug than temp tables. With temp tables I can see what the data looks like at every step of the procedure.

13

u/OriginalCrawnick Sep 17 '26

You can call on the CTE itself, unless you're using multiple CTEs in a big query and wondering which one is messing things up?

13

u/TheAmorphous Sep 17 '26

That's a massive pain if someone is chaining multiple CTEs (which they often do where I work). So much more difficult to track down in which of those steps something is going wrong. You literally have to re-write part of the select for each step you want to check.

-9

u/atrifleamused Sep 17 '26

I find people chain them because they are lazy and unnecessarily break down the problem into too many smaller steps.

10

u/neumastic Sep 17 '26

I’d argue the opposite, I train people to do it in reasonable steps to make debugging easier. Clearly delineated steps takes more thought into the process than some massive join with random subqueries. That said, I don’t know what steps you’re seeing. Typically I’ll have a cte represent a subsystem. Only rarely do you need more than the final body that joins the sources. To debug, you just comment out the alias and add a line break. You can guess and start from the top, bottom or middle rather than just staring at the query hoping you find the error or writing separate queries to see if assumptions about the data were wrong.

-6

u/atrifleamused Sep 17 '26

You seem to be describing rather trivial queries. Most of my queries are in the thousands of lines of code....I don't use random sub queries, they are written to make sense within the flow of the query - having to scroll up hundreds of lines of code to look up logic makes little to no sense.

8

u/neumastic Sep 17 '26

We’re talking the same scale, though rarely do I have someone who writes non-“trivial” queries of more than a couple thousand lines where they cannot be refactored into something shorter, more performative, and easier to debug. I also find with good naming practices I typically don’t need to scroll that much. If that works for you, great, in our environment these queries are often re-adapted by different people so I need a method that works well for everyone unless I want to start filling my time with writing queries for people.

-9

u/atrifleamused Sep 17 '26

🤣🤣🤣

14

u/topicality Sep 17 '26

Agreed. I prefer temp tables and even sub queries to CTE

2

u/Comprehensive-Tea-69 Sep 23 '26

I generally write a select for each cte at the end my my code so I can note them in and out for debugging and edits at some future point. Very nicely organized for myself and especially others needing to maintain code

4

u/neumastic Sep 17 '26

I would say CTE and never sub queries as a preference. Temp tables v CTEs are dependent on your environment, access, and abilities. I work with data that changes quickly, temp tables could be misleading when researching. Personally I think temp tables are a crutch, but can see how they’d be useful when learning.

9

u/chaosink Sep 17 '26

Temp tables are also for performance. You push big datasets through CTEs at a cost. 

7

u/Strict-Ambition4334 Sep 17 '26

It also matters whether the same CTE gets referenced more than once. Some engines end up re-evaluating it for each reference, and at that point a temp table or materialized staging table is the more predictable option.

3

u/chaosink Sep 18 '26

CTE's can loop in bad ways even on their own. Always look at the execution plan.

2

u/neumastic Sep 17 '26

I wouldn’t argue with you there. We don’t do our data processing and reporting in queries, we have a series of work and staging report tables that handle that even there we have to make sure we handle the data to not run out of memory. Similar idea in the end, though.

1

u/ShoreWhyNot Sep 18 '26

If you’re writing a stored procedure and need to spit out the results in JSON, you can’t use a CTE in the query result . Temp tables work though

1

u/cafealpha82 Sep 18 '26

Cte is usually harder to read/debug

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

10

u/atrifleamused Sep 17 '26

Yes and you can index temp tabs! CTEs rely on the underlying tables which we often have no control over.

5

u/you_are_wrong_tho Sep 17 '26

Was going to come back and add this to my answer!

2

u/atrifleamused Sep 17 '26

Temp tables are definitely the best for bigger data sets.

16

u/No_Raspberry_3282 Sep 17 '26

Temp tables. I'm an old fart.

3

u/phunkmunkie Sep 17 '26

Me too… pays to bet on a winner. 😉

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

9

u/Spillz-2011 Sep 17 '26

Sub query should be a crime

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/PatientlyAnxiously Sep 17 '26

I'm self taught too and went down the same path. Also puzzled by your CTE>subquery situation, sounds like the query engine likes CTEs more. I generally use CTE these days but subqueries are good tool.

Another reason not to use temp tables: they require permission beyond SELECT. Those can be annoying to set up if you're ever handing something off to an analyst.

1

u/SnooSprouts4952 Sep 17 '26

IIRC, it was a messy query that was pulling from the same data set 26 times for a recursive loop. 🙈

Weekly sales by SKU for 26 weeks.

2

u/crulge Sep 17 '26

Some engines materialize CTEs but not subqueries, which leads to a performance boost

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 LATERAL join 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:

  • part of the process does some sort of "slurp a CSV/TSV file off the disk into a temporary table and then query across that"
  • CTE-like data is used across multiple queries (a CTE is largely scoped to a single query); so if I'm firing off several different queries in the same transaction, and they all involve a common subset of data, using a temp-table can be advantageous
  • following on the previous multiple-query case, if your DB lets you create indexes on temp-tables, you can occasionally optimize certain reuse cases by indexing the temp-table in a way that its referencing queries can use well

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 ♥️

2

u/WolfBanner Sep 18 '26

I find #temp tables to be a god send for cutting the base data pull down to a reasonable size (and therefore resolving most of my performance issues). But I find myself moving to the “cross/outer apply” function, instead of joining in a temp table, if I need to massage the data before joining it to a table.

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:

  1. Subquery: one extra filter or lookup, used once, small.
  2. CTE: you want to read the query, or reuse the same chunk twice in one statement. It is not automatically faster.
  3. TEMP TABLE: the chunk is big, you will hit it more than once, or you need an index on the intermediate result.

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.

3

u/iLoveYoubutNo Sep 17 '26

Yesss!!! My people!

2

u/Glittering_House_654 Sep 17 '26

Why are temp tables ugly?

1

u/dyogenys Sep 17 '26 edited Sep 17 '26

In sql server the syntax is ugly, while the syntax for CTE is neat. Structurally too, the TT scripts feels less like a declarative query and more procedural series of steps compared to CTE.

1

u/Glittering_House_654 Sep 18 '26

How is a CTE prettier than a

DROP TABLE IF EXISTS #TempTable;
SELECT abc
INTO #TempTable?
FROM dbo.SrcTable;

Ofc if you want tight control of the schema and constraints, then a create insert is better and can become more burdensome. Often its not necessary though.

I am just asking out of curiosity. Tt vs cte vs sub-queries all have their place. I just don’t get the ugliness of a tt.

1

u/dyogenys Sep 18 '26 edited Sep 18 '26

WITH SomeName AS ( SELECT abc FROM dbo.SrcTable )

Is just subjectively prettier, it's like trying to explain why I don't like the taste of cherries but like the taste of oranges. Because of most contexts I code in, the temp table syntax looks like comments to my brain. And this doesn't make sense on it's own; with more steps it becomes uglier compared to CTE which is one query. Maybe it's just what I'm used to. CTE is usually more performant for what I do. I use temp tables some times, when there is clear benefit to performance.

1

u/Glittering_House_654 Sep 18 '26

Agree that its subjective. There are pros and cons with both.

No with more steps they are quite identical actually. I would love to see performance stats where cte performs better than a tt (not just ms). There is one line of diff here between the two.

1

u/dyogenys Sep 18 '26 edited Sep 18 '26

Zero lines of difference because I put the ( on new line c# style.

Where predicate pushdown is possible because you use filtering, which is often, cte can be as many orders of magnitude faster as you would like based on how much you filter down to of how much.

Any time you don't use an inermediate set more than once, which is most of the time, cte is more performant. CTE is just another, often neater, way to write an inline query, with aliasing benefits, except for some niche stuff cte can do extra; Obviously temp tables aren't always more performative than not using temp tables, right?

1

u/atrifleamused Sep 17 '26

Temp tables are not in anyway ugly. You create and define a structured table which contains the data you inserted, cleansed, deduced, indexed, etc. It can be way for elegant and clean than an inline view which relies on indexing strategies you did not define.

1

u/dyogenys Sep 17 '26

It’s in the eye of the beholder.

1

u/atrifleamused Sep 17 '26

Not understanding something doesn't make it ugly 🤷

1

u/dyogenys Sep 18 '26

What makes you think I don’t understand TT? It’s not complicated, it’s easier to understand than CTE index optimization.. but has less potential. Are you aware of the downsides of TT? If you consistently reach for them first in my job which relies on sql agent to run many jobs on gigantic tables multiple times per day, you slow down the whole database, tanks IO and jobs literally block and delay each other in the tempdb. And it forces the individual programs to be procedural, which literally makes global execution plan optimizations impossible and slows performance even before taking the database resources into consideration. Those indexing strategies you talk about are optimizations you literally can’t get with temp tables. You control if they can happen with indexes on the source tables.

That’s not why I don’t use them though, I’m not paying for the server lol, I genuinely prefer declarative over procedural for SQL.

1

u/atrifleamused Sep 18 '26

Oooo SQL agent... How year 2k.

1

u/dyogenys Sep 18 '26

We’ve organically gone back from stream processing which was just completely a counterproductive fad, from both upstream on kafka and downstream on spark. But dude, what’s your problem?

1

u/atrifleamused Sep 18 '26

Sorry I didn't mean to make you cry. You have a nice day.

→ More replies

2

u/jshine13371 Sep 18 '26

Temp Tables can be more performant than CTEs (particularly in SQL Server which you mentioned further down) both because they are indexable and because they act as a logical breakpoint in the code for the Query Planner, simplifying its job, which allows it to generate more performant execution plans.

That doesn't mean Temp Tables should always be used, but it's important to be mindful of these very real benefits.

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.

1

u/tommyfly Sep 17 '26

Temp tables are useful in many scenarios. Often complex queries/procedures need to be broken out into smaller parts. Temporary results can be effectively stored for later use, reducing the data sets for complex joins. Temp tables can also have clustered indexes to that can match the tables they join to. Don't forget, a CTE is just a sub query written in a different way. And a downside of CTEs is that they are executed every time they are referenced. So if you join a CTE to 4 tables that same CTE will be executed 4 times.

I can't count how many stored procedures I have rewritten converting CTEs to temp tables and improving the performance by factors of 100.

That said, CTEs have their place. But, generally, in my experience, once things start to get complicated or the data sets get big, I tend to use temp tables.

0

u/[deleted] Sep 17 '26

[deleted] — view deleted comment

1

u/alinroc SQL Server DBA Sep 17 '26

Why a table variable instead of a temp table?