Using an Alias in SQL Calculations

MysqlSqlDatabaseSyntax

Mysql Problem Overview


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.

Mysql Solutions


Solution 1 - Mysql

Simply wrap your reused alias with (SELECT alias) :

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

Solution 2 - Mysql

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

Solution 3 - Mysql

Aliases in sql are not like variables in a programming language. 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.

Or you could use a VIEW if your formulas are generally fixed

CREATE VIEW table10 AS SELECT 10 AS my_num FROM table;
SELECT my_num * 5 AS another_number FROM table10;

I believe that will be slightly faster than using a derived query but it probably depends a lot on your real query.

Or you could just duplicate the work:

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

Which might be convenient in something like php/perl:

my $my_num = 10;
my $query = "SELECT $my_num AS my_num, $my_num * 5 AS another_number FROM table";

Solution 4 - Mysql

``Another option is to use the APPLY operator

SELECT my_num, my_num*5 AS another_number
FROM table
CROSS APPLY 
(SELECT 5 AS my_num) X

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTom RossiView Question on Stackoverflow
Solution 1 - MysqlzessxView Answer on Stackoverflow
Solution 2 - MysqlRubens FariasView Answer on Stackoverflow
Solution 3 - MysqlRob Van DamView Answer on Stackoverflow
Solution 4 - MysqlFreddy Jose Chirinos MorònView Answer on Stackoverflow