PostgreSQL: using a calculated column in the same query

user1146150 picture user1146150 · Jan 12, 2012 · Viewed 53.7k times · Source

I am having trouble using a calculated column in postgres. A similar code which works in SQL is given below, is it possible to recreate this in PostgreSQL?

select cost_1, quantity_1, cost_2, quantity_2, 
      (cost_1 * quantity_1) as total_1,
      (cost_2 * quantity_2) as total_2,
      (calculated total_1 + calculated total_2) as total_3
from data;

In PostgreSQL a similar code returns the error that:

the column total_1 and total_2 do not exist.

Answer

a_horse_with_no_name picture a_horse_with_no_name · Jan 12, 2012

You need to wrap the SELECT statement into a derived table in order to be able to access the column alias:

select cost1,
       quantity_1,
       cost_2,
       quantity_2
       total_1 + total_2 as total_3
from (
    select cost_1, 
           quantity_1, 
           cost_2, 
           quantity_2, 
           (cost_1 * quantity_1) as total_1,
           (cost_2 * quantity_2) as total_2
    from data
) t

There won't be any performance penalty on that.

(I'm really surprised that your original SQL statement runs at all in a DBMS)