Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

column aliases in postgres for calculated values

I tried to uses aliases in postgres for this query, but postgres stops and complains that ERROR: column "subtotal" does not exist

SELECT SUM(price) AS subtotal, 
       subtotal * 3.0 AS fees,
       (subtotal + fees) AS total
  FROM cart

You cannot use aliases as part of your next column?

like image 454
dubreakkk Avatar asked May 20 '10 00:05

dubreakkk


People also ask

Can we use alias in calculation in SQL?

Using the CALCULATED Keyword with Column AliasesThe CALCULATED keyword enables PROC SQL users to reference column aliases that are associated with calculated expressions. The column alias referenced by the CALCULATED keyword can be in the WHERE clause, ON clause, GROUP BY clause, HAVING clause, or ORDER BY clause.

Can you do calculations in PostgreSQL?

So, the short answer is that you can't, and that is by design. The notable exception to this is Microsoft Access, where you can indeed use calculations in subsequent columns and WHERE clauses.

Why would you column use aliases?

SQL aliases are used to give a table, or a column in a table, a temporary name. Aliases are often used to make column names more readable. An alias only exists for the duration of that query.

Can column alias name be used for WHERE clause?

We cannot use a column alias with WHERE and HAVING clauses.


1 Answers

No, you can not re-use a column alias within the same SQL statement - use:

SELECT SUM(t.price) AS subtotal,
       SUM(t.price) * 3.0 AS fees,
       SUM(t.price + fees) AS total
  FROM CART t

You can reference the column alias in the ORDER BY clause, some databases also support referencing in the GROUP BY and HAVING clauses.

like image 170
OMG Ponies Avatar answered Oct 27 '22 19:10

OMG Ponies