Why can't I use filter my WHERE clause on a CASE statement column in SQL Server? [duplicate] Why can't I use filter my WHERE clause on a CASE statement column in SQL Server? [duplicate] sql-server sql-server

Why can't I use filter my WHERE clause on a CASE statement column in SQL Server? [duplicate]


WHERE is processed before SELECT. It doesn't know what DerviedRegion is at that point. I'd recommend using a NOT IN in this case to exclude the list of countries. However, if you really want to use your CASE you could do something like this

SELECT *FROM(    SELECT                CASE             WHEN m.Country IN ('CANADA', 'UNITED STATES', 'USA', 'MEXICO') THEN 'NA'             WHEN m.Country IN ('BRAZIL') THEN 'JD2'             WHEN m.Country IN ('NZ', 'NEW ZEALAND', 'AUSTRALIA', 'AUSTRALASIA') THEN 'ANZ'             ELSE 'Unknown'         END AS DerivedRegion,        m.ID,        m.[Account Name],         m.[Display Name],         m.[Last Name],         m.[First Name]    FROM dbo.Users AS m) AS xWHERE x.DerivedRegion = 'Unknown'

Check out MSDN and scroll down to Logical Processing Order of the SELECT statement to see the order in which a query is processed.


You should repeat all in´s in the where clause:

SELECT            CASE         WHEN m.Country IN ('CANADA', 'UNITED STATES', 'USA', 'MEXICO') THEN 'NA'         WHEN m.Country IN ('BRAZIL') THEN 'JD2'         WHEN m.Country IN ('NZ', 'NEW ZEALAND', 'AUSTRALIA', 'AUSTRALASIA') THEN 'ANZ'         ELSE 'Unknown'     END AS DerivedRegion,    m.ID,    m.[Account Name],     m.[Display Name],     m.[Last Name],     m.[First Name]FROM     dbo.Users AS mWHERE     m.Country NOT IN ('CANADA', 'UNITED STATES', 'USA', 'MEXICO', 'BRAZIL', 'NZ', 'NEW ZEALAND', 'AUSTRALIA', 'AUSTRALASIA')

Other solution could be: save the query as view without the where-clause (eg "myview") and then select from the view:

SELECT * FROM myview WHERE DerivedRegion = 'Unknown'

In this case, SQL server can better plan the execution.