views:

146

answers:

2

Hi,

Please explain.

a) "subquery factoring" is used to replace a non-correlated subquery. What about correlated subquery? Is there any way to move a correlated sub-query to 'WITH' clause section?

b) are "subquery" "subquery factoring" executed exactly once?

c) "subquery" vs "subquery factoring" which one is better

Thank you.

+2  A: 

You can use subquery factoring to replace a non-correlated subquery.
How on Earth do you propose doing so for a correlated subquery?

I don't understand part (b), can you rephrase?
Taking a guess at what you mean: a subquery in the WITH clause is typically executed only once before the main query is executed.

For large datasets, subquery factoring is obviously better since you're executing the subquery only once in most if not all cases. For smaller datasets the overhead of creating temporary tables may take longer than the actual query.

Apart from the performance concerns mentioned above, subquery factoring results in much cleaner and easer-to-maintain code.

Adam Bernier
"a subquery in the WITH clause is typically executed only once before the main query is executed."So subquery factoring is executed independently and exactly once. So it can not be used to completely replace correlated subqueries.
Sujee
I don't see any possible way to put a correlated subquery into the WITH clause. A correlated subquery is one that requires values from the main query in order to be run.
Adam Bernier
Thank you Adam Bernier.
Sujee
+1 but I wouldn't have characterised the question as a joke.
Jeffrey Kemp
@Jeffrey: True. I realised the OP was sincere after the follow-up. Edited that part out. Thank you for the comment.
Adam Bernier
+1  A: 

By the term "subquery factoring" do you really mean *re*factoring using a subquery? Refactoring is the process of altering a routine to improve maintenance and readability without altering its result. There are times when one cannot refactor a subquery into a common table expression (into "WITH" clause). Further, there is no golden rule about always using a CTE or always using a subquery (or derived table). It depends on the data and the DBMS as to what approach will perform best.

Thomas
In my question, "subquery factoring" meant by usage of 'WITH' clause to replace traditional subquery.
Sujee