简体   繁体   中英

Declaring a temp table vs.using a WITH statement

I work in market research and am in the process of getting a better understanding of best practices when writing SQL.

One of the situations that I have encountered is the use of the WITH clause and the use of declared temp tables.

In most cases I use the with clause as it is easy to implement (and I prefer it to cascaded SELECT s).

However, is there a benefit to using declared temp tables when it comes to run time and efficiency? I am more looking for pros/cons of each.

Most important is to get a correctly working query first. Any query.

If it is to be reused many times, post it here and engineers will give opinion about how to improve it and perhaps how to measure its performance.

Many factors are at play: the schema, software, edition, server distribution, number of inputs, number of outputs, etc.

This decision is case-by-case. A WITH clause is useful to 1) repeat a sub-query multiple times in an outer query and 2) to pull out a complex inner query from the outer query to keep things clean and readable. A WITH can easily be replaced by a VIEW. Think of it as an inline view.

I would argue a temp table is more specialized. A temp table is often used for caching when you need to keep a result set around during a session to be used by multiple queries. There are other use cases, but again more specialized to the situation.

These two concepts are only "kind of" related.

Depending on your scenario, neither a WITH or a temp table may be appropriate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM