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?Dynamic SQL is used to reduce repetitive tasks when it comes to querying. For example, one could use dynamic SQL to create table partitioning for a certain table on a daily basis, to add missing indexes on all foreign keys, or add data auditing capabilities to a certain table without major coding effects.
USING only works in PL/PgSQL - ie within functions or DO blocks written in the PL/PgSQL language. It does not work in plain SQL; the EXECUTE in plain SQL is completely different, for executing prepared statements. You cannot use dynamic SQL directly in PostgreSQL's SQL dialect.
SELECT SUM(points) AS total_points
FROM sometable
GROUP BY
username
HAVING SUM(points) > 25
PostgreSQL
won't calculate the sum twice.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With