4

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?

Black
  • 18,150
  • 39
  • 158
  • 271

4 Answers4

3

Looking at your code:

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

To alias the customer table you can do something like:

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

Where c is now the alias for Customers

It is not possible to use a column alias in a where clause because the where clause executes BEFORE the select.

RandomUs1r
  • 4,010
  • 1
  • 24
  • 44
3

Ugly, but can be convenient in larger, more complex queries

SELECT * FROM
(SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers) as A

WHERE Customer = "Alfreds Futterkiste";
airstrike
  • 2,270
  • 1
  • 25
  • 26
  • 1
    Especially if you are going to need that reference more than once in the rest of the query – HLGEM May 04 '17 at 18:44
3

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";
Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
1

No you can't reference the column alias in the WHERE clause.

Dessma
  • 599
  • 3
  • 11