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?
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.
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.
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.
We cannot use a column alias with WHERE and HAVING clauses.
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.
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