I know I have to write SUM
twice, if I wish to use it in a HAVING
clause (or use a derived table otherwise):
SELECT id,
sum(hours) AS totalhours
FROM mytable
GROUP BY id
HAVING sum(hours) > 50;
My question now is, whether or not this is suboptimal. As a programmer, this query looks like the DB will calculate the sum twice. Is that so, or should I rely on optimizations the DB engine will do for me?
Update: an explain of a comparable query:
postgres=> explain select sum(counttodo) from orderline group by orderlineid having sum(counttodo) > 100;
QUERY PLAN
--------------------------------------------------------------------
HashAggregate (cost=1.31..1.54 rows=18 width=8)
Filter: (sum(counttodo) > 100)
-> Seq Scan on orderline (cost=0.00..1.18 rows=18 width=8)
(3 rows)
HAVING
clause - but, to my understanding, internally this is rather done the other way around.HAVING
(and then pulling the column definition from theSELECT
clause) - for some reason they just don't do that.