Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an Alias in SQL Calculations

Why won't this query work?

SELECT 10 AS my_num, my_num*5 AS another_number FROM table 

In this example, I'm trying to use the my_num alias in other calculations. This results in unknown column "my_num"

This is a simplified version of what I am trying to do, but basically I would like to use an alias to make other calculations. My calculations are much more complicated and thats why it would be nice to alias it since I repeat it several times different ways.

like image 787
Tom Rossi Avatar asked Jan 16 '10 13:01

Tom Rossi


People also ask

Can we use alias in calculation in SQL?

Aliases can only be referenced again at certain points (particularly in GROUP BY and HAVING clauses). But you can't reuse an alias in the SELECT clause. So you can use a derived query (such as suggested by Rubens Farias) which lets you basically rename your columns and/or name any computed columns.

What is true about a column alias is useful with calculations?

Allows you to provide more readable names to the column headers when they're presented in the results. Allows client applications to refer to a calculated field by name where no column name exists. Allows you to reduce code and make your queries more concise.

When would you use an alias in SQL?

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. An alias is created with the AS keyword.

What is the benefit of using an alias in MySQL?

Advantages of MySQL AliasesIt makes the column or table name more readable. It is useful when you use the function in the query. It can also allow us to combines two or more columns. It is also useful when the column names are big or not readable.


2 Answers

Simply wrap your reused alias with (SELECT alias) :

SELECT 10 AS my_num,         (SELECT my_num) * 5 AS another_number FROM table 
like image 122
zessx Avatar answered Sep 28 '22 10:09

zessx


You'll need to use a subselect to use that aliases that way

SELECT my_num*5 AS another_number FROM (     SELECT 10 AS my_num FROM table ) x 
like image 33
Rubens Farias Avatar answered Sep 28 '22 09:09

Rubens Farias