3 ms·
Why are they recalculating the sum of the weights in the Q0 query? Their answer: select age, sum(weight) as total_weight from cats group by age ha
by gravypod 9y ago
Why are they recalculating the sum of the weights in the Q0 query?
Their answer:
select age, sum(weight) as total_weight
from cats
group by age
having sum(weight) > 12;
Which is equivalent to:
select age, sum(weight) as total_weight
from cats
group by age
having total_weight > 12;
- atarashi 9y agoThe HAVING clause is evaluated before the SELECT so you have to specify the full clause `having sum(weight) > 12` and not just the alias. Most SQL engines are probably smart enough to not actually recalculate everything.
- cema 9y agoYes, SQL engines tend to be much smarter than the SQL languages as such.
- andy_boot 9y agoAuthor here. - As others have said this SQL Engine makes me write the SQL out the long way. For some reason the shorter version (which I wrote first) is rejected by my postgres client.
- trollied 9y agoMost RDBMSes won't let you use a column alias in the same scope as it is defined (pretty sure the SQL standard itself doesn't specify that it should be allowed). You can get around this by using a CTE. Also, optimisers aren't stupid, the actual sum() function will not be recalculated.
- sourcesmith 9y agoSQL is a declarative language not a procedural language.