Click to search Andy Jarrett.co.uk RSS feed

Loading Twitter

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*/

Comments Comments (10) | Print Print | Send Send | 16745 Views

SELECT
@total := date_add(datefield, INTERVAL 1 YEAR) AS newDate
FROM
mytable
HAVING @total > now()
Marcio's Gravatar Posted By Marcio @ 7/21/07 2:45 PM
Great help for me. Thanks Andy for the question, and thanks Mike for the answer! ;)
Ya, Thanks Mike!
David's Gravatar Posted By David @ 4/14/08 11:30 AM
Thanks for the tip... Now... How would you accomplish this?
ill's Gravatar Posted By ill @ 4/25/08 5:49 PM
I was trying to figure out why my query wouldn't work. Thanks for posting this.
cheeto's Gravatar Posted By cheeto @ 5/20/08 9:02 AM
i think you meant...

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

also what is the colon for? :=
SELECT
@total := date_add(dat.....
Richard Donkin's Gravatar Posted By Richard Donkin @ 8/30/08 12:53 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...)
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
What MajiD said, I couldn't use variables nor aliases in the WHERE clause either, but the HAVING clause worked perfectly.
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...
BlogCFC by Raymond Camden + Twitter @AndyJ + ColdFusion jobs + Contact Me + Snippets/Downloads + RSS .