MySQL – Create New Field Based on SUM

MySQLselectsum

I'm trying to create a new field based in another (sum field)

SELECT sum(price) AS old_price,
   old_price+100 AS total_price
FROM sales

This returns Unknown column 'old_price' in 'field list'

sum is just a example, my real issue is to use with a select inside this field

What am I doing wrong?

Thanks.

–edit
I've used variables to reuse the alias, updated code:

SELECT @old_price := sum(price) AS old_price,
   @old_price+100 AS total_price
FROM sales

If you think that it is not a good practice, tell me.

Best Answer

You didn't do anything wrong. Unfortunately, referencing calculated columns in the field list is just not possible.

The usual workaround is to use self joins, joins to subselects or anything like that. But that would only qualify for more complex calculations. In your case, the solution would be to just write it the way Ryan mentioned, even if that turns the stomach of every programmer.