tags:

views:

4555

answers:

13

I have a simple query:

SELECT u_name AS user_name FROM users WHERE user_name = "john";

I get "Unknown Column 'user_name' in where clause". Can I not refer to 'user_name' in other parts of the statement even after select 'u_name as user_name'?

+2  A: 

No you cannot. user_name is doesn't exist until return time.

Jarrett Meyer
+4  A: 

No you need to select it with correct name. If you gave the table you select from an alias you can use that though.

Per Hornshøj-Schierbeck
+3  A: 

corrected:

SELECT u_name AS user_name FROM users WHERE u_name = 'john';
Steven A. Lowe
+8  A: 

SQL is evaluated backwards, from right to left. So the where clause is parsed and evaluate prior to the select clause. Because of this the aliasing of u_name to user_name as not yet occurred.

dacracot
Rather than "backwards" I think it makes more sense to say "inside out"
Joe Philllips
+3  A: 

Either:

SELECT u_name AS user_name
FROM   users
WHERE  u_name = "john";

or:

SELECT user_name
from
(
SELECT u_name AS user_name
FROM   users
)
WHERE  u_name = "john";

The latter ought to be the same as the former if the RDBMS supports predicate pushing into the in-line view.

David Aldridge
+5  A: 
select u_name as user_name from users where u_name = "john";

Think of it like this, your where clause evaluates first, to determine which rows (or joined rows) need to be returned. Once the where clause is executed, the select clause runs for it.

To put it a better way, imagine this:

select distinct(u_name) as user_name from users where u_name = "john";

You can't reference the first half without the second. Where always gets evaluated first, then the select clause.

Mark S.
A: 

While you can alias your tables within your query (i.e., "SELECT u.username FROM users u;"), you have to use the actual names of the columns you're referencing. AS only impacts how the fields are returned.

Blumer
A: 

Not as far as I know in MS-SQL 2000/5. I've fallen foul of this in the past.

Cirieno
+2  A: 

See the following MySQL manual page: http://dev.mysql.com/doc/refman/5.0/en/select.html

"A select_expr can be given an alias using AS alias_name. The alias is used as the expression's column name and can be used in GROUP BY, ORDER BY, or HAVING clauses."

Paul Dixon
+1  A: 

SELECT user_name FROM ( SELECT name AS user_name FROM users ) AS test WHERE user_name = "john"

A: 

Unknown Column in where clause Caused by lines 1 and 2 and resolved by line 3

  1. $sql = "SELECT * FROM users WHERE username =".$userName;
  2. $sql = "SELECT * FROM users WHERE username =".$userName."";
  3. $sql = "SELECT * FROM users WHERE username ='".$userName."'";

hope this helps

oliyide
A: 

very good Foripepe!

You save my live!

Thanks!

From Brazil

Leandro Wodonos
A: 

What about: SELECT u_name AS user_name FROM users HAVING user_name = "john";

Septimus