Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL SELECT statement expression value reuse for other expression
    primarykey
    data
    text
    <p>I have a table with huge row count in mysql (though I am looking for generic SQL solution)</p> <pre><code>very_big_table(INT a, INT b, INT c, ...) </code></pre> <p>I wanted SELECT statement</p> <pre><code>SELECT a, (b + c) as expression1, (b + c + a) AS expression2 -- basically (expression1 + a) FROM very_big_table WHERE ... GROUP BY a ORDER BY a DESC </code></pre> <p>this looks good and easily readable as long as the expression1 is simple.<br> But when CASE-WHEN/IFNULL()/SUM()/MIN()/STRCAT() or some Operator comes into play in these expressions its difficult to read and debug. </p> <p>I have gone through some of the already asked questions<br> <a href="https://stackoverflow.com/questions/5623410/assigning-mysql-value-to-variable-inline">assigning mysql value to variable inline</a><br> <a href="https://stackoverflow.com/questions/5180979/use-value-of-a-column-for-another-column-sql-server">Use value of a column for another column (SQL Server)?</a><br> <a href="https://stackoverflow.com/questions/5790697/how-to-use-conditional-columns-values-in-the-same-select-statement">How to use conditional columns values in the same select statement?</a> </p> <p>But if I use the approaches described something like</p> <pre><code>SELECT a, expression1, (expression1 + a) AS expression2 FROM (SELECT a, (b + c) AS expression1 FROM very_big_table WHERE ... GROUP BY a) as inner_table ORDER BY a DESC </code></pre> <p>this works fine, but this query is taking some 70x more time to execute. Atleast when i fired it, though only once.<br> what if I have multiple levels of the <em>expressions</em> in the output columns? </p> <p>Is there any elegant way to deal with this, without compromising readability?</p> <p>BTW why isnt this <em>expression reuse</em> or <em>alias reference</em> in select statement not supported by SQL standards or vendors? (supposing there are no cyclic evaluation in the single SELECT statement expressions. in that case the compiler fails)</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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