SQL Can I use an alias where?

I tried the following SQL on this example playground 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 an answer. It works if I use CustomerNameinstead of an alias.

Is this a test page error on the playground or is it just not possible?

+4
source share
4 answers

The offer WHEREis evaluated before a choice. Therefore, the where clause does not know about the aliases you are using.

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 an alias in the where clause, you can use a subquery or CTE (overkill and can lead to a slower query):

SELECT * from (
    SELECT CustomerID AS Id, CustomerName AS Customer
    FROM Customers
) t WHERE Customer = "Alfreds Futterkiste";
+3

:

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

- :

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

c

where, where .

+3

Awful, but can be convenient in larger and more complex requests.

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

WHERE Customer = "Alfreds Futterkiste";
+3
source

No, you cannot reference a column alias in a WHERE clause.

+1
source

Source: https://habr.com/ru/post/1676403/


All Articles