Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering on an alias in mysql

Why doesn't the following query work? Mysql complains about z - can't I use an alias in the WHERE clause?

SELECT x + y AS z, t.*  FROM t
WHERE 
x = 1 and
z = 2

The error that I get is:

Error Code : 1054
Unknown column 'z' in 'where clause'
like image 531
ripper234 Avatar asked Nov 27 '10 09:11

ripper234


People also ask

Can I use alias in WHERE clause MySQL?

You can only use column aliases in GROUP BY, ORDER BY, or HAVING clauses. Standard SQL doesn't allow you to refer to a column alias in a WHERE clause. This restriction is imposed because when the WHERE code is executed, the column value may not yet be determined.

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.

Can we use alias in GROUP BY clause?

Column aliases can be used with GROUP BY and ORDER BY clauses. We cannot use a column alias with WHERE and HAVING clauses.


1 Answers

http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html

Standard SQL disallows references to column aliases in a WHERE clause. This restriction is imposed because when the WHERE clause is evaluated, the column value may not yet have been determined. For example, the following query is illegal:

SELECT id, COUNT(*) AS cnt FROM tbl_name WHERE cnt > 0 GROUP BY id;

Try this, instead:

SELECT x + y AS z, t.* FROM t WHERE x = 1 HAVING z = 2;
like image 108
NSSec Avatar answered Sep 20 '22 01:09

NSSec