Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Is it possible to use alias in where? [duplicate]

Tags:

sql

I tried the following SQL on this example playground page from W3Schools.

SELECT CustomerID AS Id, CustomerName AS Customer
FROM Customers
WHERE Customer="Alfreds Futterkiste";

But I get No value given for one or more required parameters. as response. It works if I use CustomerName instead of the alias.

Is this a fail of the playground test page or is it just not possible?

like image 358
Black Avatar asked Dec 23 '22 18:12

Black


1 Answers

The WHERE clause is evaluated before select. Hence the where clause is not aware of the aliases you used.

So you need to use the original column name:

SELECT CustomerID AS Id, CustomerName AS Customer
FROM Customers
WHERE CustomerName="Alfreds Futterkiste";

If you must use alias in the where clause, you may use subquery or CTE (an overkill and may result in slower query):

SELECT * from (
    SELECT CustomerID AS Id, CustomerName AS Customer
    FROM Customers
) t WHERE Customer = "Alfreds Futterkiste";
like image 136
Gurwinder Singh Avatar answered Jan 03 '23 19:01

Gurwinder Singh