Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - SELECT AS in WHERE

Tags:

sql

select

mysql

For some reason, this doesn't work:

select substring(rating, instr(rating,',') +1, +2) as val from users where val = '15'; 

It gives this error:

ERROR 1054 (42S22): Unknown column 'val' in 'where clause'

How do I do it then?

like image 667
Martin Avatar asked Jan 19 '13 11:01

Martin


People also ask

Can we use SELECT in WHERE clause?

You should use the WHERE clause to filter the records and fetching only the necessary records. The WHERE clause is not only used in the SELECT statement, but it is also used in the UPDATE, DELETE statement, etc., which we would examine in the subsequent chapters.

WHERE clause is used in MySQL for?

The WHERE clause is used to filter records. It is used to extract only those records that fulfill a specified condition.

How do you use WHERE in SELECT?

WHERE clause Syntax. The basic syntax for the WHERE clause when used in a MySQL SELECT WHERE statement is as follows. “WHERE” is the keyword that restricts our select query result set and “condition” is the filter to be applied on the results. The filter could be a range, single value or sub query.

What is SELECT * from in MySQL?

The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set.


2 Answers

First, you cannot use ALIAS on the WHERE clause. You shoul be using the column,

SELECT SUBSTRING(rating, INSTR(rating,',') +1, +2) AS val  FROM   users  WHERE  SUBSTRING(rating, INSTR(rating,',') +1, +2) = '15' 

The reason is as follows: the order of operation is SQL,

  • FROM clause
  • WHERE clause
  • GROUP BY clause
  • HAVING clause
  • SELECT clause
  • ORDER BY clause

the ALIAS takes place on the SELECT clause which is before the WHERE clause.

if you really want to use the alias, wrap it in a subquery,

SELECT * FROM     (         SELECT SUBSTRING(rating, INSTR(rating,',') +1, +2) AS val          FROM   users     ) s WHERE   val  = '15' 
like image 68
John Woo Avatar answered Sep 19 '22 03:09

John Woo


You sure can with MySQL, please see below, just tested this and it works fine:

Select substring(rating, instr(rating,',') +1, +2) as val  From users  Having val = '15'; 

You can also do things like "having val is null" etc.

With ALIASes you can't use WHERE, but using HAVING does the trick.

H

like image 41
Heider Sati Avatar answered Sep 21 '22 03:09

Heider Sati