I have a table of names and addresses, which includes a postcode column. I want to strip the spaces from the postcodes and select any that match a particular pattern. I\'m tryin
Don't use the alias (P
) in your WHERE
clause directly.
You can either use the same REPLACE
logic again in the WHERE
clause:
SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
WHERE Replace(Postcode, ' ', '') LIKE 'NW101%'
Or use an aliased sub query as described in Nick's answers.
To expand on Oded's answer, your conceptual model needs a slight adjustment here. Aliasing of column names (AS
clauses in the SELECT
list) happens very late in the processing of a SELECT
, which is why alias names are not available to WHERE
clauses. In fact, the only thing that happens after column aliasing is sorting, which is why (to quote the docs on SELECT
):
column_alias
can be used in an ORDER BY clause. However, it cannot be used in aWHERE
,GROUP BY
, orHAVING
clause.
If you have a convoluted expression in the SELECT
list, you may be worried about it 'being evaluated twice' when it appears in the SELECT
list and (say) a WHERE
clause - however, the query engine is clever enough to work out what's going on. If you want to avoid having the expression appear twice in your query, you can do something like
SELECT c1, c2, c3, expr1
FROM
( SELECT c1, c2, c3, some_complicated_expression AS expr1 ) inner
WHERE expr1 = condition
which avoids some_complicated_expression
physically appearing twice.
This will work:
SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
WHERE Replace(Postcode, ' ', '') LIKE 'NW101%'
You can reference is that way if you wrap the query, like this:
SELECT P
FROM (SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts) innertable
WHERE P LIKE 'NW101%'
Be sure to give the wrapped select an alias, even unused (SQL Server doesn't allow it without one IIRC)
You have to repeat your expression everywhere you want to use it:
SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
WHERE Replace(Postcode, ' ', '') LIKE 'NW101%'
or you can make it a subquery
select P
from (
SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
) t
WHERE P LIKE 'NW101%'
You are creating an alias P
and later in the where
clause you are using the same, that is what is creating the problem. Don't use P
in where
, try this instead:
SELECT Replace(Postcode, ' ', '') AS P FROM Contacts
WHERE Postcode LIKE 'NW101%'