MySQL alias, variables and the WHERE clause

What a nice morning i had remembering that you cannot reference an ALIAS or a variable in a WHERE clause. So for anyone else that has a memory like mine (i'm jealous of fish put it that way)

standard SQL doesn't allow you to refer to a column alias in a where cause. Which make total sense (now) as the column value is most likely not determined at time of execution. So....

SELECT
@total := date_add(datefield, INTERVAL 1 YEAR) AS newDate
FROM
mytable
#WHERE
# @total > now() /*Invalid*/
#WHERE
# newDate > now() /*Invalid*/

Posted: 07-Jul-2005

View: 19590

Permalink: here

Comments

SELECT
@total := date_add(datefield, INTERVAL 1 YEAR) AS newDate
FROM
mytable
HAVING @total > now()

#1 Mike Holloway
29/Nov/06 12:28 PM

Great help for me. Thanks Andy for the question, and thanks Mike for the answer! ;)

#2 Marcio
21/Jul/07 2:45 PM

Ya, Thanks Mike!

#3 Kenny Saunders
17/Feb/08 9:02 PM

Thanks for the tip... Now... How would you accomplish this?

#4 David
14/Apr/08 11:30 AM

I was trying to figure out why my query wouldn't work. Thanks for posting this.

#5 ill
25/Apr/08 5:49 PM

i think you meant...

#WHERE
# @total > now() /*valid*/
#WHERE
# newDate > now() /*Invalid*/

also what is the colon for? :=
SELECT
@total := date_add(dat.....

#6 cheeto
20/May/08 9:02 AM

cheeto wrote:
> i think you meant...
> #WHERE
> # @total > now() /*valid*/

No, I don't believe using a variable there is a truly valid solution. Variables change values when you least expect them to. You should only use variables as a way to store information *between* queries, not *within* a query, AFAIK.

A solution I've found elsewhere is that you can use the column alias in your HAVING clause. (http://dev.mysql.com/doc/refman/5.0/en/problems-wi...)

#7 Richard Donkin
30/Aug/08 12:53 AM

Hey,
You can use HAVING instead of WHERE in this case, it works perfectly fine and the difference is :

[quote]
The WHERE statement is executed to determine which rows should be included in the GROUP BY part, whereas HAVING is used to decide which rows from the result set should be used.
[/quote]

[refrence]
http://dev.mysql.com/doc/refman/5.0/en/problems-wi...
[/refrence]

Hope it helps,
MajiD

#8 MajiD Fatemian
15/Nov/08 5:02 PM

What MajiD said, I couldn't use variables nor aliases in the WHERE clause either, but the HAVING clause worked perfectly.

#9 Ennio Wolsink
30/Sep/09 1:53 PM

Yeah, this is what HAVING is for. You can use it without a GROUP BY clause as long as the alias you're using came from an aggregate function.

http://dev.mysql.com/doc/refman/5.0/en/problems-wi...

#10 Michael
19/Feb/10 7:18 PM