Reputation: 66911
Let's say I have something like this:
select sum(points) as total_points
from sometable
where total_points > 25
group by username
I am unable to refer to total_points
in the where clause because I get the following error: ERROR: column "total_points" does not exist
. In this case I'd have no problem rewriting sum(points)
in the where clause, but I'd like some way of doing what I have above.
sum(points)
in the where clause, is postgres smart enough to not recalculate it?Upvotes: 19
Views: 8522
Reputation: 31025
You have error in statement:
select sum(points) as total_points
from sometable
where total_points > 25 -- <- error here
group by username
You can't limit rows by total_points
, because sometable
don't have that column. What you want is limit gouped resulting rows by total_points
, computed for each group, so:
select sum(points) as total_points
from sometable
group by username
having sum(points) > 25
If you replace total_point
in your example, then you simply chech if sum computed from all rows is bigger than 25 and then return all rows, grouped by username.
Edit:
Always remember order:
FROM
with JOIN
's to get tablesWHERE
for limit rows from tablesSELECT
for limit columnsGROUP BY
for group rows into related groupsHAVING
for limit resulting groupsORDER BY
for order resultsUpvotes: 9
Reputation: 5932
I believe PostgreSQL is like other brands of sql, where you need to do:
SELECT t.*
FROM (
SELECT SUM(points) AS total_points
FROM sometable
GROUP BY username
) t
WHERE total_points > 25
EDIT: Forgot to alias subquery.
Upvotes: 12
Reputation: 425833
SELECT SUM(points) AS total_points
FROM sometable
GROUP BY
username
HAVING SUM(points) > 25
PostgreSQL
won't calculate the sum twice.
Upvotes: 26