Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In your examples, the derived table is not strictly necessary. There are numerous cases where you might need to join to an aggregate or similar, and a derived table is really the only way to handle that:</p> <pre><code>SELECT * FROM A LEFT JOIN ( SELECT x, SUM(y) FROM B GROUP BY x ) AS B ON B.x = A.x </code></pre> <p>In addition, if expressions are used to derive columns from derived columns with a lot of shared intermediate calculations, a set of nested derived tables or stacked CTEs is the only way to do it:</p> <pre><code>SELECT x, y, z1, z2 FROM ( SELECT * ,x + y AS z1 ,x - y AS z2 FROM ( SELECT x * 2 AS y FROM A ) AS A ) AS A </code></pre> <p>As far as maintainability, using stacked CTEs or derived tables (they are basically equivalent) and can make for more readable and maintainable code, as well as facilitating cut-and-paste re-use and refactoring. The optimizer can typically flatten then very easily.</p> <p>I typically use stacked CTEs instead of nesting for a little better readability (same two examples):</p> <pre><code>WITH B AS ( SELECT x, SUM(y) FROM B GROUP BY x ) SELECT * FROM A LEFT JOIN B ON B.x = A.x WITH A1 AS ( SELECT x * 2 AS y FROM A ) ,A2 AS ( SELECT * ,x + y AS z1 ,x - y AS z2 FROM A1 ) SELECT x, y, z1, z2 FROM A2 </code></pre> <p>Regarding your question about:</p> <pre><code>SELECT x, x * 2 AS y, x + x*2 AS z1, x - x*2 AS z2 FROM A </code></pre> <p>This has the x * 2 code repeated 3 times. If this business rule needs to change, it will have to change in 3 places - a recipe for injection of defects. This gets compounded any time you have intermediate calculations which need to be consistent and defined in only one place.</p> <p>This would not be as much of a problem if SQL Server's scalar user-defined functions could be inlined (or if they performed acceptably), you could simply build your UDFs to stack your results and the optimizer would elimnate redundant calls. Unfortunately SQL Server's scalar UDF implementation cannot handle that well for large sets of rows.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload