Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referring to dynamic columns in a postgres query?

Tags:

sql

postgresql

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.

  • Is there any way to store the result in a variable without using a stored procedure?
  • If I do rewrite sum(points) in the where clause, is postgres smart enough to not recalculate it?
like image 924
ryeguy Avatar asked Jan 20 '10 15:01

ryeguy


People also ask

What is dynamic query in PostgreSQL?

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.

Is dynamic query is supported in PostgreSQL?

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.


2 Answers

SELECT  SUM(points) AS total_points
FROM    sometable
GROUP BY
        username
HAVING  SUM(points) > 25

PostgreSQL won't calculate the sum twice.

like image 142
Quassnoi Avatar answered Oct 13 '22 17:10

Quassnoi


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.

like image 30
Nathan Wheeler Avatar answered Oct 13 '22 18:10

Nathan Wheeler